text:
Q: What is a coarse and fine grid search? I was reading this answer
Efficient (and well explained) implementation of a Quadtree for 2D collision detection
and encountered this paragraph

All right, so actually quadtrees are not my favorite data structure for this purpose. I tend to prefer a grid hierarchy, like a coarse grid for the world, a finer grid for a region, and an even finer grid for a sub-region (3 fixed levels of dense grids, and no trees involved), with row-based optimizations so that a row that has no entities in it will be deallocated and turned into a null pointer, and likewise completely empty regions or sub-regions turned into nulls. While this simple implementation of the quadtree running in one thread can handle 100k agents on my i7 at 60+ FPS, I've implemented grids that can handle a couple million agents bouncing off each other every frame on older hardware (an i3). Also I always liked how grids made it very easy to predict how much memory they'll require, since they don't subdivide cells. But I'll try to cover how to implement a reasonably efficient quadtree.

This type of grid seems intuitive, it sort of sounds like a "N-order" grid, where instead of 4 child nodes, you have N child nodes per parent. N^3 can go much further than 4^3, which allows better precision with potentially (I guess) less branching (since there are many less nodes to branch).
I'm a little puzzled because I would intuitively use a single, or maybe 3 std::map with the proper < operator(), to reduce its memory footprint, but I'm not sure it would be so fast, since querying an AABB would mean stacking several accesses that are O(log n).
What exactly are those row-based optimizations he is talking about? Is this type of grid search common?
I have some understanding of a z order curve, and I'm not entirely satisfied with a quadtree.

A: It's my own quote. But that's based on a common pattern I encountered in my personal experience. Also, terms like "parent" and "child" are ones I'd largely discard when talking about grids. You just got a big 2-dimensional or N-dimensional table/matrix storing stuff. There's not really a hierarchy involved whatsoever -- these data structures are more comparable to arrays than trees.
"Coarse" and "Fine"
On "coarse" and "fine", what I meant there is that "coarse" search queries tend to be cheaper but give more false positives. A coarser grid would be one that is lower in grid resolution (fewer, larger cells). Coarse searches may involve traversing/searching fewer and larger grid cells. For example, say we want to see if an element intersects a point/dot in a gigantic cell (imagine just a 1x1 grid storing everything in the simulation). If the dot intersects the cell, we may get a whole lot of elements returned in that cell but maybe only one or none of them actually intersect the dot.
So a "coarse" query is broad and simple but not very precise at narrowing down the list of candidates (or "suspects"). It may return too many results and still leave a whole lot of processing required left to do to narrow down what actually intersects the search parameter*.

It's like in those detective shows when they search a database for a
  possible killer, putting in "white male" might not require much
  processing to list the results but might give way too many results to
  properly narrow down the suspects. "Fine" would be the opposite and might require more processing of the database but narrow down the result to just one suspect.
  This is a crude and flawed analogy but I hope it helps.

Often the key to broadly optimizing spatial indices before we get into things like memory optimizations whether we're talking spatial hashes or quadtrees is to find a nice balance between "coarse" and "fine". Too "fine" and we might spend too much time traversing the data structure (searching many small cells in a uniform grid, or spending too much time in tree traversal for adaptive grids like quadtrees). Too "coarse" and the spatial index might give back too many results to significantly reduce the amount of time required for further processing. For spatial hashes (a data structure I don't personally like very much but they're very popular in gamedev), there's often a lot of thought and experimentation and measuring involved in determining an optimal cell size to use.
With uniform NxM grids, how "coarse" or "fine" they are (big or small cells and high or low grid resolution) not only impacts search times for a query but can also impact insertion and removal times if the elements are larger than a point. If the grid is too fine, a single large or medium-sized element may have to be inserted into many tiny cells and removed from many tiny cells, using lots of extra memory and processing. If it's too coarse, the element may only have to be inserted and removed to/from one large cell but at costs to the data structure's ability to narrow down the number of candidates returned from a search query to a minimum. Without care, going too "fine/granular" can become very bottlenecky in practice and a developer might find his grid structure using gigabytes of RAM for a modest input size. With tree variants like quadtrees, a similar thing can happen if the maximum allowed tree depth is too high a value causing explosive memory use and processing when the leaf nodes of the quadtree store the tiniest cell sizes (we can even start running into floating-point precision bugs that wreck performance if the cells are allowed to be subdivided to too small a size in the tree).
The essence of accelerating performance with spatial indices is often this sort of balancing act. For example, we typically don't want to apply frustum culling to individual polygons being rendered in computer graphics because that's typically not only redundant with what the hardware already does at the clipping stage, but it's also too "fine/granular" and requires too much processing on its own compared to the time required to just request to render one or more polygons. But we might net huge performance improvements with something a bit "coarser", like applying frustum culling to an entire creature or space ship (an entire model/mesh), allowing us to avoid requesting to render many polygons at once with a single test. So I often use the terms, "coarse" and "fine/granular" frequently in these sorts of discussions (until I find better terminology that more people can easily understand).
Uniform vs. Adaptive Grid
You can think of a quadtree as an "adaptive" grid with adaptive grid cell sizes arranged hierarchically (working from "coarse' to "fine" as we drill down from root to leaf in a single smart and adaptive data structure) as opposed to a simple NxM "uniform" grid.
The adaptive nature of the tree-based structures is very smart and can handle a broad range of use cases (although typically requiring some fiddling of maximum tree depth and/or minimum cell size allowed and possibly how many maximum elements are stored in a cell/node before it subdivides). However, it can be more difficult to optimize tree data structures because the hierarchical nature doesn't lend itself so easily to the kind of contiguous memory layout that our hardware and memory hierarchy is so well-suited to traverse. So very often I find data structures that don't involve trees to be easier to optimize in the same sense that optimizing a hash table might be simpler than optimizing a red-black tree, especially when we can anticipate a lot about the type of data we're going to be storing in advance.

Another reason I tend to favor simpler, more contiguous data structures in lots of contexts is that the performance requirements of a realtime simulation often want not just fast frame rates, but consistent and predictable frame rates. The consistency is important because even if a video game has very high frame rates for most of the game but some part of the game causes the frame rates to drop substantially for even a brief period of time, the player may die and game over as a result of it. It was often very important in my case to avoid these types of scenarios and have data structures largely absent pathological worst-case performance scenarios. In general, I find it easier to predict the performance characteristics of lots of simpler data structures that don't involve an adaptive hierarchy and are kind of on the "dumber" side. Very often I find the consistency and predictability of frame rates to be roughly tied to how easily I can predict the data structure's overall memory usage and how stable that is. If the memory usage is wildly unpredictable and sporadic, I often (not always, but often) find the frame rates will likewise be sporadic.

So I often find better results using grids personally, but if it's tricky to determine a single optimal cell size to use for the grid in a particular simulation context, I just use multiple instances of them: one instance with larger cell sizes for "coarse" searches (say 10x10), one with smaller ones for "finer" searches (say 100x100), and maybe even one with even smaller cells for the "finest" searches (say 1000x1000). If no results are returned in the coarse search, then I don't proceed with the finer searches. I get some balance of the benefits of quadtrees and grids this way.
What I did when I used these types of representations in the past is not to store a single element in all three grid instances. That would triple the memory use of an element entry/node into these structures. Instead, what I did was insert the indices of the occupied cells of the finer grids into the coarser grids, as there are typically far fewer occupied cells than there are a total number of elements in the simulation. Only the finest, highest-resolution grid with the smallest cell sizes would store the element. The cells in the finest grid are analogous to the leaf nodes of a quadtree.
The "loose-tight double grid" as I'm calling it in one of the answers to that question is an expansion on this multi-grid idea. The difference is that the finer grid is actually loose and has cell sizes that expand and shrink based on the elements inserted to it, always guaranteeing that a single element, no matter how large or small, needs only be inserted to one cell in the grid. The coarser grid stores the occupied cells of the finer grid leading to two constant-time queries (one in the coarser tight grid, another into the finer loose grid) to return an element list of potential candidates matching the search parameter. It also has the most stable and predictable memory use (not necessarily the minimal memory use because the fine/loose cells require storing an axis-aligned bounding box that expands/shrinks which adds another 16 bytes or so to a cell) and corresponding stable frame rates because one element is always inserted to one cell and doesn't take any additional memory required to store it besides its own element data with the exception of when its insertion causes a loose cell to expand to the point where it has to be inserted to additional cells in the coarser grid (which should be a fairly rare-case scenario).
Multiple Grids For Other Purposes

I'm a little puzzled because I would intuitively use a single, or maybe 3 std::map with the proper operator(), to reduce its memory footprint, but I'm not sure it would be so fast, since querying an AABB would mean stacking several accesses that are O(log n).

I think that's an intuition many of us have and also probably a subconscious desire to just lean on one solution for everything because programming can get quite tedious and repetitive and it'd be ideal to just implement something once and reuse it for everything: a "one-size-fits-all" t-shirt. But a one-sized-fits-all shirt can be poorly tailored to fit our very broad and muscular programmer bodies*. So sometimes it helps to use the analogy of a small, medium, and large size.

*

*This is a very possibly poor attempt at humor on my part to make my long-winded texts less boring to read.

For example, if you are using std::map for something like a spatial hash, then there can be a lot of thought and fiddling around trying to find an optimal cell size. In a video game, one might compromise with something like making the cell size relative to the size of your average human in the game (perhaps a bit smaller or bigger), since lots of the models/sprites in the game might be designed for human use. But it might get very fiddly and be very sub-optimal for teeny things and very sub-optimal for gigantic things. In that case, we might do well to resist our intuitions and desires to just use one solution and use multiple (it could still be the same code but just multiple instances of the same class instance for the data structure constructed with varying parameters).
As for the overhead of searching multiple data structures instead of a single one, that's something best measured and it's worth remembering that the input sizes of each container will be smaller as a result, reducing the cost of each search and very possibly improve locality of reference. It might exceed the benefits in a hierarchical structure that requires logarithmic search times like std::map (or not, best to just measure and compare), but I tend to use more data structures which do this in constant-time (grids or hash tables). In my cases, I find the benefits far exceeding the additional cost of requiring multiple searches to do a single query, especially when the element sizes vary radically or I want some basic thing resembling a hierarchy with 2 or more NxM grids that range from "coarse" to "fine".
Row-Based Optimizations
As for "row-based optimizations", that's very specific to uniform fixed-sized grids and not trees. It refers to using a separate variable-sized list/container per row instead of a single one for the entire grid. Aside from potentially reducing memory use for empty rows that just turn into nulls without requiring an allocated memory block, it can save on lots of processing and improve memory access patterns.
If we store a single list for the entire grid, then we have to constantly insert and remove from that one shared list as elements move around, particles are born, etc. That could lead to more heap allocations/deallocations growing and shrinking the container but also increases the average memory stride to get from one element in that list to the next which will tend to translate to more cache misses as a result of more irrelevant data being loaded into a cache line. Also these days we have so many cores so having a single shared container for the entire grid may reduce the ability to process the grid in parallel (ex: searching one row while simultaneously inserting to another). It can also lead to more net memory use for the structure since if we use a contiguous sequence like std::vector or ArrayList, those can often store the memory capacity of as many as twice the elements required to reduce the time of insertions to amortized constant time by minimizing the need to reallocate and copy the former elements in linear-time by keeping excess capacity.
By associating a separate medium-sized container per grid row or per column instead of gigantic one for the entire grid, we can mitigate these costs in some cases*.

*

*This is the type of thing you definitely measure before and after though to make sure it actually improves overall frame rates, and probably attempt in response to a first attempt storing a single list for the entire grid revealing many non-compulsory cache misses in the profiler.

This might beg the question of why we don't use a separate teeny list container for every single cell in the grid. It's a balancing act. If we store that many containers (ex: a million instances of std::vector for a 1000x1000 grid possibly storing very few or no elements each), it would allow maximum parallelism and minimize the stride to get from one element in a cell to the next one in the cell, but that can be quite explosive in memory use and introduce a lot of extra processing and heap overhead.
Especially in my case, my finest grids might store a million cells or more, but I only require 4 bytes per cell. A variable-sized sequence per cell would typically explode to at least something like 24 bytes or more (typically far more) per cell on 64-bit architectures to store the container data (typically a pointer and a couple of extra integers, or three pointers on top of the heap-allocated memory block), but on top of that, every single element inserted to an empty cell may require a heap allocation and compulsory cache miss and page fault and very frequently due to the lack of temporal locality. So I find the balance and sweet spot to be one list container per row typically among my best-measured implementations.
I use what I call a "singly-linked array list" to store elements in a grid row and allow constant-time insertions and removals while still allowing some degree of spatial locality with lots of elements being contiguous. It can be described like this:
struct GridRow
{
     struct Node
     {
         // Element data
         ...

         // Stores the index into the 'nodes' array of the next element
         // in the cell or the next removed element. -1 indicates end of
         // list.
         int next = -1;
     };

     // Stores all the nodes in the row.
     std::vector<Node> nodes;

     // Stores the index of the first removed element or -1
     // if there are no removed elements.
     int free_element = -1;
};

This combines some of the benefits of a linked list using a free list allocator but without the need to manage separate allocator and data structure implementations which I find to be too generic and unwieldy for my purposes. Furthermore, doing it this way allows us to halve the size of a pointer down to a 32-bit array index on 64-bit architectures which I find to be a big measured win in my use cases when the alignment requirements of the element data combined with the 32-bit index don't require an additional 32-bits of padding for the class/struct which is frequently the case for me since I often use 32-bit or smaller integers and 32-bit single-precision floating-point or 16-bit half-floats.
Unorthodox?
On this question:

Is this type of grid search common?

I am not sure! I tend to struggle a bit with terminology and I'll have to ask people's forgiveness and patience in communication. I started programming from early childhood in the 1980s before the internet was widespread, so I came to rely on inventing a lot of my own techniques and using my own crude terminology as a result. I got my degree in computer science about a decade and a half later when I reached my 20s and corrected some of my terminology and misconceptions but I've had many years just rolling my own solutions. So I am often not sure if other people have come across some of the same solutions or not, and if there are formal names and terms for them or not.
That makes communication with other programmers difficult and very frustrating for both of us at times and I have to ask for a lot of patience to explain what I have in mind. I've made it a habit in meetings to always start off showing something with very promising results which tends to make people more patient with my crude and long-winded explanations of how they work. They tend to give my ideas much more of a chance if I start off by showing results, but I'm often very frustrated with the orthodoxy and dogmatism that can be prevalent in this industry that can sometimes prioritize concepts far more than execution and actual results. I'm a pragmatist at heart so I don't think in terms of "what is the best data structure?" I think in terms of what we can effectively implement personally given our strengths and weaknesses and what is intuitive and counter-intuitive to us and I'm willing to endlessly compromise on the purity of concepts in favor of a simpler and less problematic execution. I just like good, reliable solutions that roll naturally off our fingertips no matter how orthodox or unorthodox they may be, but a lot of my methods may be unorthodox as a result (or not and I might just have yet to find people who have done the same things). I've found this site useful at rare times in finding peers who are like, "Oh, I've done that too! I found the best results if we do this [...]" or someone pointing out like, "What you are proposing is called [...]."
In performance-critical contexts, I kind of let the profiler come up with the data structure for me, crudely speaking. That is to say, I'll come up with some quick first draft (typically very orthodox) and measure it with the profiler and let the profiler's results give me ideas for a second draft until I converge to something both simple and performant and appropriately scalable for the requirements (which may become pretty unorthodox along the way). I'm very happy to abandon lots of ideas since I figure we have to weed through a lot of bad ideas in a process of elimination to come up with a good one, so I tend to cycle through lots of implementations and ideas and have come to become a really rapid prototyper (I have a psychological tendency to stubbornly fall in love with solutions I spent lots of time on, so to counter that I've learned to spend the absolute minimal time on a solution until it's very, very promising).

You can see my exact methodology at work in the very answers to that
  question where I iteratively converged through lots of profiling and
  measuring over the course of a few days and prototyping from a fairly orthodox quadtree to that
  unorthodox "loose-tight double grid" solution that handled the largest
  number of agents at the most stable frame rates and was, for me
  anyway, much faster and simpler to implement than all the structures
  before it. I had to go through lots of orthodox solutions and measure them though to generate the final idea for the unusual loose-tight variant. I always start off with and favor the orthodox solutions and start off inside the box because they're well-documented and understood and just very gently and timidly venture outside, but I do often find myself a bit outside the box when the requirements are steep enough. I'm no stranger to the steepest requirements since in my industry and as a fairly low-level type working on engines, the ability to handle more data at good frame rates often translates not only to greater interactivity for the user but also allows artists to create more detailed content of higher visual quality than ever before. We're always chasing higher and higher visual quality at good frame rates, and that often boils down to a combination of both performance and getting away with crude approximations whenever possible. This inevitably leads to some degree of unorthodoxy with lots of in-house solutions very unique to a particular engine, and each engine tends to have its own very unique strengths and weaknesses as you find comparing something like CryEngine to Unreal Engine to Frostbite to Unity.

For example, I have this data structure I've been using since childhood and I don't know the name of it. It's a straightforward concept and it's just a hierarchical bitset that allows set intersections of potentially millions of elements to be found in as little as a few iterations of simple work as well as traverse millions of elements occupying the set with just a few iterations (less than linear-time requirements to traverse everything in the set just through the data structure itself which returns ranges of occupied elements/set bits instead of individual elements/bit indices). But I have no idea what the name is since it's just something I rolled and I've never encountered anyone talking about it in computer science. I tend to refer to it as a "hierarchical bitset". Originally I called it a "sparse bitset tree" but that seems a tad verbose. It's not a particularly clever concept at all and I wouldn't be surprised or disappointed (actually quite happy) to find someone else discovering the same solution before me but just one I don't find people using or talking about ever. It just expands on the strengths of a regular, flat bitset in rapidly finding set intersections with bitwise OR and rapidly traverse all set bits using FFZ/FFS but reducing the linear-time requirements of both down to logarithmic (with the logarithm base being a number much larger than 2).

Anyway, I wouldn't be surprised if some of these solutions are very unorthodox, but also wouldn't be surprised if they are reasonably orthodox and I've just failed to find the proper name and terminology for these techniques. A lot of the appeal of sites like this for me is a lonely search for someone else who has used similar techniques and to try to find proper names and terms for them often to end in frustration. I'm also hoping to improve on my ability to explain them although I've always been so bad and long-winded here. I find using pictures helps me a lot because I find human language to be incredibly riddled with ambiguities. I'm also fond of deliberately imprecise figurative language which embraces and celebrates the ambiguities such as metaphor and analogy and humorous hyperbole, but I've not found it's the type of thing programmers tend to appreciate so much due to its lack of precision. But I've never found precision to be that important so long as we can convey the meaty stuff and what is "cool" about an idea while they can draw their own interpretations of the rest. Apologies for the whole explanation but hopefully that clears some things up about my crude terminology and the overall methodology I use to arrive at these techniques. English is also not my first language so that adds another layer of convolution where I have to sort of translate my thoughts into English words and struggle a lot with that.


text:
Q: WPF, datagrid програмно изменить значение ячейки У меня есть datagrid:
<DataGrid    Name="dataGrid1">
    <DataGrid.Columns>
        <DataGridTextColumn CellStyle="{StaticResource NameCellStyle}"    Header="Канал"  Width="0.6*"   IsReadOnly="True" Binding="{Binding Path=Channel}">
            <DataGridTextColumn.ElementStyle>
                <Style>
                    <Setter Property="TextBlock.VerticalAlignment" Value="Center" />

                </Style>
            </DataGridTextColumn.ElementStyle>
        </DataGridTextColumn>

        <DataGridTextColumn  CellStyle="{StaticResource NameCellStyle}" Width="0.4*" Header="Статус"  IsReadOnly="True"  Binding="{Binding Path=Status}">
            <DataGridTextColumn.ElementStyle>
                <Style>
                    <Setter Property="TextBlock.VerticalAlignment" Value="Center" />
                </Style>
            </DataGridTextColumn.ElementStyle>
        </DataGridTextColumn>

    </DataGrid.Columns>
</DataGrid>

Заполнение:
dataGrid1.Items.Add(new TaskTable()
{
    Channel = "text",
    Status = @"Работает",
});

Как изменить определенную ячейку в строке X столбцу Y?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Advanced Settings dialog box on Ubuntu MATE is too long for the screen, so can't change settings When I click on Advanced Settings in User Settings in Ubuntu MATE, the diaog box is so long that it cannot fit the screen, so I cannot apply the settings, and I cannot resize the dialog box.

A: Either...
Hold down the ALT key, and then left-click-hold-drag inside the window and drag the window such that you can get to the Apply button.
Make sure that workspaces are enabled with 2-4 workspaces, open the settings, and then switch to workspace 2/3 to be able to get to the Apply button.


text:
Q: What kind of error is this sysmalloc: Assertion? Can anyone explain why I'm getting this error and how can I rectify it?
#include<stdio.h>
#include<stdlib.h>

char makemeunique(char *s,int l)
{
char *xp=(char *)malloc(l*sizeof(char));
int *pp=xp;
for(int i=1;i<l; i++)
{
    int yes=0;
    for(int j=i-1;j>=0; j--)
    {
    if(s[i]==s[j])
    yes=1;
    }
    if(yes-1)
    *pp++=s[i];
}

*pp='\0';
printf("%s\n",xp);
return xp;
}

Main function
int main()
{
char s[9999],x [9999];
scanf("%s\n%s",s,x);

char *p1, *p2;

p1=makemeunique(s, strlen(s));
p2=makemeunique(x, strlen(x));
}

My output:
Hello: malloc.c:2385: sysmalloc: Assertion (old_top == initial_top (av) && old_size == 0) || ((uns igned long) (old_size) >= MINSIZE && prev_inuse (old_top) && ((unsigned long) old_end & (pa gesize - 1)) == 0)' failed. Aborted (core dumped)

What is the meaning of this output??
This program simply gets two strings and calls the function and stores created heap array in the pointer.
This is my program and output:

A: You create wrong pointer type at :
int *pp=xp;

pp should be char* : each time you do *pp++ you add sizeof(int) instead of sizeof(char) : result is you go beyond allocated memory to xp and this can result in usual C undefined behaviour.


text:
Q: Github star/unstar in API Do you know if github has implemented their new star/unstar feature of repositories in the API yet? I can't find anything in the documentation over there.

A: https://developer.github.com/v3/activity/starring/#star-a-repository:

Star a repository
PUT /user/starred/:owner/:repo

Unstar a repository
DELETE /user/starred/:owner/:repo

A: Please read that document, changelog states:

Breaking Beta Changes
August 7, 2012
Clarified watching/stargazing

The changeset is here:

*

*https://github.com/github/developer.github.com/commit/14c25df8c1a5e4e9a593d477d9e7d42b632ceb3c
Let me know if you still have problems to locate the information.

A: It's been added: http://developer.github.com/v3/repos/starring/ (history). There's also some transitional stuff to deprecate the watching APIs, if you've been using them.


text:
Q: Why is it dangerous to use an email address as an OpenID? Google uses email addresses as OpenID login strings for its provider service.
I was reading about a conference where they were pushing to have it incorporated into the standard.  Microsoft was against this, the "official" reason being security vulnerabilities this would supposedly introduce.  Is this bogus? If not, why is it insecure?

A: This goes against the minimal disclosure concept. Right now if an OpenID relying party wants your email address they ask for it and you are warned about this by the identity provider and asked to confirm it. Using the email address means it goes whether you like it or not unless you're using OpenID 2.0 which can generate unique values on a per relying party basis.
It would also be a big change for all the OpenID libraries - URLs are discoverable, you know where to go with them, email addresses are not, which was why there was outrage at Google unilaterally doing this and effectively forking the OpenID standard to suit themselves.
The other problem lies in phishing. OpenID is very vulnerable to this as users trust the relying party to redirect them to their provider after discovering it via the OpenID provided - so a "mischievous" relying party may redirect to a phishing site which saves the OpenID and the password. With Google the OpenID and password is your gmail account and password so you've not only lost control of your OpenID but your email account as well. Of course this could be secured by the provider - you could have separate email passwords and OpenID passwords, you could have a secret message on a per user basis you show on the OpenID login page, but as we're well aware users are stupid. They don't check URLs in the browser, they blindly click OK on dialog boxes, they simply don't think that a web page could be fake. By using the email address and the same password Google are exposing the majority of their users to an unacceptable risk.

A: One danger of using email address is that it is guessable. Or rather than someone who wants to break your account will probably know it.
Compare that to the current situation where your username and your OpenID provider could be anything. Maybe that's guessable, maybe it isn't. If it's not it makes it just a little harder to compromise your account.
Some people seem to have a problem with this. Look it's pretty simple. I haven't said that a non-obvious username is in and of itself sufficient security. Far from it. Security through obscurity is no security at all.
However, it's pure commonsense that out of:

*

*A password with an obscure username; and

*The same password with an obscure username.

that (1) is, at worst, equally secure to (2) and at best it is more secure.
What's more if your email is your password then if you compromise someone's email address you potentially compromise every system that uses that as a username is more easily compromised both by virtue of "Forget Password?" links and the fact that a password used in one place is more likely to be used in another.
Sorry but that's just commonsense.


text:
Q: How to force SMB2 protocol in samba? For security reasons, I'd like to disable the SMB1 protocol in samba. Is it possible? I'm running Ubuntu 14.04 LTS.

A: My testing with Nessus has indicated SMBv1 is only disabled when setting
min protocol = SMB2

in the [global] section of smb.conf . Core, LANMAN2 and NT1 were all still flagged as being vulnerable.

A: I had to add this for it to work in my old ubuntu 12-server; with either of min/max-combination SMBv1 is enabled but with both it works fine.
[global]
min protocol = SMB2
max protocol = SMB2
client min protocol = SMB2
client max protocol = SMB2

A: While I'm not sure where SMB1 fits in (My guess is CORE), here is the order of protocols from "man smb.conf"
   max protocol (G)
       The value of the parameter (a string) is the highest protocol level that will be supported by the server.
       Possible values are :
       ·   CORE: Earliest version. No concept of user names.
       ·   COREPLUS: Slight improvements on CORE for efficiency.
       ·   LANMAN1: First
            modern version of the protocol. Long filename support.
       ·   LANMAN2: Updates to Lanman1 protocol.
       ·   NT1: Current up to date version of the protocol. Used by Windows NT. Known as CIFS.
       ·   SMB2: Re-implementation of the SMB protocol. Used by Windows Vista and newer.

   min protocol (G)
       The value of the parameter (a string) is the lowest SMB protocol dialect than Samba will support. Please refer to the max
       protocol parameter for a list of valid protocol names and a brief description of each. You may also wish to refer to the C
       source code in source/smbd/negprot.c for a listing of known protocol dialects supported by clients.
       If you are viewing this parameter as a security measure, you should also refer to the lanman auth parameter. Otherwise, you
       should never need to change this parameter.
       Default: min protocol = CORE
       Example: min protocol = NT1

A: I think that I managed to disable SMB1 protocol with these two lines in the [global] section:
min protocol = LANMAN2
max protocol = SMB3

I'm still not completely sure about the order of protocols in Samba, but I'm quite confident that LANMAN2 is after SMB1.

A: I think what you are looking for in the smb.conf file is:

###
server min protocol = SMB2_10
client min protocol = SMB2
client max protocol = SMB3


text:
Q: retaining selected dropdown option on postback How do I retain whatever was selected from the dropdown even after page refresh so user knows what he/she selected using jquery? or javascript?
<select id="hospitalDropDown" onchange="window.open(this.options[this.selectedIndex].value,'_top')">
      <option disabled="disabled">Select Hospital</option>
      <option value="http://mysite.com/events/Pages/default1.aspx">All Hospitals</option>
      <option value="http://mysite.com/events/Pages/default1.aspx?hos=Dyer">Dyer</option>
      <option value="http://mysite.com/events/Pages/default1.aspx?hos=Carmel">Carmel</option>
    </select>

A: Try this:
<select id="hospitalDropDown" onchange="window.open('http://mysite.com/events/Pages/default1.aspx?hos='+this.value,'_top')">
  <option disabled="disabled">Select Hospital</option>
  <option value="All">All Hospitals</option>
  <option value="Dyer">Dyer</option>
  <option value="Carmel">Carmel</option>
</select>

$(document).ready(function(){
    var value = window.location.href.match(/[?&]hos=([^&#]+)/) || [];
    $('#hospitalDropDown').val(value[1]);
});

A: <select id="hospitalDropDown">
    <option value="">All Hospitals</option>
    <option value="Dyer">Dyer</option>
    <option value="Carmel">Carmel</option>
</select>
<script type="text/javascript">

$(document).ready(function() {
    $('#hospitalDropDown').val('<?php echo $_GET['hos']; ?>');
    $('#hospitalDropDown').change(function() {
        location.href = 'http://mysite.com/events/Pages/default1.aspx?hos=' + $(this).val();
    });
});
</script>


text: Q: Nuxtjs pre rendered in combination with spa In nuxt.js I want to serve first pages that you get with "nuxt generate", and after it's ready to run spa way of functioning. I see it's possible(VuePress did it), my question is, is that possible with nuxt and how?


text:
Q: How to set the user to whom we need to send approval request. I have a trigger from where I need to submit a record for approval. With that I also want to set to how it should send for approval. Is this possible to do from trigger.

A: You can definitely submit a record for approval from a trigger. Have a look at the following example for an Opportunity Approval Process:
trigger OpportunitySubmitForApproval on Opportunity (after update) {

    for (Integer i = 0; i < Trigger.new.size(); i++) {

        if (Trigger.old[i].Probability < 30 && Trigger.new[i].Probability >= 30) {

            // create the new approval request to submit
            Approval.ProcessSubmitRequest req = new Approval.ProcessSubmitRequest();
            req.setComments('Submitted for approval. Please approve.');
            req.setObjectId(Trigger.new[i].Id);
            // submit the approval request for processing
            Approval.ProcessResult result = Approval.process(req);
            // display if the reqeust was successful
            System.debug('Submitted for approval successfully: '+result.isSuccess());

        }

    }

}

Source: http://blog.jeffdouglas.com/2010/01/04/automating-salesforce-approval-processes-with-apex-triggers/
If you want to dynamically set the user who approves the process, you can do the following:

*

*Set the approval process up to use the Approver field of the Record Owner.

*Now, before you submit the Approval Request in your trigger, update the Approver field of the Record Owner so that the Approval Request is routed correctly.


text:
Q: Hover on button does not work on Firefox I've coded some buttons that increase in size when hovered.
It works perfectly on Chrome, yet on Firefox it doesn't do anything.
What's going wrong?

.P1 {
  background-color: transparent;
  border: 0;
  background-repeat: no-repeat;
  width: 80px;
  height: 110px;
}
.roundB {
  height: 60%;
  width: 80%;
}
.roundB:hover {
  border: 2px solid black;
  border-radius: 50%;
  height: 100%;
  width: 115%;
}

    <button type="button" class="P1" data-toggle="modal" data-target="#myModal">

    </button>
    <button type="button" class="P1" data-toggle="modal" data-target="#myModal1">

    </button>
    <button type="button" class="P1" data-toggle="modal" data-target="#myModal2">

    </button>
    <button type="button" class="P1" data-toggle="modal" data-target="#myModal3">

    </button>
    <button type="button" class="P1" data-toggle="modal" data-target="#myModal4">

    </button>
    <button type="button" class="P1" data-toggle="modal" data-target="#myModal5">

    </button>

A: Firefox is only accept hover on button (not see elements inside button tag). If You replace selector .roundB:hover to .P1:hover .roundB this will works the same like now on chrome.


text:
Q: Last command's output is doubled (trying to print stack elements) So, the task is to implement simple stack using array and to write a program that calls stack methods using command line commands. For example:

*

*set_size 5 – calls  a function that returns stack with 5 elements

*push N – calls stack.push(N)

*pop - calls stack.pop()

*print – calls stack print

The corresponding code is below. :
#include <iostream>
#include <vector>
#include <string>
#include <regex>
#include <sstream>

template <class T>
class Stack
{
    int size = 0;
    T* Array;
    int top = 0;

public:
    Stack(size_t Size);
    ~Stack()
    {
        delete[] Array;
    }
    void push(T element);
    void pop();
    void print();
};
template <class T>
Stack<T>::Stack(size_t Size)
{
    size = Size;
    top = -1;
    Array = new T[size];
}
template <class T>
void Stack<T>::push(T element)
{
    if (top >= (size - 1))
    {
        std::cout << "overflow" << std::endl;
    }
    else
    {
        Array[++top] = element;
    }
}
template <class T>
void Stack<T>::pop()
{
    if (top < 0)
    {
        std::cout << "underflow" << std::endl;
    }
    else
    {
        std::cout << Array[top--] << std::endl;
    }

}
template <class T>
void Stack<T>::print()
{
    if (top == -1)
    {
        std::cout << "empty" << std::endl;
    }
    int i = -1;
    while (++i <= top)
    {
        std::cout << Array[i] << " ";
    }
    std::cout << std::endl;
}
template <class T>
Stack<T> set_size(int Size)
{
    return Stack<T>(Size);
}

int main()
{
    int size = 0;
    std::string command, line, element;
    std::cin >> command >> size;
    if (command == "set_size")
    {
        auto stack = set_size<std::string>(size);
        while (std::getline(std::cin, line))
        {
            std::istringstream is(line);
            is >> command;
            if (command == "push")
            {
                is >> element;
                if (is.rdbuf()->in_avail() == 0)
                {
                    stack.push(element);
                }
                else
                {
                    std::cout << "error" << std::endl;
                }
            }
            if (command == "pop")
            {
                stack.pop();
            }
            if (command == "print")
            {
                stack.print();
            }
        }
    }
    return 0;
}

But for some reason the testing utility's output differs from the one I get in Visual Studio – last command is repeated twice. Utility's input:
set_size 5
pop
push 1 10
push 2
push 3
push 4
push 5
print
push 6
pop
push 7
print

EDIT: For some reason when pressing enter in command line it repeats the previous command, so that's why the utility repeats last print. But I still don't know why and how to fix this.
And here are the outputs:
Utility:
underflow
error
2 3 4 5
6
2 3 4 5 7
2 3 4 5 7

The desired output (the one I also get in Visual Studio):
underflow
error
2 3 4 5
6
2 3 4 5 7

I reckon it is somehow related to the usage of istringstream or the way my commands are inputted, but I can't figure out why it differs and how to fix it. Or are there ways to do it smarter / simpler?
(Note: I need to check if there is only 1 push argument, so the whole istringstream thing is meant to do exactly this)

A: When you enter an empty string the subsequent input operation is >> command will fail, leaving command with the value it had last, which is print. To fix this, either create a local variable to work with inside the loop, or call command.clear() before the input operation.


text:
Q: Given a set of points in 3d space, find all sets of points within a distance of eachother I have a set of 3d points S.
I need to find the set X of all sets of points in S which are within manhattan distance d of each other.
i.e. for each set Y in X there exists atleast one point in 3d space that is within distance d of all points in Y
The length of set S will never be >20 but I will have to run this analysis on a stream of sets which are being produced at ~10 new sets per second, so whatever solution I use will have to be fairly efficient.
an example to help visualize the problem, given the following:

the output would be ((A,B), (B,C,E), (B,D,E))
we only care about the largest possible sets so the sets (B,C), (B,D), (B,E), (C,E) and (D,E), while within the given parameters, are not in the output given they are subsets of other sets in X
also this I'm doing this in java but any pointers in terms of algorithms or pseudo code would be greatly appreciated, thanks in advance.

A: A solution in pseudocode would be:
calculate_intersections(areas):
    intersections = calculate every two intersecting areas
    combinations = combine_intersections(intersections)
    reduced = remove all sets in combinations that are included in bigger sets

combine_intersections(intersections):
    do:
        combinations = new HashSet

        for s1 in intersections:
            for s2 in intersections:
                diff_1_2 = s1 \ s2
                diff_2_1 = s2 \ s1

                if diff_1_2.len == 1 && diff_2_1.len == 1:
                    union = diff_1_2 + diff_2_1

                    if union in intersections:
                        union2 = s1 + s2
                        if !union2 in intersections:
                            combinations.add(union)
    while (combinations not empty)

An implementation in Java could look like this:
import java.util.Arrays;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

import org.apache.commons.collections4.SetUtils;

public class IntersectionSetCalculation {

    private static class ManhattanDistanceArea {

        private String id;
        private Vector3D center;
        private double distance;

        public ManhattanDistanceArea(Vector3D center, double distance, String id) {
            this.center = center;
            this.distance = distance;
            this.id = id;
        }

        @Override
        public String toString() {
            return id;
        }

        @Override
        public int hashCode() {
            final int prime = 31;
            int result = 1;
            result = prime * result + ((center == null) ? 0 : center.hashCode());
            long temp;
            temp = Double.doubleToLongBits(distance);
            result = prime * result + (int) (temp ^ (temp >>> 32));
            result = prime * result + ((id == null) ? 0 : id.hashCode());
            return result;
        }

        @Override
        public boolean equals(Object obj) {
            if (this == obj)
                return true;
            if (obj == null)
                return false;
            if (getClass() != obj.getClass())
                return false;
            ManhattanDistanceArea other = (ManhattanDistanceArea) obj;
            if (center == null) {
                if (other.center != null)
                    return false;
            }
            else if (!center.equals(other.center))
                return false;
            if (Double.doubleToLongBits(distance) != Double.doubleToLongBits(other.distance))
                return false;
            if (id == null) {
                if (other.id != null)
                    return false;
            }
            else if (!id.equals(other.id))
                return false;
            return true;
        }

        public boolean intersects(ManhattanDistanceArea other) {
            double maxDist = distance + other.distance;
            return center.distance(other.center, 1) < maxDist;
        }
    }

    /**
     * Calculate the intersection of all areas (maximum of 2 areas in an intersection)
     */
    public static Set<Set<ManhattanDistanceArea>> getIntersectingAreas(Set<ManhattanDistanceArea> areas) {
        Set<Set<ManhattanDistanceArea>> intersections = new HashSet<Set<ManhattanDistanceArea>>();

        for (ManhattanDistanceArea area : areas) {
            for (ManhattanDistanceArea area2 : areas) {
                if (!area.equals(area2) && area.intersects(area2)) {
                    HashSet<ManhattanDistanceArea> intersection = new HashSet<ManhattanDistanceArea>();
                    intersection.add(area);
                    intersection.add(area2);
                    intersections.add(intersection);
                }
            }
        }

        Set<Set<ManhattanDistanceArea>> combined = combineIntersections(intersections);
        Set<Set<ManhattanDistanceArea>> reduced = reduceIntersections(combined);

        return reduced;
    }

    /**
     * Combine the small intersections (with a maximum of 2 areas in an intersection) to bigger intersections
     */
    public static Set<Set<ManhattanDistanceArea>> combineIntersections(Set<Set<ManhattanDistanceArea>> inters) {
        Set<Set<ManhattanDistanceArea>> intersections = new HashSet<Set<ManhattanDistanceArea>>(inters);
        Set<Set<ManhattanDistanceArea>> combinations;

        do {
            combinations = new HashSet<Set<ManhattanDistanceArea>>();

            for (Set<ManhattanDistanceArea> intersecting1 : intersections) {
                for (Set<ManhattanDistanceArea> intersecting2 : intersections) {
                    Set<ManhattanDistanceArea> diff_1_2 = SetUtils.difference(intersecting1, intersecting2);
                    Set<ManhattanDistanceArea> diff_2_1 = SetUtils.difference(intersecting2, intersecting1);

                    if (diff_1_2.size() == 1 && diff_2_1.size() == 1) {
                        Set<ManhattanDistanceArea> union_1_2 = SetUtils.union(diff_1_2, diff_2_1);

                        if (intersections.contains(union_1_2)) {
                            Set<ManhattanDistanceArea> union = SetUtils.union(intersecting1, intersecting2);
                            if (!intersections.contains(union)) {
                                combinations.add(union);
                            }
                        }
                    }
                }
            }

            intersections.addAll(combinations);

        } while (!combinations.isEmpty());

        return intersections;
    }

    /**
     * Remove the small intersections that are completely covered by bigger intersections
     */
    public static Set<Set<ManhattanDistanceArea>> reduceIntersections(Set<Set<ManhattanDistanceArea>> inters) {
        Set<Set<ManhattanDistanceArea>> intersections = new HashSet<Set<ManhattanDistanceArea>>(inters);
        Iterator<Set<ManhattanDistanceArea>> iter = intersections.iterator();

        while (iter.hasNext()) {
            Set<ManhattanDistanceArea> intersection = iter.next();
            for (Set<ManhattanDistanceArea> intersection2 : inters) {
                if (intersection2.size() > intersection.size() && intersection2.containsAll(intersection)) {
                    iter.remove();
                    break;
                }
            }
        }

        return intersections;
    }

    public static void main(String[] args) {
        final double dist = 2d;//the manhattan distance d

        ManhattanDistanceArea A = new ManhattanDistanceArea(new Vector3D(0, -3, 0), dist, "A");
        ManhattanDistanceArea B = new ManhattanDistanceArea(new Vector3D(0, 0, 0), dist, "B");
        ManhattanDistanceArea C = new ManhattanDistanceArea(new Vector3D(3.5, 0, 0), dist, "C");
        ManhattanDistanceArea D = new ManhattanDistanceArea(new Vector3D(0, 3.5, 0), dist, "D");
        ManhattanDistanceArea E = new ManhattanDistanceArea(new Vector3D(1, 1, 0), dist, "E");

        ManhattanDistanceArea F = new ManhattanDistanceArea(new Vector3D(-1, 1, 0), dist, "F");

        //test the example you provided
        Set<ManhattanDistanceArea> abcde = new HashSet<ManhattanDistanceArea>();
        abcde.addAll(Arrays.asList(new ManhattanDistanceArea[] {A, B, C, D, E}));

        //test another example
        Set<ManhattanDistanceArea> abcdef = new HashSet<ManhattanDistanceArea>();
        abcdef.addAll(abcde);
        abcdef.add(F);

        Set<Set<ManhattanDistanceArea>> intersectionsABCDE = getIntersectingAreas(abcde);
        Set<Set<ManhattanDistanceArea>> intersectionsABCDEF = getIntersectingAreas(abcdef);

        System.out.println(intersectionsABCDE);
        System.out.println(intersectionsABCDEF);

        //test the runntime for 1000 calculation
        double startTime = System.currentTimeMillis();
        final int calculations = 1000;
        for (int i = 0; i < calculations; i++) {
            Set<ManhattanDistanceArea> areas = new HashSet<ManhattanDistanceArea>();
            for (int j = 0; j < 20; j++) {
                areas.add(new ManhattanDistanceArea(new Vector3D(Math.random() * 10 - 5, Math.random() * 10 - 5, Math.random() * 10 - 5), dist,
                        "A" + j));
            }

            getIntersectingAreas(areas);
        }
        System.out.println("\nTime used for " + calculations + " intersection calculations (with sets of size 20): "
                + (System.currentTimeMillis() - startTime) + "ms");
    }
}

For the implementation I used this class Vector3D:
public class Vector3D {

    public double x;
    public double y;
    public double z;

    public static final Vector3D NAN_VEC = new Vector3D(Double.NaN, Double.NaN, Double.NaN);
    public static final Vector3D NULL_VEC = new Vector3D(0, 0, 0);

    public enum Axis {
        X, Y, Z;
    }

    public Vector3D() {

    }

    /**
     * Crate a new Vector2D with x and y components.
     */
    public Vector3D(double x, double y, double z) {
        this.x = x;
        this.y = y;
        this.z = z;
    }
    public Vector3D(double... val) {
        x = val[0];
        y = val[1];
        z = val[2];
    }

    /**
     * Create a Vector3D by two angles (in degree).
     *
     * The first angle is in XY direction. The second angle is the Z direction.
     *
     * An angle (XY) of 0° results in (x, y) = (1, 0); 90° in (x, y) = (0, 1); ... An angle (Z) of 0° results in (x, y, z) = (x, y, 0); 90° in (x, y,
     * z) = (x, y, 1); -90° in (x, y, z) = (x, y, -1)
     *
     * The resulting vector has a length of 1.
     *
     * @param angleXY
     *        The angle of the new vector (in degree) for the XY direction (from 0 to 360).
     *
     * @param angleZ
     *        The angle of the new vector (in degree) for the Z direction (from -90 to 90).
     */
    public Vector3D(double angleXY, double angleZ) {
        x = Math.cos(angleXY * Math.PI / 180) * Math.cos(angleZ * Math.PI / 180);
        y = Math.sin(angleXY * Math.PI / 180) * Math.cos(angleZ * Math.PI / 180);
        z = Math.sin(angleZ * Math.PI / 180);
        double len = length();
        x /= len;
        y /= len;
        z /= len;
    }

    private Vector3D(Vector3D clone) {
        this.x = clone.x;
        this.y = clone.y;
    }

    @Override
    public Vector3D clone() {
        return new Vector3D(this);
    }

    @Override
    public String toString() {
        return "Vector3D[x: " + x + " y: " + y + " z:" + z + "]";
    }

    @Override
    public boolean equals(Object obj) {
        if (obj instanceof Vector3D) {
            Vector3D v = (Vector3D) obj;
            return Math.abs(x - v.x) < 1e-8 && Math.abs(y - v.y) < 1e-8 && Math.abs(z - v.z) < 1e-8;
        }
        return false;
    }

    /**
     * Get this vector as 3D-Array.
     */
    public double[] asArray() {
        return new double[] {x, y, z};
    }

    /**
     * The (euclidean) length of the Vector.
     */
    public double length() {
        return Math.sqrt(Math.pow(x, 2) + Math.pow(y, 2) + Math.pow(z, 2));
    }
    /**
     * The length of this vector in a given norm.
     *
     * @param norm
     *        The norm of the vector length.
     *
     * @return The length of this vector in the given norm.
     */
    public double length(int norm) {
        if (norm == Integer.MAX_VALUE) {
            return Math.max(Math.max(x, y), z);
        }
        return Math.pow(Math.pow(x, norm) + Math.pow(y, norm) + Math.pow(z, norm), 1.0 / norm);
    }

    /**
     * Rotate this vector an angle (in degrees) around an axis resulting in a new Vector that is returned.
     *
     * @param degrees
     *        The angle to return the vector.
     *
     * @param axis
     *        The axis around which the vector is rotated.
     *
     * @return The new created vector.
     */
    public Vector3D rotate(double degrees, Axis axis) {
        double cos = Math.cos(degrees * Math.PI / 180);
        double sin = Math.sin(degrees * Math.PI / 180);
        switch (axis) {
            case X:
                return new Vector3D(x, cos * y - sin * z, sin * y + cos * z);
            case Y:
                return new Vector3D(cos * x + sin * z, y, -sin * x + cos * z);
            case Z:
                return new Vector3D(cos * x - sin * y, sin * x + cos * y, z);
            default:
                return null;
        }
    }

    /**
     * Project the vector given as parameter on this vector.
     *
     * @param vec
     *        The vector that is to be projected on this vector.
     *
     * @return The projected vector.
     */
    public Vector3D project(Vector3D vec) {
        return mult(scalar(vec) / Math.pow(length(), 2));
    }

    /**
     * Add another Vector3D to this vector resulting in a new Vector that is returned.
     *
     * @param vec
     *        The vector added to this vector.
     *
     * @return The new created vector.
     */
    public Vector3D add(Vector3D vec) {
        return new Vector3D(x + vec.x, y + vec.y, z + vec.z);
    }
    /**
     * Subtract another Vector3D from this vector resulting in a new Vector that is returned.
     *
     * @param vec
     *        The vector subtracted from this vector.
     *
     * @return The new created vector.
     */
    public Vector3D sub(Vector3D vec) {
        return new Vector3D(x - vec.x, y - vec.y, z - vec.z);
    }
    /**
     * Multiply this vector with a scalar resulting in a new Vector that is returned.
     *
     * @param scalar
     *        The scalar to multiply this vector with.
     *
     * @return The new created vector.
     */
    public Vector3D mult(double scalar) {
        return new Vector3D(x * scalar, y * scalar, z * scalar);
    }

    /**
     * Check whether this vector is linearly dependent to the parameter vector.
     *
     * @param vec
     *        The checked vector.
     *
     * @return True if the vectors are linearly dependent. False otherwise.
     */
    public boolean isLinearlyDependent(Vector3D vec) {
        double t1 = (x == 0 ? 0 : vec.x / x);
        double t2 = (y == 0 ? 0 : vec.y / y);
        double t3 = (z == 0 ? 0 : vec.z / z);
        return Math.abs(t1 - t2) < 1e-5 && Math.abs(t1 - t3) < 1e-5 && t1 != 0;//all parameters t are equal and != 0
    }

    /**
     * Calculate the scalar product of this vector and the parameter vector.
     *
     * @param vec
     *        The vector to calculate the scalar with this vector.
     *
     * @return The scalar of the vectors.
     */
    public double scalar(Vector3D vec) {
        return this.x * vec.x + this.y * vec.y + this.z * vec.z;
    }

    /**
     * Calculate the cross product of this vector with another vector (resulting vector = this X parameter vector)
     *
     * @param vec
     *        The second vector for the cross product calculation.
     *
     * @return The cross product vector of the two vectors.
     */
    public Vector3D cross(Vector3D vec) {
        return new Vector3D(y * vec.z - z * vec.y, z * vec.x - x * vec.z, x * vec.y - y * vec.x);
    }

    /**
     * Create a new vector with the same direction but a different length as this vector.
     *
     * @param length
     *        The length of the new vector.
     *
     * @return The new vector with a new length.
     */
    public Vector3D setLength(double length) {
        double len = length();
        return new Vector3D(x * length / len, y * length / len, z * length / len);
    }

    /**
     * Get the distance of this point's position vector to another point's position vector.
     *
     * @param p
     *        The second point's position vector.
     *
     * @return The distance between the points.
     */
    public double distance(Vector3D p) {
        return Math.sqrt((this.x - p.x) * (this.x - p.x) + (this.y - p.y) * (this.y - p.y) + (this.z - p.z) * (this.z - p.z));
    }
    /**
     * Get the distance of this point's position vector to another point's position vector in a given norm.
     *
     * @param p
     *        The second point's position vector.
     *
     * @param norm
     *        The norm in which the distance is calculated (1 -> manhattan, 2 -> euclide, ...)
     *
     * @return The distance between the points in the given norm.
     */
    public double distance(Vector3D p, int norm) {
        return Math.pow((Math.pow(Math.abs(this.x - p.x), norm) + Math.pow(Math.abs(this.y - p.y), norm) + Math.pow(Math.abs(this.z - p.z), norm)),
                1d / norm);
    }

    /**
     * Change this vector to the new coordinates.
     */
    public void move(double x, double y, double z) {
        this.x = x;
        this.y = y;
        this.z = z;
    }

    /**
     * Move a point's position vector in a direction (by a vector) and a distance.
     *
     * @param p
     *        The direction vector.
     *
     * @param distance
     *        The distance to move the new vector
     *
     * @return The new created vector.
     */
    public Vector3D moveTo(Vector3D p, double distance) {
        double d = distance(p);
        double dx = p.x - x;
        double dy = p.y - y;
        double dz = p.z - z;
        double coef = distance / d;
        return new Vector3D(x + dx * coef, y + dy * coef, z + dz * coef);
    }

    /**
     * Get the angle difference of this vector to another vector.
     *
     * @param vec
     *        The other vector.
     *
     * @return The angle difference of the two vectors (from 0° to 180°).
     */
    public double getAngleTo(Vector3D vec) {
        double angle = Math.acos(scalar(vec) / (length() * vec.length())) * 180 / Math.PI;
        if (angle > 180) {
            angle = 360 - angle;
        }
        return angle;
    }

    /**
     * Get the vector from this point to another.
     *
     * @param vec
     *        The point to which the vector is calculated.
     *
     * @return The vector from this points position vector to the other point.
     */
    public Vector3D vectorTo(Vector3D vec) {
        return new Vector3D(vec.x - x, vec.y - y, vec.z - z);
    }

    /**
     * Checks whether a point (by its position vector) is in a given range of this point.
     *
     * @param p
     *        The point that is checked.
     *
     * @param range
     *        The range used for the check.
     *
     * @return True if the point is in the range of this point (distance <= range).
     */
    public boolean isInRange(Vector3D p, double range) {
        return p != this && distance(p) <= range;
    }
}

and the class SetUtils from the apache commons lib.
I also added some tests:

*

*the test from your question

*another test with a bigger intersection set

*a test for the runtime

The results are:

[[A, B], [B, E, C], [B, E, D]]
[[A, B], [B, E, C], [D, E, F, B]]
Time used for 1000 intersection calculations (with sets of size 20):
  791.0ms

So the results seem to be correct and you can calculate more than 1000 intersections in a second.

A: Exhaustive distance computation between 20 points, i.e. 190 distances is nothing for a PC. Time will measure in microseconds. You can draw the desired information from the "close to" relation encoded in a matrix.


text:
Q: Comparing approximate values in c# 4.0? First of all, please excuse any typo, English is not my native language.
Here's my question. I'm creating a class that represents approximate values as such:
public sealed class ApproximateValue
{
    public double MaxValue { get; private set; }
    public double MinValue { get; private set; }
    public double Uncertainty { get; private set; }
    public double Value { get; private set; }

    public ApproximateValue(double value, double uncertainty)
    {
        if (uncertainty < 0) { throw new ArgumentOutOfRangeException("uncertainty", "Value must be postivie or equal to 0."); }

        this.Value = value;
        this.Uncertainty = uncertainty;
        this.MaxValue = this.Value + this.Uncertainty;
        this.MinValue = this.Value - this.Uncertainty;
    }
}

I want to use this class for uncertain measurments, like x = 8.31246 +/-0.0045 for example and perform calculations on these values.
I want to overload operators in this class. I don't know how to implement the >, >=, <= and < operators... The first thing I thought of is something like this:
    public static bool? operator >(ApproximateValue a, ApproximateValue b)
    {
        if (a == null || b == null) { return null; }

        if (a.MinValue > b.MaxValue) { return true; }
        else if (a.MaxValue < b.MinValue) { return false; }
        else { return null; }
    }

However, in the last case, I'm not satisfied with this 'null' as the accurate result is not 'null'. It may be 'true' or it may be 'false'.
Is there any object in .Net 4 that would help implementing this feature I am not aware of, or am I doing the correct way? I was also thinking about using an object instead of a boolean that would define in what circumstances the value is superior or not to another one rather than implementing comparison operators but I feel it's a bit too complex for what I'm trying to achieve...

A: I'd probably do something like this.  I'd implement IComparable<ApproximateValue> and then define <, >, <=, and >= according to the result of CompareTo():
public int CompareTo(ApproximateValue other)
{
    // if other is null, we are greater by default in .NET, so return 1.
    if (other == null)
    {
        return 1;
    }

    // this is > other
    if (MinValue > other.MaxValue)
    {
        return 1;
    }

    // this is < other
    if (MaxValue < other.MinValue)
    {
        return -1;
    }

    // "same"-ish
    return 0;
}

public static bool operator <(ApproximateValue left, ApproximateValue right)
{
    return (left == null) ? (right != null) : left.CompareTo(right) < 0;
}

public static bool operator >(ApproximateValue left, ApproximateValue right)
{
    return (right == null) ? (left != null) : right.CompareTo(left) < 0;
}

public static bool operator <=(ApproximateValue left, ApproximateValue right)
{
    return (left == null) || left.CompareTo(right) <= 0;
}

public static bool operator >=(ApproximateValue left, ApproximateValue right)
{
    return (right == null) || right.CompareTo(left) <= 0;
}

public static bool operator ==(ApproximateValue left, ApproximateValue right)
{
    return (left == null) ? (right == null) : left.CompareTo(right) == 0;
}

public static bool operator !=(ApproximateValue left, ApproximateValue right)
{
    return (left == null) ? (right != null) : left.CompareTo(left) != 0;
}

A: It looks to me like you need to check if a.MaxValue == b.MinValue also, in your current implementation that would return null, which seems incorrect, it should either return true or false based on how you want the spec to actually work.  I'm not sure of any built in .net functionality for this, so I believe you are going about it the correct way.

A: This is one of the rare cases where it may make more sense to define a value type (struct), which then eliminates the null case concern.  You can also modify MinValue and MaxValue to be computed properties (just implement a get method that computes the result) rather than storing them upon construction.
On a side note, comparison of approximate values is itself an approximate operation, so you need to consider the use cases for your data type; are you only intending to use comparison to determine when the ranges are non-overlapping?  It really depends on the meaning of your type.  Is this intended to represent a data point from a normally distributed data set, where the uncertainty is some number of standard deviations for the sampling?  If so, it might make more sense for a comparison operation to return a numeric probability (which couldn't be called through the comparison operator, of course.)

A: return a.Value - a.Uncertainty > b.Value + b.Uncertainty

I wouldn't really mess with the semantics of >: I think bool? is a dangerous return type here. That said, given the uncertainty, you could return true, if a is more likely to be > b.

A: It seems to me that you're trying to implement some form of Ternary Logic because you want the result of applying the operators to be either True, False or Indeterminate. The problem with doing that is that you really cannot combine the built-in boolean values with your indeterminate value. So whilst you could do some limited form of comparison of two ApproximateValues I think that it's inappropriate to use bool as the result of these comparisons because that implies that the result of the comparisons can be freely combined with other expressions that result in bool values, but the possibility of an indeterminate value undermines that. For example, it makes no sense to do the following when the result of operation on the left of the OR is indeterminate.
ApproximateValue approx1 = ...;
ApproximateValue approx2 = ...;
bool result = ...;

bool result = approx1 > approx2 || someBool;

So, in my opinion, I don't think that it's a good idea to implement the comparisons as operators at all if you want to retain the indeterminacy. The solutions offered here eliminate the indeterminacy, which is fine, but not what was originally specified.


text:
Q: Fluent NHibernate HasManyToMany() Mapping I am having a problem in Fluent NHibernate example utilizing the Many-to-Many relationships. I tried to find out examples on a similar case, and I found tons, but I'm still having the same problem.
When running the test project, the following exception is thrown:
NHibernate.PropertyAccessException: Exception occurred getter of project.Entities.User.UserName --->  System.Reflection.TargetException: Object does not
match target type.
This is an image of the tables:

and the code
 public UsersMap()
    {

        this.Table("Users");
        Id(x => x.UserName).Column("Username").GeneratedBy.Assigned();

        Map(x => x.FirstName);
        Map(x => x.LastName);
        Map(x => x.Password);
        Map(x =>x.EMail);
        Map(x => x.Title);
        Map(x => x.Division);

        HasManyToMany<User>(x => x.Roles)
            .Table("UserInRoles").ParentKeyColumn("Username")
            .ChildKeyColumn("Usernamepk")
           .Cascade.SaveUpdate().LazyLoad();

    }

  public RolesMap()
    {
        this.Table("Roles");
        Id(x => x.ID).GeneratedBy.Assigned().Column("ID");
        Map(x => x.RoleName).Length(50);

        HasManyToMany<User>(x => x.Users)
            .Table("UserInRoles").ParentKeyColumn("ID")
            .ChildKeyColumn("RoleIdpk").Cascade.SaveUpdate().LazyLoad();

    }

here is the code, most examples on the web and the Fluent Nhibernate mappings page are written in the same way, so any ideas ?

A: Regarding to code I am using in my project I would define your manyTomany relations this way:
 public UsersMap()
    {
...
            HasManyToMany(x => x.Roles)
                .WithTableName("UserInRoles")
                .WithParentKeyColumn("Usernamepk")
                .WithChildKeyColumn("RoleIdpk");
    }

  public RolesMap()
    {
...
            HasManyToMany(x => x.Users)
                .WithTableName("UserInRoles")
                .WithParentKeyColumn("RoleIdpk")
                .WithChildKeyColumn("Usernamepk");

    }

Such a definitions works for me.
Check this first then decorate with LazyLoading and some other properties.


text:
Q: Android development - Users updating app question I've written a program that, when completed, I plan to add to the Android Marketplace.  I have given many files as features for users to store information and reload later, and while debugging, I've noticed the files tend to get deleted when I update the code after a long while (like a few days spread apart--for some reason, it doesn't happen when I update the code often, like every hour when I'm adding new features and testing them out).  Note that I use a real phone for testing and not the emulator.  What I'm wondering is, will the files get deleted after each release of the app?
I really don't want users to lose their stored information on every update or bug fix I provide, so if that is the case, is there a way around this?

A: Nope the files doesn't get deleted automatically, but it depends upon where you are storing the files. If the user deletes the app the files associated with it will get deleted too. But in case of an upgrade, No! normally it won't.
In case you are using SQLite for storing data, there is a proper way to handle upgrade there.


text:
Q: Date format to cron dormat conversion I want to change the date format into cron date format.How could it be done?
date format : 2018-05-15 17:30:00
cron format : 30 17 15 05 *

A: You could do that in a number of ways, but this is one of the more straightforward methods:
#!/bin/bash
_DATESTR='2018-05-15 17:30:00'
echo "date format: ${_DATESTR}"
echo "cron format: ${_DATESTR:14:2} ${_DATESTR:11:2} ${_DATESTR:8:2} ${_DATESTR:5:2} *"


text:
Q: Wifi drivers won't work after I upgraded kernel to 3.4 for ubuntu 12.04 My wifi support got broken after I upgraded my kernel from 3.2 to 3.4 for ubuntu 12.04. I know I need to use sudo apt-get install firmware-b43-installer but whenever I type it into terminal, I get:
Reading package lists... Done
Building dependency tree
Reading state information... Done
E: Unable to locate package firmware-b43-installer

I also tried using synaptic package manager but when I search for firmware-b43-installer I don't see any options. Check box for Proprietary drivers for devices (restricted) has also been selected from Settings->Repositories but I still don't see firmware-b43-installer.
Running lspci -vvnn | grep 14e4 command on the terminal gives:
02:00.0 Network controller [0280]: Broadcom Corporation BCM4331 802.11a/b/g/n [14e4:4331] (rev 02)

I am worried that I may have deleted some important package while trying to fix wifi. Please help I am very new to Ubuntu.

A: Please be certain that you have a working internet connection and then try:
sudo apt-get update
sudo apt-get install linux-firmware-nonfree
sudo apt-get purge bcmwl-kernel-source

If the latter package is not installed, that's fine. Reboot and let us have your report.
Do you have a wireless interface, ideally wlan0?
iwconfig

Are there any clues in the log?
dmesg | grep b43

Is the wireless switch on?
rfkill list all

Do you have a file blacklist-bcm43.conf?
ls /etc/modprobe.d

If so, remove it:
sudo rm /etc/modprobe.d/blacklist-bcm43.conf

Reboot and show us again:
dmesg | grep b43

The file /lib/firmware/b43/ucode29_mimo.fw is included in linux-firmware-nonfree according to: http://packages.ubuntu.com/precise/all/linux-firmware-nonfree/filelist Let's try to reinstall it and see if it helps:
sudo apt-get install --reinstall linux-firmware-nonfree

Reboot and check:
dmesg | grep b43

If not successful, try:
sudo apt-get purge linux-firmware-nonfree
wget http://mirrors.kernel.org/ubuntu/pool/multiverse/l/linux-firmware-nonfree/linux-firmware-nonfree_1.11_all.deb
sudo dpkg -i linux*.deb

Please tell me any errors or warnings.
To get the module to load automatically on boot:
gksudo gedit /etc/modprobe.d/blacklist.conf

If there is any reference to blacklisting b43 or ssb or bcma, remove them. Proofread, save and close. Next:
sudo -i
echo b43  >>  /etc/modules
exit

You should be all set.


text:
Q: While looping to end of file? #include <stdio.h>
#include <stdlib.h>
//#define true 0

typedef struct
{
    char currency[8];
    int exchangerate;
} randT;

void main()
{
    int i, num;
    char currency1[8], ch;
    FILE *file = fopen("address", "r");

    randT name[7];

    while(fscanf(file, "%i", &name[i].exchangerate) != EOF)/*I think this is where my problem is*/
    {
        fscanf(file, "%s %i", &name[i].currency, &name[i].exchangerate);
        //printf("%s %i\n", currency1, num);
        //if (fscanf(file, "%i", &currency1) == EOF) break;
        printf("%s %i\n", name[i].currency, name[i].exchangerate);
        i++;
    }

    fclose(file);
}

It is giving segmentation fault(core dumped) and i am fairly new to the fscanf functions and such. Please help!
my text file looks like this:
jeff 4
jina 5
jeffrey 6
jinna 7
jeffu 8
jinina 9
jeffz 10

A: The cause of the crash is that you need to initialize int i = 0;. As you have it, i is indeterminate, so probably name[i] is a massively out-of-bounds access.
For the fscanf, you have mostly the right idea about the loop, except instead of checking != EOF it's better to check  == 1 or however many items you were reading.  If the file contains something that can't be processed as a number, then fscanf will not return EOF.
However this is not the right way to read your particular file. You read %i then %s %i every time around, but your file only contains a string and an int.  Change to:
while ( 2 == fscanf(file, "%7s %i", name[i].currency, &name[i].exchangerate) )

Also after doing i++ you need to check that i has not gone out of bounds (i.e. it's less than 7).
Note that name[i].currency decays to pointer to char - you shouldn't put & on it. Also you should use the length specifier to avoid running over the end of the array.
I would use the loop structure:
for (num_read = 0; num_read < sizeof name / sizeof name[0]; ++num_read)
{
     if ( 2 != fscanf(file,.....
         break;

     printf(....
}


text:
Q: LabelEncoder() won't store parameters? LabelEncoder won't "remember" parameters. When I fit and transform data with it then ask for the parameters, all I get is {}. This makes it impossible to re-use the encoder on new data.
Example:
from sklearn.preprocessing import LabelEncoder

encode = LabelEncoder()
encode.fit_transform(['one', 'two', 'three'])
print(encode.get_params())

Not sure about the intended format, but I expect something like {['one', 0], ['two', 1], ['three', 2]}
Actual Result: {}
I'm on:
Darwin-16.7.0-x86_64-i386-64bit
Python 3.6.1 |Anaconda 4.4.0 (x86_64)| (default, May 11 2017, 13:04:09)
[GCC 4.2.1 Compatible Apple LLVM 6.0 (clang-600.0.57)]
NumPy 1.12.1
SciPy 0.19.0
Scikit-Learn 0.18.1

A: Label encoder stores the parameters in the classes_ attribute. You can obtain the encoded values transforming those classes and creating a dictionary. This encoder will work with new data that has the same labels otherwise it will raise a ValueError. Use the transform method on the labels you want to encode and that's it.
from sklearn import preprocessing

encode = preprocessing.LabelEncoder()
encode.fit_transform(['one', 'two', 'three'])
keys = encode.classes_
values = encode.transform(encode.classes_)
dictionary = dict(zip(keys, values))
print(dictionary)

Output: {'three': 1, 'two': 2, 'one': 0}


text:
Q: Can't connect to oracle database with IntelliJ, Locale not recognized I have Oracle Database 11g Express Edition installed, and can normally connect to my local database with PLSQL Developer, but I can't connect with IntelliJ. It says Locale not recognized.

After searching for some similar questions here, solution was kinda to change the machine locale manually, I did that and rebooted, but it still does not work. And I'm sure it really changed, because now, this line of java code:
System.out.println(Locale.getDefault()) printed en_US.
Now i really don't know what is the problem, why does PLSQL work and IntelliJ does not.
I am using ojdbc6.jar for connection.
When I tried to connect with the java code below the same kind of exception was thrown.
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection conn = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe", "SYSTEM", "password");

exception:
Exception in thread "main" java.sql.SQLException: Locale not recognized
    at oracle.jdbc.driver.T4CTTIoauthenticate.setSessionFields(T4CTTIoauthenticate.java:1006)
    at oracle.jdbc.driver.T4CTTIoauthenticate.<init>(T4CTTIoauthenticate.java:238)
    at oracle.jdbc.driver.T4CConnection.logon(T4CConnection.java:401)
    at oracle.jdbc.driver.PhysicalConnection.<init>(PhysicalConnection.java:553)
    at oracle.jdbc.driver.T4CConnection.<init>(T4CConnection.java:254)
    at oracle.jdbc.driver.T4CDriverExtension.getConnection(T4CDriverExtension.java:32)
    at oracle.jdbc.driver.OracleDriver.connect(OracleDriver.java:528)
    at java.sql.DriverManager.getConnection(DriverManager.java:664)
    at java.sql.DriverManager.getConnection(DriverManager.java:247)
    at data_coonnections.DataConnector.main(DataConnector.java:15)

A: Additionally changing Format(in Control Panel -> Clock and Region -> Region -> Format) to English (United States) did help.

A: Instead of changing the regional settings of the OS you can go to the "Advanced" tab (see the picture that you posted) and down to the "VM options:" field.
Enter -Duser.language=en -Duser.region=US.
You can also set -Duser.region=UK or what ever region is recognized.

A: The JDBC thin driver uses the Java's Locale to change your Database session language. For example I'm French, I live in France, when I connect to a Database in the US from my local system my Database session is in French. Why? That's because my Locale is configured this way. You can always override the default Locale to something else if your Locale isn't recognized by Oracle.


text:
Q: DISM Apply-Image out of Windows PE without formatting - loading screen I am looking for a way to reapply the wim image without losing any users data out of Windows PE. So far my script looks like that:
$TSProgressUI = New-Object -COMObject Microsoft.SMS.TSProgressUI
$TSEnv = New-Object -COMObject Microsoft.SMS.TSEnvironment

$OSDDownload = $TSEnv.Value("osDownload01")
$LogsDirectory = $TSEnv.Value("_SMSTSLogPath")

$wimImagePath = "$OSDDownload\install.wim"
$systemDriveLetter = "S"

Remove-Item -Path "$($env:_OSDDetectedWinDrive)Program Files\WindowsApps" -Recurse -Force -ErrorAction SilentlyContinue
Remove-Item -Path "$($env:_OSDDetectedWinDrive)ProgramData\Microsoft\Windows\AppRepository" -Recurse -Force -ErrorAction SilentlyContinue

$wimIndex = (Get-WindowsImage -ImagePath $wimImagePath | Where-Object {$_.ImageName -eq "Windows 10 Enterprise"} | select -property ImageIndex).ImageIndex
dism /Apply-Image /ImageFile:$wimImagePath /index:$wimIndex /ApplyDir:$($env:_OSDDetectedWinDrive)
#dism /Image:$($env:_OSDDetectedWinDrive) /Cleanup-Image /RestoreHealth /Source:$wimImagePath /LimitAccess

Get-Partition | Where-Object {$_.GptType -eq "{C12A7328-F81F-11D2-BA4B-00A0C93EC93B}"} | Set-Partition -NewDriveLetter $systemDriveLetter
cmd /c """$($env:_OSDDetectedWinDrive)Windows\System32\bcdboot.exe"" ""$($env:_OSDDetectedWinDrive)Windows"" /s $($systemDriveLetter): /f UEFI"

However, doesn't better what I try after the apply-image command, my windows installation afterwards stays in the loading screen. If I do a reset I receive the message "The computer restarted unexpectedly or encountered an unexpected error".
Any idea what I am doing wrong?
Thanks
md

A: Ok, the way I wanted it to work did not work. At the same time I didn't want to add the 21H2 Image as an extra upgrade package into SCCM because from 20H2 to 21H2 you only need the enablement package.
So here is what I did:
First I created a new package with all setup files from the disc but without the install.wim and I replaced the boot.wim with a 0KB boot.wim file. Additionally I added  the folder SMSTSPostUpgrade, which I took just from a previous Upgrade TS. This includes the SetupComplete.cmd and SetupRollback.cmd. But this was only for another intended way, see comments below. Finally I got a package size of around 275MB.
In my SCCM Task Sequence I did following steps:

*

*Downloading content:

I used the function "Download Package Content" to download once the Vanilla Install Image and the new created Setup content files. Both I saved with a variable (osImage; osSetup)

*Creating a hardlink to add the install.wim to the setup folder. Probably you could maybe also just move it there:
$TSEnv = New-Object -COMObject Microsoft.SMS.TSEnvironment

$OSDDownload = $TSEnv.Value("osImage01")
$OSDSetup = $TSEnv.Value("osSetup01")

 fsutil hardlink create "$OSDSetup\sources\install.wim"

"$OSDDownload\install.wim"

*I called the "Upgrade Operating System" function with the source path %osSetup01% and the Edition index 3 (in that case Enterprise)
After that I can use my task sequence also as a repair one.
Btw. Instead of the "Upgrade Operating System"  function I also tried a powershell script, but I couldn't find a way to manage the reboots:
#$TSProgressUI = New-Object -COMObject Microsoft.SMS.TSProgressUI

$TSEnv = New-Object -COMObject Microsoft.SMS.TSEnvironment

$OSDDownload = $TSEnv.Value("osImage01")
$OSDSetup = $TSEnv.Value("osSetup01")
$OSDUnattended = $TSEnv.Value("osUnattended01")
$LogsDirectory = $TSEnv.Value("_SMSTSLogPath")

$wimImagePath = "$OSDDownload\install.wim"
#$wimUnattendedPath = "$OSDUnattended\Unattend.xml"
#$systemDriveLetter = "S"

Remove-Item -Path "$($env:_OSDDetectedWinDrive)Program Files\WindowsApps" -Recurse -Force -ErrorAction SilentlyContinue
Remove-Item -Path "$($env:_OSDDetectedWinDrive)ProgramData\Microsoft\Windows\AppRepository" -Recurse -Force -ErrorAction SilentlyContinue

$wimIndex = (Get-WindowsImage -ImagePath $wimImagePath | Where-Object {$_.ImageName -eq "Windows 10 Enterprise"} | select -property ImageIndex).ImageIndex

#dism /Image:$($env:_OSDDetectedWinDrive) /Cleanup-Image /RestoreHealth /Source:$wimImagePath /LimitAccess

#dism /Apply-Image /ImageFile:$wimImagePath /index:$wimIndex /ApplyDir:$($env:_OSDDetectedWinDrive) /Apply-Unattend:$wimUnattendedPath
#Get-Partition | Where-Object {$_.GptType -eq "{C12A7328-F81F-11D2-BA4B-00A0C93EC93B}"} | Set-Partition -NewDriveLetter $systemDriveLetter
#cmd /c """$($env:_OSDDetectedWinDrive)Windows\System32\bcdboot.exe"" ""$($env:_OSDDetectedWinDrive)Windows"" /s $($systemDriveLetter): /f UEFI"

Write-Output "cmd /c start /wait $OSDSetup\setup.exe /ImageIndex $wimIndex /auto Upgrade /quiet /noreboot /EULA accept /Telemetry Disable /postoobe $OSDSetup\SMSTSPostUpgrade\SetupComplete.cmd /postrollback $OSDSetup\SMSTSPostUpgrade\SetupRollback.cmd /postrollbackcontext system /DynamicUpdate Disable /compat IgnoreWarning /InstallFrom $OSDDownload\install.wim"
cmd /c start /wait $OSDSetup\setup.exe /ImageIndex $wimIndex /auto Upgrade /quiet /noreboot /EULA accept /Telemetry Disable /postoobe $OSDSetup\SMSTSPostUpgrade\SetupComplete.cmd /postrollback $OSDSetup\SMSTSPostUpgrade\SetupRollback.cmd /postrollbackcontext system /DynamicUpdate Disable /compat IgnoreWarning /InstallFrom $OSDDownload\install.wim

return 3010


text:
Q: Laravel ajax pagination printing out entire site On my site's user pages, there's a section called "Reviews". In reviews, as you can imagine, there's a list of reviews for that user.
In the controller:
$reviews = Review::where('artist_id', $user->id)->orderBy('created_at', 'desc')->simplePaginate(5);

in the markup:
@if ($reviews->count())

Reviews

nextPageUrl() }}">
        @foreach ($reviews as $review)

            {{ $review->body }}

        @endforeach

{!! $reviews->render() !!}

@endif

Cool. It lists 5 reviews, then you have to click the pagination button which will refresh the page and show the next set of reviews.
However, I don't want users to have to refresh the page, so I'm trying out ajax.
JS:
$('body').on('click', '.pagination a', function(e){

    e.preventDefault();
    var url = $(this).attr('href');

    $.get(url, function(data){
        $('.reviews').html(data);
    });

});

Now this works. Kinda. Problem is, it'll inject the ENTIRE NEW PAGE into the reviews div. But hey, at least it brings up the right results.
How would I fix this so that the .html() method ONLY brings me the next set of results?

A: You could use the load() method to load page fragments and avoid loading the entire page
// container is the id of the returned reviews container
// Change it to your returned review container id
$( ".reviews" ).load( url +" #container" );

A: You can fix this by doing following steps;
In Controller
$reviews = Review::where('artist_id', $user->id)->orderBy('created_at', 'desc')->simplePaginate(5);

if(request()->ajax())
{
    return $reviews;    // in case of ajax, return only data instead of view
}
else
{
    return view('name-of-your-view', ['reviews' => $reviews])
}

JavaScript
$('body').on('click', '.pagination a', function(e){

    e.preventDefault();
    var url = $(this).attr('href');

    $.get(url, function(data){

        $('.reviews').empty();                  // make it empty first

        $.each(data, function(i, review){
            $('.reviews').append('
'+review.body+'
');
        });

    });

});

Explanation
Controller: We need to modify the controller that when request is ajax then it will return only $reviews collection instead of complete view.
JavaScript: When data is recieved, we will first empty the $('.reviews') div and then append new reviews divs.
Note
Above code may have syntax error because I did not type it on Code Editor and I also did not test it. But this is the correct method to solve your problem.


text:
Q: Can qplot directly display percentages without intermediate columns? I have a bunch of histograms to plot on data that is still coming. As the sample sizes vary, in order to compare them I need to plot the histograms with percentages not counts.
qplot (field, data=mydata, geom="histogram", binwidth=10)

the above qplot displays the counts. The density option is not applicable as it divides the counts within a bin to the bin's width, whereas I need to divide on the total number of samples.
I can precalculate a column containing the percentage, but it's cumbersome (I have many data sets).
Is there a better way to tell qplot to directly plot the histogram with percentages (ideally, also displayed as percentages (as 69%) and not as 0.69)?
Thanks!

A: try this:
ggplot(movies,aes(x=rating))+stat_bin(aes(n=nrow(movies), y=..count../n))+
scale_y_continuous(formatter = "percent")


text:
Q: Python Numpy - Matrix memory error and limits after I have been searching this topic on the web, I saw that I was not the only one to have this problem but I can't understand if there is a way to overcome the problem or not.
I have 5036 text files and a word list of 15985 words. For each word of the word list found on the text file, I would like to put a 1 on my matrix. But I get the error : MemoryError.
I tried also just to create the matrix and make a print (in case of a bug in my python code).. I got the same error.
Any suggestions?
matrix = np.zeros(shape=(5036,15985))

Edit: That's my code maybe there are some errors..
It should work in this way:

*

*create the dictionary from a file (each word on the text file is
names as "1_word1 2_word2 " etc, so splitting each line of the text
file I will have in split_[0] the position in matrix, in split_[1]
the word itself)

*for each text file it saves the number of the file in order to put
the right document on the matrix (each text file is named
"1_1A_out.txt   2_1A_out.txt etc")

*finally it prints the matrix.
import os
import re
import fileinput
import numpy as np

matrix = np.zeros(shape=(6000,16000))

def dictionary_creation (filepath):
    fileopen = open(filepath, "r")
    dictionary = fileopen.read().split('\n')
    fileopen.close()
    return dictionary

def find_doc_matrix_position (filename):
    regex = re.compile('(\d)_(.*)')
    find_regex = regex.search(file)
    if find_regex:
        pos_doc = int(find_regex.group(1))-1
    return pos_doc

def put_nbdoc_nbword_in_matrix (filename, dictionary, nb_file):
    for line in fileinput.input([filename]):
            line = line.replace("\n", "")
            for w in range(0,len(dictionary)-1):
                split_ = dictionary[w].split('_',1)
                if line == split_[1]:
#                    print ("nb_file is: "+str(nb_file))
#                    print ("nb_word is : "+str(split_[0]))
#                    print ("line is: "+line+" word is: "+split_[1])
#                    print '####'
                    matrix[nb_file,split_[0]] = 1

dictionary = dictionary_creation('C:\\Users\\KP\\Desktop\\FSC_lemmes_sort.txt')

for file in os.listdir('C:\Users\KP\Desktop\FSC_Treetag\out'):
        fin = open(file, 'r')
        filename = file
        nb_file = find_doc_matrix_position(file)
        put_nbdoc_nbword_in_matrix(filename, dictionary, nb_file)

print "this is the final matrix\n"
print matrix

A: You are getting a memory error probably because your matrix is too big, or you don't have enough available RAM memory in your computer.
You can try to iterate across all your text files, so you just need to create a matrix like:
matrix = np.zeros(shape=(15985))

and then save the result to a file for every of your texts.

A: Based on the specific error message:

File
  "C:/Users/KP/Desktop/FSC_Treetag/out/f3_test_from_files_to_matrix_fonctions.py",
  line 6, in  matrix = np.zeros(shape=(5037,15999)) MemoryError

You don't have enough memory to allocate the array.  Depending on your system, each value in your matrix will be using something like 8 bytes, so this array should only occuryp about 600 MB of memory... which really isn't much.  Likely there are other things (processes, open files, etc) that are eating up all of your system memory.
At the same time, since you are just finding whether each word exists or not in the file, you only need a single bit for each file-word entry in the matrix.  In that case you should simply use a bitarray (i.e. a single bit for each entry).


text:
Q: bootstrap icons not being displayed in internet explorer I'm using bootstrap, very new to it all. On my production side of things my icons are appearing fine, under safari and chrome they appear fine also. The code I use to link the icons to appear is as follows:
Users

The site is iskittle.co.uk if you view it other apart from IE the icons appear. I'm somewhat stumped...I guess it will have something to do with how IE is handling the how the CSS gets the images.
Like I said I am new to this but I think it gets the icons from a larger image http://iskittle.co.uk/images/icons/glyphicons-halflings-white.png
Why would chrome and safari be able to work out how to do this but no IE...any ideas/help would be great, I have done a lot of searching on the net but cant seem to a straight forward answer...

A: The font isn't loading as IE is unable to download the .woff file. Internet Explorer is much more picky about permissions to use fonts. To fix it, check:

*

*Make sure the file exists on the server and is accessible from http://iskittle.co.uk/font/fontawesome-webfont.woff.

*If it is already there make sure your IIS server is set up correctly to deploy woff files. In your web.config, make sure the following exists:
<staticContent>
      <remove fileExtension=".woff" />
      <mimeMap fileExtension=".woff" mimeType="application/octet-stream" />
</staticContent>

A: In your CSS File look for this:
@font-face {
  font-family: "FontAwesome";
  src: url("../font/fontawesome-webfont.eot");
  src: url("../font/fontawesome-webfont.eot") format("eot"), url("../font/fontawesome-webfont.woff") format("woff"), url("../font/fontawesome-webfont.ttf") format("truetype"), url("../font/fontawesome-webfont.svg#FontAwesome") format("svg");
  font-weight: normal;
  font-style: normal; }

Change this part:
src: url("../font/fontawesome-webfont.eot") format("eot"), url("../font/fontawesome-webfont.woff") format("woff"), url("../font/fontawesome-webfont.ttf") format("truetype"), url("../font/fontawesome-webfont.svg#FontAwesome") format("svg");

To this:
src: url('../font/fontawesome-webfont.eot?#iefix') format('embedded-opentype'), url('../font/fontawesome-webfont.woff') format('woff'), url('../font/fontawesome-webfont.ttf') format('truetype'), url('../font/fontawesome-webfont.svg#FontAwesome') format('svg');