Invalid hook call. Hooks can only be called inside of the body of a function component error

Question: For some reason I'm getting the invalid hook call error. It's the first time I've used hooks for a new component. I even commented out and/or removed the hooks from the code but it still gave the error. One other thing I can think of is that I am installing this component into the app by giving the direct file path like
"dependencies": {
  "br": "file.../br"
}

Which according to the docs could happen if there's 2 react versions? I'm not sure if that's the issue.
import React, { useState, useEffect } from "react";
import PropTypes from "prop-types";
import BrRelatedSearchCategory from "./bloomreach/br-related-search-category";
import BrRelatedProduct from "./bloomreach/br-related-product";
import {fetchBrSEO} from "../store/bloomreach/bloomreach-seo.actions";
export const baseClass = "sc-br";
const c = prefix(baseClass);

/* Each module can be individually not rendered by passing in the corresponding prop
*  hideRelatedSearches
*  hideRelatedCategories
*  hideRelatedProducts  */

export const BloomreachSEO = ({relatedSearches, relatedCategories, relatedProducts, fetchBrSEO, hideRelatedSearches, hideRelatedCategories, hideRelatedProducts}) => {
  // Fetch bloomreach data
  useEffect(() => {
    fetchBrSEO();
  }, [])

  const RelatedSearches = ({relatedSearches, hideRelatedSearches}) => {
    if (relatedSearches && !hideRelatedSearches) {
      return (

          Related searches

            {relatedSearches.map((relatedSearch) => {
              return (
                <BrRelatedSearchCategory
                  searchOrCategory={relatedSearch}
                  className={"search"}
                />
              )
            })}

      )
    }
    return null;
  }

  const RelatedCategories = ({relatedCategories, hideRelatedCategories}) => {
    if (relatedCategories && !hideRelatedCategories) {
      return (

          Related categories

            {relatedCategories.map((relatedCategory) => {
              return (
                <BrRelatedSearchCategory
                  searchOrCategory={relatedCategory}
                  className={"category"}
                />
              )
            })}

      )
    }
    return null;
  }

  const RelatedProducts = ({relatedProducts, hideRelatedProducts}) => {
    if (relatedProducts && !hideRelatedProducts) {
      return (

          Related products

            {relatedProducts.map((product) => {
              return (
                <BrRelatedProduct
                  relatedProduct={product}
                />
              )
            })}

      )
    }
    return null;
  }

  return (

      <RelatedSearches
        relatedSearches={relatedSearches}
        hideRelatedSearches={hideRelatedSearches}
      />
      <RelatedCategories
        relatedCategories={relatedCategories}
        hideRelatedCategories={hideRelatedCategories}
      />
      <RelatedProducts
        relatedProducts={relatedProducts}
        hideRelatedProducts={hideRelatedProducts}
      />

  );
}

BloomreachSEO.propTypes = {
  relatedSearches: PropTypes.array,
  relatedCategories: PropTypes.array,
  relatedProducts: PropTypes.array,
  fetchBrSeo: PropTypes.func,
  hideRelatedSearches: PropTypes.bool,
  hideRelatedCategories: PropTypes.bool,
  hideRelatedProducts: PropTypes.bool
};

BloomreachSEO.defaultPops = {
  hideRelatedCategories: false,
  hideRelatedProducts: false,
  hideRelatedSearches: false
}

export default page(
  state => ({
    relatedSearches: state["related-item"],
    relatedCategories: state["related-category"],
    relatedProducts: state["more-results"]
  }),
  {
    fetchBrSEO
  }
)(BloomreachSEO);

Answer: Looks like installing my local package by linking directly to it with
"dependencies": {
  "br": "file.../br"
}

was the issue. The issue was having 2 reacts one from the app and one from my local package itself. I used yalc instead and everything works fine now.


Rails : export to excel all that users are visible in the current page

Question: I am working on a Rails Project and I have the next issue :
I am have the users view, where is all users are listed and on click on every user i redirect to the view with all information about the clicked users, that's what i want to do is , to export all the users which is visible in that view to excel file with all the information about them.
So the columns will be something like this :
|id|name|notes|balance|
|1|user1|aasfs|33.44  |
|2|user2|aasfs|33.44  |
|3|user3|aasfs|33.44  |
I almost have done the logic for exporting the data on the controller :
users controller:
def index
    @users = User.all.page(params[:page]).order('created_at DESC').per(10)
    if params[:search]
      @users = Client.search(params[:search]).page(params[:page]).order('created_at DESC').per(10)
    end
  end

def export_to_csv
    @users = User.find(:all)
    csv_string = CSV.generate do |csv|
      csv << ["Id", "name","notes","balance"]
      @clients.each do |user|
        csv << [user.id, user.name, user.notes, user.balance ]
      end
    end

    send_data csv_string,
              :type => 'text/csv; charset=iso-8859-1; header=present',
              :disposition => "attachment; filename=users.csv"
  end

I know that i need to implement an if statement too, to export only the users with the same ID , but my proble is in the front end part:
    <%= link_to '#', { onclick: "$('#export_users').submit()", class:"btn btn-primary" } do %>
         Export
    <% end %>
    <%= link_to '#', { onclick: "$('#delete_users').submit()", class:"btn btn-danger" } do %>
        Delete
    <% end %>

          users

                Name

            <%= form_tag(delete_users_path, method: :post,:id => 'delete_users',) do %>
              <% @clients.each do |client| %>

                  <%= check_box_tag 'ids[]', client.id, false, :class => 'table-row-checkbox' %>
                  <%= link_to client.name, edit_client_path(client)  %>

              <% end %>
            <% end %>

How i can get and all the users ID's which is shown in the page (example we can have 30 users per page) and send request to the controller to export the users?
i am havin a form where i delete checked users, so i cant implement form in another form , so which is the best solution ? maybe to get the users ID with javascript ?
p.s sorry for my bad english, it is not my native language.
Comment: Could you post controller responsible for displaying users on the page?
Comment: Hey, You have the form already no need to create the new or other forms, Instead of it you can send the action name for doing operation, like export or delete.
It's not a good way to read all the ID's via JavaScript, You can submit the form, that will submit all the ID's which are selected on the form.
Comment: Yes but i want to get all the id's which is shown on the page, and not only the selected ones. Thank you
Comment: Then why you have added the check-box in your form ? Can you please tell me the reason.
Comment: the check-box is added for the delete functionality!
Answer: As you already have pagination in the index action, it is easiest to reuse the same logic, but output CSV instead of HTML.
You didn't specify Your Rails version, but with any recent version the fastest way to achieve this is using Rails's respond_to helper.
In your HTML create a link back to current page, but with different format:
<%= link_to "Download CSV", params.merge(:format => :csv) %>

And then modify the controller:
def index
  @users = User.all.page(params[:page]).order('created_at DESC').per(10)
  if params[:search]
    @users =   Client.search(params[:search]).page(params[:page]).order('created_at DESC').per(10)
  end

  respond_to do |format|
    format.html # renders HTML view
    format.csv do
      send_data users_to_csv(@users),
              :type => 'text/csv; charset=iso-8859-1; header=present',
              :disposition => "attachment; filename=users.csv"
    end
  end
end

def users_to_csv(users)
  CSV.generate do |csv|
    csv << ["Id", "name","notes","balance"]
    users.each do |user|
      csv << [user.id, user.name, user.notes, user.balance ]
    end
  end
end

This way, what ever pagination settings or searche you use, exactly the same set of users will be exported as CSV.
Note: I renamed the export_to_csv and made it return CSV string instead, so it would be more uniform which are helper methods and which are actual outputting actions.


Can't wrap my mind around css floats (divs floatup to / around an image) -

Question: The image is pulled in, then the posts.  I'd like the posts to float up next to the image and fill the space to the right.  I've tried various combos of the image float/left, the posts float/left or right, display:inline-block on things (I've also pulled the h3 just to muck around with it and it didn't matter).
I have a feeling it has to do with widths of the posts divs, because when I had the first post with very little text it would float up to the vertical version of a thumbnail (that got loaded), but if the post had a full chunk of text, forget it.
So what am I missing.  :)  Danke.
Comment: Put the `h3` tag before the image and set `.homefloat { width: 50%; }`
Comment: @Andy - You don't need to move the `h3` tag at all.
Comment: @Shauna I'm assuming OP wants the header above image, moving the h3 tag is better than using absolute positioning or negative margins to get it there
Comment: @Andy - Fair enough, though I'd note that the OP never mentioned anything about the `h3` that's currently next to the image.
Answer: You are correct, it does have to do with the width of your homeFloat divs.
Block level elements will make themselves as wide as their container by default. This will push them down under other containers when floated. In order to make them float next to other items, you need to specify a width (or a max-width), such that homeFloat + image + padding is equal to or less than the width of the container.
Edit: Also, make sure everything is properly wrapped in elements.
 tags will wrap around floated images like you're looking for, so it should be doable with a little reworking of your HTML.
Comment: `clear:both` only works on the elements that are above the element with `clear` on it. And no, there's not a solution with your current setup, at least not without JavaScript. You might want to experiment with your HTML structure to see what does and doesn't wrap how you want (I know plain `` blocks will wrap how you're wanting, for example).
Comment: So there is no real solution to having how ever many divs float up next to the image while the ones that don't make that cut and stay below the image take up the full space below that image.

I was trying to think if all the posts were just 'text' and not inside divs, would that wrap around the image.
I only mentioned the H tag because (and can't remember if I removed it or not) it had a clear:both; on it.
Comment: I went in and changed the html and stripped all the DIVS and put P tags around each post entry and now it is floating up like I wanted (nicely around the dynamic image that is being pulled in).  But it's nice to have someone to chat it out with.  :)  Thanks.
Comment: @KBarnes - Don't forget to mark answers to your question as "accepted" so that people will be more inclined to help you.
Comment: I thought I did as soon as I replied.  I have a big green check mark next to your answer, and a up arrow next to your second reply.
Comment: Yeah, it's there now. I submitted that comment before it registered that you accepted it.


How to format allowence of multiple whitespaces between characters in Regex more compact?

Question: I came up with this regEx to check if a IBAN is entered correctly into a field which also let's the user enter up to 4 whitespaces between character without causing an error.
^\s?\s?\s?\s?N\s?\s?\s?\s?\s?O\s?\s?\s?\s?([0-9a-zA-Z]\s?\s?\s?\s?){13}$

It works perfectly, but I want to get rid of the "\s?\s?\s?\s?" and format it more compact, I've tried  [\s?]{4} but that doesn't work.
What's the correct way to shorten this up?
The system I work with doesn't allow me to use any Javascript, I can only put pure regEx definitions to control entry into the field.
thank you
Comment: Try using `\s{0,4}` shortened `^\s{0,4}N\s{0,4}O\s{0,4}(?:[0-9a-zA-Z]\s{0,4}){13}$` https://regex101.com/r/o89Bzp/1 Note that `\s` could also match a newline
Comment: thank you! what does ?: do if I might ask? :)
Comment: It is a non capturing group.
Answer: You can shorten the repeating \s parts using a quantifier {0,4} to match 0-4 times a whitespace char and add an anchor $ to assert the end of the string to prevent a partial match.
If you don't need that value of the capturing group afterwards, you could make it non capturing (?: instead.
^\s{0,4}N\s{0,4}O\s{0,4}(?:[0-9a-zA-Z]\s{0,4}){13}$

Regex demo
If you don't want to match a newline, you could use [^\S\r\n]{0,4} instead of \s{0,4} but that would defeat the purpose of making the pattern smaller.


On calculating $\sigma(n^2) \pmod 4$ if $n$ is odd

Question: This will be my very first post in math.stackexchange, so please bear with me if I make any silly mistakes with my maths.
So, to proceed:  I am trying to calculate $\sigma(n^2) \mod 4$, given that $n$ is odd.
If I let $n = \displaystyle\prod_{i=1}^{r}{{p_i}^{{\alpha}_i}}$, then by considering the cases $p_i \equiv 1 \pmod 4$ and $p_i \equiv 3 \pmod 4$ separately (and taking the exponents ${\alpha}_i$ into consideration as well), I am led to the final congruence relation:
$$\sigma(n^2) \equiv (-1)^c \pmod 4,$$
where $$c = \left|\left\{i|1 \le i \le r, p_i \equiv 1 \pmod4, 2 \nmid {\alpha}_i \right\}\right|.$$
My question now would be:  Is this as far as we could go with this congruence?  I mean, is there no further possible improvement to this congruence, as far as computing $\sigma(n^2) \pmod 4$ for odd $n$ is concerned?
Appreciate any of your replies/feedback on this.
Edit:  In response to Marvis's inquiry as to what sort of improvement I am looking at - I am trying to determine whether $\sigma(n^2) \equiv 1 \pmod 4 \hspace{0.10in} XOR \hspace{0.10in} \sigma(n^2) \equiv 3 \pmod 4$, given that I also know that $4 \nmid \left(\sigma(n) - 2\right)$.
Comment: In response to Marvis, I am hereby copying my comment to his answer here:  I am trying to determine if either $\sigma(n^2) \equiv 1 \pmod 4$ XOR $\sigma(n^2) \equiv 3 \pmod 4$, given that I also know that $4 \nmid \left(\sigma(n) - 2\right)$.
Comment: To clarify, so far I have:  $\sigma(n^2) \equiv (-1)^c \pmod 4$, where $c$ is the number of $i$'s such that $1 \le i \le r$, for prime(s) $p_i \equiv 1 \pmod 4$ and the corresponding exponent(s) $\alpha_i$ is/are odd.
Answer: If $p \equiv 1\pmod{4}$, then $\sigma (p^{2 \alpha}) = 1 + p + p^2 + \cdots + p^{2 \alpha} \equiv (2 \alpha + 1)\pmod{4} \equiv (-1)^{\alpha}\pmod{4}$, since each term is $1 \pmod{4}$.
If $p \equiv 3\pmod{4}$, then $\sigma (p^{2 \alpha}) = 1 + p + p^2 + \cdots + p^{2 \alpha} \equiv 1\pmod{4}$, since $$1 + p + p^2 + \cdots + p^{2 \alpha} = 1 + p(1+p) + p^3(1+p) + p^5(1+p) + \cdots + p^{2 \alpha-1}(1+p)$$ and $1+p \equiv 0 \pmod{4}$.
Hence, $$\sigma(n^2) = \prod_{p_i-\text{primes of the form $4k+1$}} (-1)^{\alpha_i} \pmod{4}$$
Hence, if $\displaystyle \alpha = \sum_{i} \alpha_i$ where $\alpha_i$ is the highest power of prime $p_i$ of the form $4k+1$ dividing $n$, then $$\sigma(n^2) = (-1)^{\alpha} \pmod{4}$$
What sort of improvement are you looking at?
Comment: @ArnieDris $\alpha = 1 \implies (-1)^{\alpha} = -1$ and where did I say that $(p+1) \vert \sigma(p^{2 \alpha})$?
Comment: @ArnieDris No problem. I just wanted to point it out.
Comment: @ArnieDris Yes $\pmod{4}$. It was a typo.
Comment: I am trying to determine if either $\sigma(n^2) \equiv 1 \pmod 4$ XOR $\sigma(n^2) \equiv 3 \pmod 4$, given that I also know that $4 \nmid \left(\sigma(n) - 2\right)$.
Comment: Oops sorry, got confused.  Yes you're right.  How do I delete these comments?  :(
Comment: There, found the delete button.  Sorry about that...
Comment: Hi Marvis, I double-checked my calculations.  You're spot right on considering only the residues of $p \mod 4$.  However, in light of my current considerations (i.e. trying to relate $\sigma(n^2)$ to $\sigma(n)$) I would have to do it my way and consider the exponent $\alpha$ too.  Thus, my clarification(s) in my comments above.
Comment: Hey Marvis, is that really $\sigma(n^2) \equiv (-1)^{\alpha} \pmod n$?  Shouldn't it be just $\sigma(n^2) \equiv (-1)^{\alpha} \pmod 4$?
Comment: I apologize, I didn't realize that I forgot to accept your answer to my 'first' question here at MSE.  I would like you to know that I have already accepted it just now.


Sum of square representations

Question: How can I find the number of proper representations of a number n as a sum of 2 squares where $n \le 10000$ ?
How to calculate such a thing?
Comment: why $n \leq 10000?$
Answer: Since it looks more like a programming question and the upper bound on $n$ is very small, you can simply iterate over the $\sqrt{\frac{10000}{2}}\approx 70$ possible values of one of the squares and just check if the difference between $n$ and this square is a square too.
Even faster approach is to have two variables, one corresponding to the "(S)maller" (starting at $1$) and one to the "(L)arger" square (starting from the greatest possible value used in the representation) and keep moving them towards each other until they meet. In pseudo-code:

Let $S=1$ and $L=\sqrt{10000}$.
While $S\leq L$, calculate $S^2 + L^2$:

If the result is smaller than $n$, increase $S$.
If the result is greater than $n$, decrease $L$.
Otherwise it must be equal to $n$, so record one "successful hit" and increase $S$ and decrease $L$.
Answer: First of all, $n$ cannot have any prime factors $3$ modulo $4$. This is Fermat's Two Square theorem which you might want to check out.
Also, there is a function associated with this. See here: http://mathworld.wolfram.com/SumofSquaresFunction.html
Comment: If $n$ has a prime factor $p$ equivalent to $3$ mod $4$ it must occur to an even power in the prime factorisation of $n$. e.g. $12^2+6^2=180=2^2\times 3^2\times 5$ is divisible by $3$. If $n=p^{2a}r$ then the representations of $n$ correspond to the representations of $r$.

Sum of square representations


C# void ReceiveData(IAsyncResult iar)

Question: i would like some help with the following. this is to do with Asynchronous sockets.
from the sender:
<code>string stringData = "Welcome to my server server server";
byte[] message1 = Encoding.ASCII.GetBytes(stringData);

//MessageBox.Show(message1.Length.ToString());

client.BeginSend(message1, 0, message1.Length, SocketFlags.None, new AsyncCallback(SendData), client);
</code>
here as can be seen, the message.length can be found.
--
on the client:
<code>  Socket remote = (Socket)iar.AsyncState;
  int recv = remote.EndReceive(iar);
  string stringData = Encoding.ASCII.GetString(data, 0, recv);
</code>
my question is is there a way to access the actual length of the sent data and based on that call recieve data until the complete message is recieved?
Answer: No - TCP/IP is a stream protocol. Just because you've sent the data with one call doesn't mean it will be sent as one packet, or that it won't be merged with other packets. In other words, sending "X" then "Y" is equivalent to sending "XY" - they may well be transmitted with the exact same packets, indistinguishable to the other end.
If you want the idea of an individual "message" in a stream, you should prefix the data with a few bytes explicitly stating its length. (An alternative is to use a delimiter, but I far prefer using a length prefix - it makes it easier to know how much data you've still got to receive, you don't need to worry about starting to consume the next message, and you don't have to worry about escaping the delimiter in some form.)
Comment: instead of prefixing i just implemented a loop as stated here http://stackoverflow.com/questions/582550/c-begin-endreceive-how-do-i-read-large-data. it seems to be working! :)
Comment: You can only just keep looping if you want to receive all of the data until the socket is closed - otherwise you won't know when you've *actually* seen it all. That's fine if you're just doing a single request/response on the connection, but it doesn't work for a "conversation" type of protocol with multiple messages in each direction.
Answer: Only if something is transmitted to communicate the length - either pre-pend the length to the message, or send a terminator character of some kind.

C# void ReceiveData(IAsyncResult iar)


What's the biggest time saver you've implemented?

Question: Which changes that you have implemented did have the biggest impact on saving time in you daily sysadmin workload? What are your tricks to work more efficient and get more things done or work less for the same results?
I'm thinking about automation, changes in workflow/processes, new tools, stop doing some things altogether, outsourcing, better delegation, changing software/hardware, reducing bureaucracy, etc.
Comment: This question is off-topic under current topicality rules.
Answer: monitoring+alerting - which is great safety net. just as developers write unit tests to make sure things don't get messed up when they update code, i rely on monitoring as additional safety net just in case i screw something up [ that is disconnect a server, deny production traffic on firewall etc ]. it gives a peace of mind - if things break i will know before customers call.
Comment: Plus: we have a huge TV on the wall, showing rotating diagrams of our network (done with nagios and nagvis). Creates great visibility, and latest version of nagvis is a stunner. Gives your boss and your users the feeling that you are in control (which you are once you have this).
Answer: For me, it has been centralized authentication.
I got to the point that I was administering 40 or so Slackware machines, and each one had local authentication PLUS local Samba authentication. I also had a VPN solution where each account needed to be setup, plus an internal jabber server and an internal email server. Everything had its own account. MAC (Moves, Adds, Changes) were insane.
So I switched from Slackware to CentOS, created an Active Directory infrastructure, and used Likewise Open to authenticate all of my Linux machines against AD. It probably saved me 20 hours a month without joking even a little.
Now, I've got everything authenticated through AD that I can, and it works tremendously. I can't recommend centralized authentication enough if you're still doing things the bad old way.
Comment: chmeee: I don't know, as my infrastructure isn't as complicated as yours. I suggest you try it on a spare box. Likewise Open is free, and it makes no domain changes at all, other than adding the machine to the AD computers OU.
Comment: Do you know if likewise open will solve the problem with trusted domains that samba does? See http://serverfault.com/questions/35492/avoid-user-lookup-in-active-directory-trusted-domains-from-samba
Comment: Why AD and not OpenLDAP or the Redhat/Netscape one?  Is it predominantly a windows network?
Comment: Because I was familiar with AD and not OpenLDAP or Redhat Directory Server
Answer: I agree with the obvious choices here; Automation and central authentication. However, it appears that I have to be the guy to mention documentation.
By documenting as many problems, workflows, installations and guides as possible people were able to work through some of their issues without the need to get our department on it.
Another great time saver is issue tracking.
Being able to prioritize tasks, assign them to team members and getting rid of all the clutter of people sending in requests by email, msn or simply coming to the office. This also helps our good friends, the managers with seeing how efficient you are (if you want).
Then of course, the icing on the cake would be my 'RTFM' (Read the Fine Manual) mug that gets raised a lot.
Comment: Monitonring + Alerting are the "what".  Documentation is the "why".
Comment: Monitoring+Alerting imho is way better than documentation. It is implicit documentation (that is not that I dislike written docs). Agreed on issue tracking, couldn't do without
Comment: You can have all the monitoring and alerting you like but if you don't have any documentation about what to do when the pager goes off or notes on how to extend the monitoring then you'll be stuck answering all the pages and maintaining all of the monitoring yourself.  Documentation allows knowledge transfer so you can build your team and let others step in to share the work.
Answer: Infrastructure automation with a tool like Chef or Puppet is the best thing I've implemented on systems I manage. Monitoring is great and all, but often, getting the various bits to play nice with the rest of the infrastructure requires a lot of work. Chef and Puppet are both great at automating the entire infrastructure, providing a lot of glue that used to be written by hand. Particularly piecing together which servers provide what services.
Chef has, built in, the ability to query the server for attributes and recipes applied on other nodes, so you can ask who the production web servers are, or who the database master is, making automation much easier. Puppet can do this too, but it requires an external node classification tool like iClassify.
This should have obvious implications for monitoring and trending tools like Nagios and Munin. It can also, for example, provide automated configuration of load balanced environments, so the LB's can query all the web servers that need to be covered for a particular app.
The other big time saver I've implemented in a variety of environments is automated builds, like kickstart (redhat/centos) and preseed (debian/ubuntu). This should be obvious for most people, but it can be surprising how many sites still build systems from hand off CD. It's even better if the automated build gets the system ready to run Chef or Puppet to get all the other goods ready.
Comment: Configuration management ( I used puppet ) plus  PXE server (cobbler) were great time savers for me.
But the biggest time save has come from 'time management'
I found Tom Limoncelli's book 'Time Management for System Administrators' to be invaluable in this.
Now that my day is more structured and planned I spend less time 'planning' and procrastinating and more time just doing whats relevant.
Comment: Nice automation tools, but do you know of any tools similar to Chef or Puppet that are not based on Ruby?
Comment: @Android - cfEngine, but Chef and Puppet are nicer to work with, and so is Ruby :D.
Comment: Check out Bcfg2. It's similar in capability to Puppet but written in Python.
Answer: Multiple monitors, with a window open on the console of each server I was responsible for.
Comment: That will only scale so far.
Comment: Yes.  Though I could keep adding additional machines with additional monitors, but really you can only go so far.
Answer: Monitoring is great of course, but not sure it's a time saver.  For my money it was centralized logging, with a viewing system that filtered out the mundane, highlighted the dangerous (disk failure, virus scanner finds) and displayed everything else for categorization.
syslog (and perl) for the win.
It basically allowed me to read the event logs of all the computers on the network while eating my bagel; at least a cursory check to look for anything scary. Huge time savings.
Comment: I know its commercial but have a look at splunk, A log centralizing system with a wonderful front end.
Comment: +1 centralized logging and perl scripted reporting.
Comment: We're rolling out logcheck to our servers. It's taking a little while to add filters for lines we don't care about, but it is useful.
Answer: Removed local admin rights for all users.  (if I can)
This has had the effect of now I don't have to deal with any of the, how do I get X application to install (cause you are not allowed to now), my computer has a virus/spyware, my computer is running slow and pretty much anything related to that.
I never relized how stable this made the workstations until I came across one workstation that had been completely missed in the audits, windows updates, etc.  It had been running for about 4 years without a single update done to it.  I think I it was on Windows SP1.  That site never once complained about any issues with it and when I did discover it, I found it running great.
Comment: Let me just add that it doesn't work to bundle together _all_ users under a policy like this. If there are legitimate power users (e.g. developers) they need to be treated differently. If not, a) they can't do their job, and b) they'll subvert it anyway, causing other problems.

Thus, the policy needs to be aware of many types of users.
Comment: This is really good advice for a small company making the awkward transition into a medium-sized company.
Comment: Don't assume developers need admin access.  If they don't have admin access maybe then they will actually develop programs that worked properly as limited users (for a change).  There are users that do need it, thats why they would be given a second account to install software,etc so their daily account is still a limited user.  Much like how the Linux world works.  If they subvert it, that's easy, fire the first person, the rest will get in line real quick.  If they need something installed to do their job, then request what they need, not admin access.
Answer: Virtualization (VMware)
Between deploying servers from templates, managing servers from a single interface, detailed hardware monitoring built into the infrastructure client, it has really changed how we administer our infrastructure.
And the impact it has had on how we think of our "hardware" has really made it a game changer.  Clusters are no longer "too expensive" because we can deploy them virtually.  Need more Citrix servers, clone it.  As long as we keep our physical hardware farm providing adequate resources (and those servers are truly commodities now), everything is peachy.
Answer: cfengine for config management under debian/linux.
openvpn to connect the satellite stations
tighvnc through the vpn to reach the 2300 Windows Clients in the satellite stations.
munin and nagios for monitoring and reporting
smartmontools on the servers for automatic healthy checks (and status mails, if something goes wrong)
raid1 (mirroring) on the servers. If one disk fails, the server is still running - this ist really major for my time management.
Meta
TeamWork - It's useless to do all the things on your own. share the work and together your are more productive.
working atmosphere respect your mates, do jokes and laugh - this is enormous usefull for an positiv and creative atmosphere.
Enjoy your job! man, I love my job! This makes me really goog (I think ;))
Answer: For me it was to hire a very good sysadmin.
Answer: Puppet.  The idea of changing one place and having all the systems that are affected is fantastic.
Couple that with standard installs, and, it's very fast to bring a new system up.  You netboot and run a stock install, and then puppet takes over and everthing is configured.
Finally, standardize.  No, you really don't want 35 different linux distros and 4 different Solaris versions.  Work to move to one standard install.  Each unique system that you turn off saves you loads of time.
Answer: Add another vote for monitoring. The principle is quite simple: I want to know what's happening before the users are affected. System Administration should ideally be a transparent role. Users should neither know nor care about what you're doing. From their perspective it should just simply work. Happy and satisfied users should equal happy and satisfied admins.
One thing that is often overlooked in IT is that the computers are there to work for us, not the inverse. Nevertheless I know admins who spend a significant part of their day manually checking their servers and the logs. Why? Computers can monitor each other and with a little scripting you can have just the interesting part of the logs delivered to you. Really, you don't need to wade through a few million informational entries, such as Fred's print job or the DNS transfer was successful. Just tell me when they're not.
Answer: The biggest time saver I have implemented was Disk Imaging of our production workstations.  They are all the same and no one stores anything locally, so if there is a problem I just re-image the machine and it's all set to go, good as new.
Answer: Time saved is most important when systems are down.
I documented all support contract info in standardized text files in a standardized directory structure. I had one central and kept more than one copy around.
Each bit of information (web portal, phone number, point of contact, expiry date, contract number, phone menu shortcuts, etc.) where preceded by a standard tag in old .ini format (tag:data).
Finding a phone number was as simple as going to the top level directory and running:
<code>grep Phone */*support.txt | more
</code>
Where the first wildcard expanded to the vendor and/or product name.
I did not use Excel, Word, OpenOffice, a database, etc., etc., simply because when something is down, that something might be the very thing holding your support information. Also these are not easily viewable from a text mode console screen.
I also documented all how-to's in the same manner.
Comment: Upvoted for realizing the business value of time.
Answer: My biggest time saver, so far, has been SSH keys + ssh-agent + keychain as described in this
IBM article on OpenSSH key management
No more passwords for shells, scripts and scp.
NOTE: I still have a passphrase on my private key.
Answer: I implemented an IT Department Wiki (using Mediawiki for those interested) several years ago.  When we started getting comfortable using it, the reply to many questions asked around the office was "Did you check the wiki?"  It took a little time for us to get used to checking the Wiki for specific information, but once we did we realized it's great potential.  We have all the information we need right at our fingertips -- if there is something that isn't in there, we have the ability to add/change a page quickly.
Answer: I have to agree with pQd about monitoring.
Although we haven't seen the full benefits yet, implementing configuration management using Puppet is promising to save us a considerable amount of time and massively reduce mistakes.
Answer: I found AutoIt and later AutoHotkey and fell in love.
The last job I had was for a custom vehicle manufacturer.  The assemblers were minimally proficient computer users
and managed to crash the program they had to use to enter which job they were on.  Everyday, several times a day, I had to go around to 15+ workstations in 3 different buildings and kill the crashed program, relaunch it, and get it back to the data entry screen.  I eventually installed VNC so I could do it remotely which cut down on travel time but still involved me remembering to go in and reset the machines every so often.  When I found AutoIt, I realized I could set the program to watch the computer and if there hasn't been any input for 5 minutes, it could reset the program and type and click everything needed to get it back to the input screen.  Doing this saved me at least an hour a day and made finance very happy since less people complained about the computers being down and more people were entering their job data.
Answer: ++ for central auth and account management including account creation AND termination handling.  We have AD (two forests) and LDAP (and, until recently NDS) with various groups accessing resources existing in either directory.  The time we put into getting the directories in sync and getting all resources managed in one or other of the directories has been worth it in spades.
The next-biggest win has been any amount of automation whether it's account cleanups, config centralization, or what have you.
I'm not sure how much time actually monitoring saves but it's essential.  It doesn't take all that much for an environment to get big enough or complex enough for "manual checking" to be impossible and ineffective.  Plus, it's nice to sleep sometimes. ;)
This may be a bit off out of the main vein of thinking on this but we also had a huge win when we standardized our hardware platform.  We picked a server platform that was workable for all our OS in-house and have stuck with it for several years.  We learned the hardware and we learned the remote management of it and it saves time and energy in various  ways:

No more supporting half-dozen or more wonky types of servers each with their own quirks
Cross-team support: when it comes to hardware, the Unix folks know it, the Windows folks know it, even the network folks are familiar enough with it to pitch in a hand as needed since various of their appliances run on the hardware.
spare parts!

Same goes for standard, documented, and reviewed OS builds.  May seem basic but I bump with shops frequently where the builds aren't standard and there's no end of messing around to see if this tool or that tool is present or whether a particular server has its settings right.  That kind of chaos can turn even the most basic tasks and problems into firedrills.
Answer: Learning to delegate and trust my colleagues - once you know that you can hand off bits of work to other people life becomes much more relaxed. And not because I'm lazy and have everybody else do my work for me; it's the peace of mind that comes with knowing you have good backup. And, of course, well-monitored, standardized OS configurations on standard hardware. Goes without saying.
My goal for automation has always been that now again I get an email saying "Such-and such broke on server foo. It's been fixed." and then once I've sent the bug to the developers I can go back to reading the paper and drinking coffee. We're not there yet, but we've come a long way from the reactive chaos we used to fight through every day.
Answer: I recently implemented AntHill Pro at work and now have all our builds and deployments for a number of projects completely automated and tracked. This included creating a shared Tomcat deployment Ant library that all the projects use, simplifying the maintenance of those projects in AHP. Next up is creating a similar library for site CDA deployments.
While it doesn't save me time personally, it saves the time of our developers and our operations staff. I enjoy being the oil can for other people's wheels. :-)
I'm hoping to look at Chef and Puppet next to help out on the infrastructure side of automating things.
Oh, and documentation is HUGE help. It saves a lot of time to just point people to a well written document rather than answer the same question 20 times.
Answer: My biggest time saver was preseed scripts for the installation of our linux workstations. we have contractors coming and going all the time, so we have a pool of workstations that get re-used on a regular basis. When they come back to IT, we shove the install CD in, add the preseed file to the install command and within 20 minutes (and no further keystrokes from anyone of us) the box is back to a fresh, working base install, with all the tools and pre-configured to run in our network. Plug'n'play.


To what extent a song's words determine its music

Question: Imagine you want to compose music for a song and only for a single instrument: the piano. What are the guiding principles? How much freedom does one have in this process?
My reason for asking this question is partly curiosity and partly because I've recently been learning singing and I think if I know what rules guide the process of associating musical notes to the lyrics, I can match my voice to the pitch with more ease.
Case in point let's take a look at the song Shadow of Your Smile.

The first and the second verse follow a similar pattern but in the first, at "smile" the note drops to C sharp, but in the second, at "dreams" it drops to E. What causes this difference? If I swap the notes it will sound off so my question is how can one determine the notes without lots of trial and error?
Comment: are you asking about the lyrics or about the melody? Like thinking purely melodically just study basic harmonies and chord progressions and fit the melody to those. If you're talking about what notes correspond to what words, that's purely subjective and anyone can argue for anything.
Comment: Sorry, there isn't really any guidance here. There are some popular techniques related to setting words to music, but they mostly focus on the rhythm, not the notes chosen. Often a higher note will be used on an important word and notes may be higher or lower based on the sound of the word itself, but there's nothing to tell you exactly which note a word is meant to be sung at except the sheet music.
Comment: There's such a thing as [word painting](https://en.wikipedia.org/wiki/Word_painting) (or tone painting for music without lyrics, I guess), which makes the melody notes fit the lyrics better, but I'm not quite sure if that's what you're going for. At any rate, it seems rare in modern music and much more common in classical music.
Comment: "To what extent a songs lyrics determine it music" for a single instrument. If the answer to this is opinion based then the answer to "Does a given music match a given song" must be opinion based too.
Answer: music is a creative process - so there are no rules other than "it should sound pretty good".  music theory tries to capture some the the common ways composers do their thing.  but nobody has to follow those rules when writing their song.
but i'd say lyrics can definitely send the music in certain directions at least.  Lyrics are poetry so...

there are syllables that can contribute to the rhythm.
at the end of a phrase there is a pause that music can fill or punctuate.
Poetry has intonation (how it's read/sung), so that can lead to increases/decreases in volume and
changes in pitch as your voice naturally goes up or down saying certain things.

but that's just something you can do.  not rules.


How is the ideal $(x,y)$ isomorphic to $k[x, y]$ as $k[x, y]$-modules?

Question:
Let $R = k[x, y]$ where $k$ is a field and consider the ideal $I = (x, y)$ as a $R$-module.

Consider the $R$-module homomorphism $\varphi : R^2 \to I$ given by $\varphi(a, b) = ax + by$.

Prove that the kernel of $\varphi$ is the set $\{(−cy, cx) \mid c ∈ R\}$, and show that $\ker \varphi$ is isomorphic to $R$ as a $R$-module.

Deduce an isomorphism $R^2/R \cong I$.

I've figured everything out, but I'm bothered by the last statement.
We have $I \cong R^2/ \ker \varphi \cong R^2/R$ since $R \cong \ker \varphi$.
However, isn't $R^2/R \cong R$?
This would mean $I \cong R$, but $I$ is an $R$-module generated by two elements whereas $R$ is an $R$-module generated by one element.
Am I not understanding something?
Answer: Certainly, it is true that there are isomorphisms between $R^2/M$ and $R$ where $M$ is a free rank one submodule of $R^2.$ For example, $R^2/(R\oplus 0)$ or $R^2/(0\oplus R)$ are both isomorphic to $R.$ You are also correct that $I\not\cong R.$
The issue here is that there are many different ways to embed $R$ as a submodule of $R^2$ (equivalently, there are many $R$-submodules $M\subseteq R^2$ which are isomorphic to $R$), and the quotients of $R^2$ by different such $M$ need not be isomorphic. Indeed, as you've shown, there exists such an $M$ with $R^2/M\cong I\not\cong R$! So, writing $R^2/R$ is a little misleading.
An example of this phenomenon which might be more familiar is the following. Consider the ring $\Bbb{Z},$ and note $$\Bbb{Z}/\Bbb{Z}\cong 0$$ while on the other hand we have $$\Bbb{Z}/2\Bbb{Z}\not\cong0.$$ However, $\Bbb{Z}\cong2\Bbb{Z}$ as $\Bbb{Z}$-modules, via $n\mapsto 2n.$
So, given two $R$-modules $M$ and $N$ such that there exist $R$-submodules $N'$ and $N''$ of $M$ with $N\cong N'\cong N'',$ we cannot unambiguously write $M/N.$ We need to specify the embedding $N\to M$ which we are using to consider $N$ as a submodule of $M$!


Add JS to all webform

Question: I have a Drupal 9 custom theme and would like to attach a JS file on the webform.
Adding JS file in themename.libraries.yml does not work.
webform:
  js:
    theme:
      js/webform.min.js: {}

What is the right way to attach a JS file to the other module(webform)?
Answer: Adding lines to themename.libraries.yml is not enough to add the JS, you just declared a library doing this.
Now if you want to use that library on all your theme pages, you need to add in themename.info.yml
libraries:
  - themename/webform

But if you just need to attach the library to your forms, you can use  the hook_form_alter, target your webform ids and write
$form['#attached']['library'][] = 'themename/webform';
Comment: If this is the only solution I got, then I will add a JS if the form ID contains `webform_submission`. I can write something like this `if ( strpos($form['#form_id'], 'webform_submission') !== false ) { $form['#attached']['library'][] = 'myTheme/webform'; }`
Comment: Is the `hook_form_alter` for a specific form id? I want to load a JS file on all webforms.

Add JS to all webform


Rigorously proving $\displaystyle\int^{\infty}_0 \frac{\sin{x}}{x} dx= \frac{\pi}{2}$

Question: I want to prove the famous formula: $\displaystyle\int^{\infty}_0 \frac{\sin{x}}{x} dx = \frac{\pi}{2}.$ There are many ways to do it, for example, by some Fourier analysis. But how about a simple method: integrating just $e^{-xy}\sin{x}$ by $y$ and $x$ successively? Since $|\frac{\sin{x}}{x}|$ is not in $L^1$, Fubini-Tonelli theorem cannot be applicable at first glance. Is this way rigorously justifiable?
Comment: @JohnMa it's not quite a duplicate since the question is specifically **how to justify** the method in [this answer](http://math.stackexchange.com/a/5257/81360).
Answer: Here is one way.  Let
$$I(a)=\int_0^{\infty}\frac{\sin x}{x}e^{-ax}dx$$
Taking the derivative of $I$ yields
$$I'(a)=-\int_0^{\infty}e^{-ax}\sin x\,dx=-\frac{1}{a^2+1}$$
Integrating, we find that
$$I(a)=-\arctan(a)+C$$
Noting that $\lim_{a\to \infty}I(a)=0$, we see that $C=\pi/2$.  Thus,
$$I(0)=\pi/2$$
and we're done!


Raphael JS - Pie chart as color picker

Question: I use RaphaeJs to display colors extracted from an image in a pie chart.
I am looking for a way to display an alert (for exemple) when clicking on one of the covers that make up the chart.
I tried the code below but without success.
var clickSomeSlice = function() {
    console.log(this.attrs.fill);
};
for (var index_i = 0; index_i < myChartPie.covers.length; index_i++) {
    myChartPie.covers[index_i].click(clickSomeSlice);
}

Solved:
Rapahel JS generates covers with #000 fill color and it places it above each color, I found colors stored in series attribute which is constituted with colors and covers
for (var index_i = 0; index_i < myChartPie.covers.length; index_i++) {
    myChartPie.covers[index_i].click(function(){
        console.log(myChartPie.series[this.id-data.length].attrs.fill);
    });
}

Answer: edit
for (var index_i = 0; index_i < myChartPie.covers.length; index_i++) {
    myChartPie.covers[index_i].click(function(){
         // look in the console in javascript debugger to see if the object has a color
         console.log(this);
    });
}

Comment: thank you for answering but it always return #000 even if the color of the part where I click is red for exemple. I don't know where colors are stored.
Comment: Please check my edit. I suggest you display the object in the console so you can look if it has a color property

Raphael JS - Pie chart as color picker


Symbol is passed to 'raise'

Question: Code for context:
module Devise
  module Strategies
    class AuthxAuthenticatable < Authenticatable
      def valid?
        !params[scope].nil?
      end

      def authenticate!
        resource = mapping.to.authenticate_with_credentials(params[scope])
        return fail(:invalid) if resource.nil?
        success!(resource) if validate(resource)
      end
    end
  end
end

Warden::Strategies.add(:authx_authenticatable, Devise::Strategies::AuthxAuthenticatable)

Came across some code where a symbol is passed to raise:
raise(:invalid)

Doesn't look like there's any monkey patching of raise to handle symbol arguments. Seems like fail used to be used, and the code actually works if I use fail.
Isn't that just an alias for raise? Does this make sense in any context?
Comment: Yeah that should throw a `TypeError` with either `fail` or `raise`. Can you give more context? Any gems at play?
Comment: Thanks @hoffm. And yeah that's what I was thinking, posted some additional code above, essentially it's just a custom strategy for Devise
Comment: @hoffm looks like devise is using that syntax in some of its code as well
Comment: What version of Devise are you using? Looks like the latest doesn't do that https://github.com/plataformatec/devise/search?q=%22raise%22&type=&utf8=%E2%9C%93
Comment: @hoffm looks like it's mapped to the https://github.com/plataformatec/devise/blob/master/config/locales/en.yml file
Comment: @hoffm sorry, looks like they're using it with the fail method https://github.com/plataformatec/devise/blob/88724e10adaf9ffd1d8dbfbaadda2b9d40de756a/lib/devise/strategies/database_authenticatable.rb#L18
Comment: Ah, so it's just an implicit localization of a string then?
Comment: Must be something to that effect, but wouldn't the fail method have to be redefined somewhere to use a mapping scheme? Maybe they have their own gem at play...
Comment: Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/157016/discussion-between-drew-and-hoffm).
Answer: Looks like the fail method being used was the warden method:
http://www.rubydoc.info/github/hassox/warden/Warden%2FStrategies%2FBase:fail

Symbol is passed to 'raise'


Find the Keys in a Prolog Pairs List

Question: I currently have a list of (Key,Value) pairs and I want to pull out all the keys to use in another function.
Such that I have a list called
PairsList

and I want to
retractall(map(Key,_).

I have tried:
retractall(map(PairsList[(Key,_)],_).

but that just throws a syntax error.
Any help would be super!
Answer: retractall it's a powerful Prolog memory tool, useful for dynamic information managing, but it's important not to abuse of it. In your question, seems irrelevant. If you have a list of pairs (Key,Value) then

if you can use SWI-Prolog, there is this interesting library(pairs).
Instead of (A,B) uses A-B, but for the representation change you gain much. With that library, the builtin you would use is pairs_keys(Pairs, Keys)
without any library, the function (but it's a relation, not a function) is really easy to write in pure Prolog.
keys([(Key,_)|Pairs], [Key|Keys]) :- keys(Pairs, Keys).
keys([], []).

I think the best way is using maplist from library(apply), and a very simple predicate:
keys(Pairs, Keys) :- maplist(key, Pairs, Keys).
key((K, _), K).

note that this way we can reuse the logic abstracting from 'actual' pair representation: just add
key(K - _, K). to handle the preferred Prolog way
Answer: If you use SWI-Prolog and module(lambda), you can write
maplist(\X^Y^(X = (Y,_)), L, L1),

For example this code :
:- use_module(library(lambda)).

t(L, L1) :-
    maplist(\X^Y^(X = (Y,_)), L, L1).

gives
?- t([(1,a), (2,b), (3,c)], L).
L = [1,2,3].

Comment: beware the efficiency. lambda need still a bit of love, at least when I tested last time, there was no way to make the variable copy optional...
Comment: @chac: similar is true for `maplist/3`! Efficient support in SWI is still awaiting its realization.

Find the Keys in a Prolog Pairs List


Basic Vim - Search and Replace text bounded by specific characters

Question: Say I wanted to replace :
"Christoph Waltz" = "That's a Bingo";
"Gary Coleman" = "What are you talking about, dear Willis?";

to just have :
"Christoph Waltz"
"Gary Coleman"

i.e. I want to remove all the characters including and after the = and the ;
I thought the regex for finding the pattern would be \=.*?\;. In vim, I tried :
:%s/\=.*?\;$//g

but it gave me an Invalid Command error and Nothing after \=. How do I remove the above text? Apologies, but I'm new to this.
Comment: Do you need to keep the last semicolon? Because if you don't, you can just simplify the regex to:

:%s/=.*//g

And that would do the trick (note that the equality sign doesn't have to be escaped)
Answer: Vim's regular expression dialect is different; its escaping is optimized for text searches. See :help perl-patterns for a comparison with Perl regular expressions. As @EvergreenTree has noted, you can influence the escaping behavior with special atoms; cp. :help /\v.
For your example, the non-greedy match is .\{-}, not .*?, and, as mentioned, you mustn't escape several literal characters:
:%s/ =.\{-};$//

(The /g flag is superfluous, too; there can be only one match anchored to the end via $.)
Answer: This is because of vim's weird handling of regexes by default.  Instead of \= interpreting as a literal =, it interprets it as a special regex character.  To make vim's regex system work more normally, you can prefix it with \v, which is "very magic" mode.  This should do the trick:
%s/\v\=.*\;$//g

I won't explain how vim enterprets every single character in very magic mode here, but you can read about it in this help topic:
:help /magic


Django Admin save_model() creates a new object when I only try to edit

Question: My original issue was that I was trying to attach the current user to new entries, so I override the save_model method under admin.ModelAdmin to do
def save_model(self, request, obj, form, change):
    obj.submit_usr = request.user
    super().save_model(request, obj, form, change)

This works great when I try to create new object or new entry in my db, but when I try to edit the existing one, it still creates a new entry
my model looks like (I took out all the settings to avoid being messy here)
class AppUser(models.Model):
    app_name = model.CharField()
    submit_usr = models.ForeignKey()
    submit_date = model.DateTimeField()

I know that the change arg indicates if there's a change in existing entry, but I still don't have a way to tell Django that I only want to modify the current entry instead of creating a new one.
Any ideas how to achieve that?
Comment: Which button you clicking in Django admin to teste it? because your code is right, but maybe you clicking to Save a new one at django instando ok clicking save the currenty object
Comment: is the code right though? Shouldn't it be `super(AppUserAdmin, self).save_model(request, obj, form, change)`? or is that unnecessary in modern django/python?
Comment: @DiegoVinícius I do not see an "OK" button. the "Save", "Save and add another" and "Save and continue editing" are the only buttons I see
Comment: @NicholasClaudeLeBlanc I actually tried both. Both have the same effect. I'm not sure if things work inherently different in this case. I'm using django 2.0 btw
Comment: hmmm, I'm just looking through the source. I don't have time to run my own tests right now. try printing `form.is_valid()` `change` and `obj.id` and see what you get
Comment: @NicholasClaudeLeBlanc `form.is_valid()` = `True`, `change` = `True`, `obj` doesn't have `id` attribute, from the database, it seems like there's no autoincrementing value for id. `PrimaryKey` is linked to `app_name`. Does this make editing `app_name` impossible?
Comment: I'm not sure I follow, can you post the rest of the model?
Answer: You can try
def save_model(self, request, obj, form, change):
    if not change:
        obj.submit_usr = request.user
    super().save_model(request, obj, form, change)


HibernatePersistence class not found exception with JPA + Hibernate + OSGI

Question: I am facing problem with jpa + hibernate in equinox environment. I am getting exception
    Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter#53308cd' defined in OSGi resource[classpath:/spring/gdl-commons-db-jpa-context.xml|bnd.id=177|bnd.sym=gdl-open-domain]: Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter]: Constructor threw exception; nested exception is java.lang.NoClassDefFoundError: org/hibernate/ejb/HibernatePersistence
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:1037)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:983)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:487)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:458)
    at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveInnerBean(BeanDefinitionValueResolver.java:271)
    ... 34 common frames omitted
Caused by: org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter]: Constructor threw exception; nested exception is java.lang.NoClassDefFoundError: org/hibernate/ejb/HibernatePersistence
    at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:163)
    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:87)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:1030)
    ... 38 common frames omitted
Caused by: java.lang.NoClassDefFoundError: org/hibernate/ejb/HibernatePersistence
    at org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter.<init>(HibernateJpaVendorAdapter.java:57)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:526)
    at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:148)
    ... 40 common frames omitted

Please find below about my jars details
    com.springsource.javassist-3.15.0.GA.jar
hibernate-core-3.3.2.GA.jar
com.springsource.javax.transaction-1.1.0.jar
hibernate-core-4.1.9.Final.jar
com.springsource.org.hibernate-4.1.0.Final.jar
com.springsource.org.hibernate.annotations.common-3.3.0.ga.jar
hibernate-entitymanager-3.4.0.GA.jar
com.springsource.org.hibernate.annotations.common-4.0.1.Final.jar
hibernate-entitymanager-4.1.9.Final.jar
hibernate-annotations-3.4.0.GA.jar
hibernate-jpa-2.0-api-1.0.1.Final.jar
spring-data-commons-1.6.0.RELEASE.jar
hibernate-validator-4.0.2.GA.jar

My manifest.mf is
    Import-Package: org.springframework.data.jpa.domain.support;version="[
 1.3,2)",org.springframework.data.jpa.repository;version="[1.3,2)",org
 .springframework.data.repository;version="[1.5,2)",javax.sql,org.apac
 he.commons.pool;version="[1.5,2)",org.apache.commons.pool.impl;versio
 n="[1.5,2)",org.springframework.orm.jpa.persistenceunit,org.springfra
 mework.core.io,org.springframework.core.type.classreading,org.springf
 ramework.core.io.support,org.springframework.core.type.filter,org.spr
 ingframework.util,org.springframework.core.type,javax.persistence;version="1.0.1";jpa
 ="2.0",javassist.util.proxy;resolution:=optional,org.
 hibernate,org.springframework.orm.jpa,org.hibernate.ejb,org.springfra
 mework.orm.jpa.vendor,org.springframework.dao.annotation,org.springfr
 amework.jmx.export.assembler,org.springframework.jmx.support,org.spri
 ngframework.beans.factory.config,org.springframework.beans.factory.as
 pectj,org.hibernate.proxy,org.springframework.aop.aspectj.autoproxy,o
 rg.springframework.aop.interceptor,org.hibernate.ejb.connection,javax.persistence.criteria

Meta-Persistence: META-INF/persistence.xml
Spring-Context: spring/*.xml

Please help me to solve this class not found exception.
Thank you,
gopy
Edited:
Still i am facing problem now i am using hibernate-release-4.3.7.Final,
Okay let me explain my project structure and give me clue where i am missing,
Currently our system having one war file inside so many jar files. So i need to migrate to osgi and take out all business related jar to setup module concept.
So initially i take out some important library and converted to as bundle.
Lets say,
Bundle_A is a main bundle and inside contain lots of third party dependency including our application related library library_b, library_c etc.
All library imported as Bundle-ClassPath from Bundle_A,
library_b, library_c having own spring.xml with some configuration which are loading from Bundle_A
library_b, spring.xml having JPARepositoryImpl and configuration, We have some repositories in Bundle_A also referencing library_a implementation. Seems i am getting exception like JPARepositoryImpl class is not loading properly. Class not found exception.
Find some exception below please,
nested exception is java.lang.NoClassDefFoundError: com.domain.jpa.impl.MyRepositoryFactoryBean not found from bundle [My  Platform Domain (My--domain)]
Related cause: org.springframework.beans.factory.CannotLoadBeanClassException: Error loading class [org.springframework.data.jpa.domain.support.AuditingEntityListener] for bean with name 'org.springframework.data.jpa.domain.support.AuditingEntityListener' defined in null: problem with class file or dependent class; nested exception is java.lang.NoClassDefFoundError: org.springframework.data.jpa.domain.support.AuditingEntityListener not found from bundle [My  Platform Domain (My--domain)]
Related cause: org.springframework.beans.factory.CannotLoadBeanClassException: Error loading class [com.domain.jpa.impl.MyRepositoryFactoryBean] for bean with name 'communicationSettingRepository' defined in null: problem with class file or dependent class; nested exception is java.lang.NoClassDefFoundError: com.domain.jpa.impl.MyRepositoryFactoryBean not found from bundle [My  Platform Domain (My--domain)]
Related cause: org.springframework.beans.factory.CannotLoadBeanClassException: Error loading class [com.domain.jpa.impl.MyRepositoryFactoryBean]

..
..
.. etc
This is huge exception because i have lots of repository such as communicationSettingRepository, so its printing all repository name such as
Error loading class [com.domain.jpa.impl.MyRepositoryFactoryBean] for bean with name 'repository' defined in null

end of exception is
Caused by: java.lang.ArrayStoreException: sun.reflect.annotation.TypeNotPresentExceptionProxy
    at sun.reflect.annotation.AnnotationParser.parseClassArray(AnnotationParser.java:715)
    at sun.reflect.annotation.AnnotationParser.parseArray(AnnotationParser.java:522)
    at sun.reflect.annotation.AnnotationParser.parseMemberValue(AnnotationParser.java:348)
    at sun.reflect.annotation.AnnotationParser.parseAnnotation2(AnnotationParser.java:283)
    at sun.reflect.annotation.AnnotationParser.parseAnnotations2(AnnotationParser.java:117)
    at sun.reflect.annotation.AnnotationParser.parseAnnotations(AnnotationParser.java:70)
    at java.lang.Class.initAnnotationsIfNecessary(Class.java:3271)
    at java.lang.Class.initAnnotationsIfNecessary(Class.java:3278)
    at java.lang.Class.getAnnotation(Class.java:3219)
    at java.lang.Class.isAnnotationPresent(Class.java:3232)
    at org.hibernate.annotations.common.reflection.java.JavaAnnotationReader.isAnnotationPresent(JavaAnnotationReader.java:50)
    at org.hibernate.annotations.common.reflection.java.JavaXAnnotatedElement.isAnnotationPresent(JavaXAnnotatedElement.java:60)
    at org.hibernate.cfg.Configuration$MetadataSourceQueue.syncAnnotatedClasses(Configuration.java:3780)
    at org.hibernate.cfg.Configuration.secondPassCompile(Configuration.java:1411)
    at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1846)
    at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl$4.perform(EntityManagerFactoryBuilderImpl.java:852)
    at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl$4.perform(EntityManagerFactoryBuilderImpl.java:845)
    at org.hibernate.boot.registry.classloading.internal.ClassLoaderServiceImpl.withTccl(ClassLoaderServiceImpl.java:398)
    at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:844)
    at org.hibernate.jpa.HibernatePersistenceProvider.createContainerEntityManagerFactory(HibernatePersistenceProvider.java:152)
    at org.hibernate.ejb.HibernatePersistence.createContainerEntityManagerFactory(HibernatePersistence.java:67)
    at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:288)
    at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:310)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1571)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1509)
    ... 31 common frames omitted

Hope you guys can guess actuall issue? Please help me to solve this.
Answer: hibernate-entitymanager-4.1.9.Final.jar should the missing class. You have multiple versions of hibernate libraries in your classpath. 3.x and 4.x. I suggest you to download the latest hibernate version and replace them with the current classpath jars.
Also as a side note org/hibernate/ejb/HibernatePersistence is deprecated. org.hibernate.jpa.HibernatePersistenceProvider is the right persistence provider to be used if you are using JPA standard.
Comment: @AndyDufrense may you look at this question http://stackoverflow.com/questions/27602318/hibernate-myinterceptoronflushdirty-is-never-called pls?
Answer: Make sure you set the packaging parameter in your pom.xml; war for web project.
<packaging>war</packaging>. The web server needs this parameter set to war so that it can properly deploy your application with its dependendencies.


Should a small company block multicast on their network?

Question: Currently, the firewall at a small company is blocking multicast on their network. Should they continue to block multicast? Are there security concerns to unblocking it? Are there benefits to unblocking it?
Comment: What kind of firewall?  Are you sure it is even setup to route multicast if it wasn't blocked?
Answer: Blocking Multicast at the border has some good things going for it. Blocking it internally I personally don't agree with. This is an opinion.
Comment: If we're talking about IPv4 and routing it is going to be disabled by default, but on individual LAN segments it is pretty moot as you have to join the group to actually receive the traffic.
Answer: Here's a SANS article that might shed some light into Multicast security concerns.  Also, it might be a good idea to look around SF for past Multicast questions, and notice a pattern of issues that that might potentially affect your network.

Why does multicasting make the WAN inaccessible?
Why are my listener-less multicast packets affecting Wifi performance?
Answer: There's a valid argument for locking down all traffic types and only opening up what you need. I wouldn't personally extend that to blocking multicast internally on a small network but its arguably a matter of opinion (as sysadmin1138 says) rather than flat right or wrong.
If someone's blocked this as part of a policy to block everything and open up only the things they need then that seems perfectly rational to me.
If someone perceives a direct threat or issue from multicast then they may be absolutely correct (e.g. they had issues in the past and this is the fix) or they may be a little paranoid, which isn't the same as wrong.
If this block is in place however because someone doesn't know what they're doing and simply blocked everything that the CEO reckoned sounded "scary" then that's... not so good.
Answer: The only multicast apps I've ever used are the Ganglia monitoring tool and ntp on occasion (and that's not the default ntp configuration anyway).  It's not terribly clear to me how much multicast is really used these days on small networks like you describe so I'm not sure if blocking it matters too much.
At the same time, I don't see any reason to block it inside your network without a specific threat.  I vote for leaving it unblocked in your network.
I would say block it at the edge of your network just to be safe, although by default multicast isn't routed anyway unless you go through extra hoops.
Comment: Multicast is used quite heavily for mass operating system deployments and streaming broadcast video over a LAN. Of course neither of those are strong requirements for multicast in a small business LAN, but I'd hate to try and do them on a larger network without multicast.


Sql 2005 problem in set up

Question: When I setup sql2005 this problem appear Minimum Hardware Requirement (Warning) Messages Minimum Hardware Requirement
The current system does not meet the minimum hardware requirements for this SQL Server release. For detailed hardware and software requirements, see the readme file or SQL Server Books Online.
and I continued setup but I couldnot found sql management studio tools in start menue
Comment: are you sure the installation was completed, or did it abort because of the hardware constraints problem?
Answer: the minimum hardware requirements are only a warning, thus it shouldn't prevent you from installing sql server.  Are you sure you selected to install the client tools?  did you do a DVD or CD media install?  I think with the CD the client tools are on the second CD for 2005.
Follow these steps to add the client tools to your existing install.

Sql 2005 problem in set up


Custom usage message for many-valued argument

Question: Given sth. like (or similar to):
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("FILES", nargs="+", type=str)
args = parser.parse_args()

Now I'd like to have the many-valued positional argument FILES displayed in the usage message as
usage: cli.py [-h] FILES

instead of
usage: cli.py [-h] FILES [FILES ...]

Any step-by-step explanations or pointers are appreciated.
Comment: Upvoted because I don't know how to do this, but my opinion is that the default usage message is clearer and better.
Comment: @Rocky Li: I don't disagree with your assessment ...but I know it can be done -- wasn't able to figure out the "how" by myself, though.
Answer: This is the built-in behavior of the default formatter: source.
You could have your custom formatter with special handling for the nargs="+" type arguments:
import argparse

class CustomFormatter(argparse.HelpFormatter):
    def _format_args(self, action, default_metavar):
        get_metavar = self._metavar_formatter(action, default_metavar)
        if action.nargs == argparse.ONE_OR_MORE:
            return '%s' % get_metavar(1)
        else:
            return super(CustomFormatter, self)._format_args(action, default_metavar)

parser = argparse.ArgumentParser(formatter_class=CustomFormatter)
parser.add_argument("FILES", nargs="+", type=str)
args = parser.parse_args()

Would print out:
usage: cli.py [-h] FILES
cli.py: error: the following arguments are required: FILES

Answer: fbahr, I just decided to dive into the source code of argparse. I found out the formatting of the usage is hardcoded, look at it here. The only way you can override it is inheriting from HelpFormatter (the default class used when creating a new ArgumentParser instance) and say to the parser to use the class you created, to use your own formatter. You will have to override a "private" method (it is prefixed with an underscore) named _format_args, which is a little ugly and anti-pattern (in fact the only reason you can do that is because we are using Python) but it seems to be the only way to customize argparse the way you wanna do it.
import argparse

class NArgsCustomUsageHelpFormatter(argparse.HelpFormatter):

    def _format_args(self, action, default_metavar):
        get_metavar = self._metavar_formatter(action, default_metavar)

        if action.nargs == argparse.ONE_OR_MORE:
            result = '%s' % get_metavar(1)
        else:
            result = argparse.HelpFormatter._format_args(self, action, default_metavar)

        return result

parser = argparse.ArgumentParser(formatter_class=NArgsCustomUsageHelpFormatter)

parser.add_argument("FILES", nargs="+", type=str)
args = parser.parse_args()

The code above just change the default behaviour if the action to be formatted needs at least one argument (nargs='+'), otherwise it doesn't do anything different.

I hope this help you!
Comment: Modifying 'private' methods is how all the other `HelpFormatter` subclasses work.  In creating a subclass you are assuming the role of a developer with all its privileges and responsibilities (at least within your own programming domain).


Find absolute convergence of $\sum_{n=1}^{\infty}\left[{\frac{\sin{\frac 1 n}+\cos{\left({n\pi}\right)}}{n}}\right]$

Question: I have the following series:
$$\sum_{n=1}^{\infty}\left[{\frac{\sin{\frac 1 n}+\cos{\left({n\pi}\right)}}{n}}\right]$$
My textbook asks to determine the simple and absolute convergence of the series. Finding the simple (sorry, not sure what's the English term for it) convergence is easy enough:
$$\sum_{n=1}^{\infty}\left[{\frac{\sin{\frac 1 n}+\cos{\left({n\pi}\right)}}{n}}\right]=\sum_{n=1}^{\infty}\left[{\frac{\sin{\frac 1 n}}{n}}\right]+\sum_{n=1}^{\infty}\left[{\frac{\cos(n\pi)}{n}}\right]$$
The first series is positive and is asymptotic to $\frac 1 {n^2}$. The second one converges for the Leibniz rule.
My textbook though asks to check for the absolute convergence and it does the following passages:
$$\left|{\frac{\sin{\frac 1 n}+\cos{\left({n\pi}\right))}}{n}}\right|=\left|{(-1)^n\frac{1+(-1)^n\sin{\frac 1 n}}{n}}\right|=\frac{1+(-1)^n\sin{\frac 1 n}}{n}\sim\frac 1 n$$
I'm completely clueless about these passages. I am aware that both $\sin{\frac 1 x}$ oscillate between $-1$ and $1$ but I'm not sure if the textbook is grouping $(-1)$ and what rule it is following to do so. Any hints?
Comment: is that greatest integer or simple brackets
Comment: Cesare, you agreed in the first part that $\sin \frac{1}{n} \to 0.$ Therefore the alternating term in $\frac{1+(-1)^n\sin \frac{1}{n}}{n}$ vanishes.
Comment: $sin(\frac{1}{n})$ approaches zero as n becomes larger
Comment: BTW: A very nice proof. Could you write the author of this textbook, please?
Comment: @PrzemysławScherwentke it's by an Italian author Marco Bramanti: Analisi matematica 1
Answer: Because $\cos(n\pi)=(-1)^n$ and $1=(-1)^{n}(-1)^n$, we have
$$
\left|{\frac{\sin{\frac 1 n}+(-1)^n}{n}}\right|
=\left|{(-1)^n\frac{(-1)^n\sin{\frac 1 n}+1}{n}}\right|=\frac{1+(-1)^n\sin{\frac 1 n}}{n}\sim\frac1n+(-1)^n\frac1{n^2}\sim\frac 1 n
$$
But the harmonic series is divergent.
Answer: Another approach is via the inequality $|a-b|\ge |a|-|b|.$ This gives
$$\frac{|(-1)^n-\sin(1/n)|}{n} \ge \frac{|(-1)^n|-|\sin(1/n)|}{n} = \frac{1-|\sin(1/n)|}{n}.$$
Since $\sin(1/n)\to 0,$ the term on the right is greater than $\dfrac{1/2}{n}$ for large $n,$ proving the series of absolute values diverges.


Como fazer com que o cursor esteja no Text ao inicio do programa?

Question: Gostaria de saber como fazer piscar o cursor num objeto tkinter.Text quando eu faço andar a aplicação, porque normalmente nenhum widget é selecionado. Gostaria de ter o mesmo efeito dum terminal quando é ligado, onde se vê o cursor piscar.
Este é o código que estou utilizando, mas não funciona:
self.prompt = tkinter.Text(self.root, bg=self.bg, fg=self.fg, insertbackground=self.fg)

self.prompt.insert(tkinter.END, self.PROMPT_M)
self.prompt.bind('<Return>', self.add_prompt)

self.prompt.pack()
self.prompt.focus()

Answer: Utilize Entry.focus()
from tkinter import *

root = Tk()
text = Text(root)
entry = Entry(root)
entry.pack()
entry.focus()

root.mainloop()


Logarithmic scaling / colorbar in Julia using PyPlot (matplotlib)

Question: I am using Julia 0.5 and the latest version of PyPlot.
I am printing an 2D-Array using plot.pcolorand it works pretty good. But now I have data that needs a logarithmic scaling. I searched on the web and what I found was an example using
plt.pcolor(X, Y, Z1, norm=LogNorm(vmin=Z1.min(), vmax=Z1.max()), cmap='PuBu_r')
But since LogNorm seems to be a python function ist doesn't work in Julia. Does anyone have an idea what I can hand over to norm=to get a logarithmic scaling?
An example would be:
using PyPlot
A = rand(20,20)
figure()
PyPlot.pcolor(A, cmap="PuBu_r")
colorbar()

Comment: If this is not implemented in julia's pyplot, you have to implement it yourself. It's a fairly easy function to port. [See here](https://github.com/matplotlib/matplotlib/blob/84d979b9b55d5165630aa4e7d5ca1b30fb52e420/lib/matplotlib/colors.py).
Answer: Matplotlib fields and methods can be accessed using the
matplotlib[:colors][:LogNorm]

syntax (i.e. for the corresponding matplotlib.colors.LogNorm object).
UPDATE: Thank you for your mwe. Based on that example, I managed to make it work like this:
PyPlot.pcolor(A, norm=matplotlib[:colors][:LogNorm](vmin=minimum(A), vmax=maximum(A)), cmap="PuBu_r")

Comment: Works perfect! Thanks a lot!
And I totally understand that it's much easier to find a solution if one has got a simple example of what the problem is :-) Just didn't thought about it immediatly.
Comment: Ok, I added an example.
Comment: Many thanks. I updated my answer. Also, just in case you might think I was refusing to answer until you provided a trivial example (which something in my gut tells me might be the case, heheh, I might be wrong!), you might think that was a trivial example, but actually I don't use PyPlot that much so it was helpful to have something to play with, that was guaranteed to both work and be along the lines of what you were looking for. So thanks again for updating your question with one.
Comment: also, just pointing out `minimum` and `maximum` are the equivalent julia methods for finding the minimum and maximum of a collection. (`min` and `max` julia functions also exist, but they do something slightly different).


Open Sans installed by default on all major OS's

Question: Do all major operating systems have Open Sans installed by default? Ie, if my website uses Open Sans will it display on:

Windows
Mac OS
Linux
iOS
Android
Answer: Short answer: no.
Longer answer: No, it is not installed on every operating system. If you website relies on a particular font, ensure that font gets loaded even if the OS is supposed to come with it, because you need a specific version. You want to rule out even the possibility of one flavour of linux using version 1.1 while another uses 3.4.1230 and looking wildly different. So use <code>@font-face</code> and load the exact version you need.
As a bonus, that will even override your own locally installed copy, so you are guaranteed to be looking at the same thing your users will be.


gcda files are not generated while running the functional test cases on the instrumented image

Question: I am trying to generate the coverage for C files (Yocto project).
So, I have added gcov flags "-g -O0 --coverage" in the Makefile.am of most of the available modules.
It generated ".gcno" files during the compilation of each module with coverage flags.
I have generated an image from all these modules and loaded it in the test device and ran functional test cases.
I am able to find the path of the "gcda" files using strings command from the process that is running the test device.
So I have used gdb mode to flush the coverage using the "__gcov_flush" command after attaching the process id to gdb.
This throws an error "No symbol __gcov_flush in current context". Please suggest me what may be the cause for this error.
Comment: Not a makefile question. Removed incorrect tag.
Comment: Please have a look at your build log (enable verbose mode if you don't see any commands) and then add an example compiler command line, i.e. from a module where you expect `--coverage` to be used, and a linker command to your question text. For coverage to work you'll need it to be enabled in the compilation **and** linking command lines.
Comment: Thanks for the reply Stefan Becker.

Actually I am building a yocto image so using bitbake to compile the code. So there is no make command line to add debug mode.

The compilation generated .gcno successfully for a module. While running the functional test cases for the module, .gcda files are not generated.
Comment: Are you trying to get coverage for Linux Kernel or driver module?
Comment: Yes Ameya. We are trying to get the coverage for Yocto modules (both kernel and driver)
Answer: As per the comments it is not directly possible to just build the Linux Kernel with the Coverage Compiler flags and assume to get meaningful coverage metrics.
The Code Coverage metrics actually require some file systems to be available to write the run-time coverage data(i.e. *.gcda files).
If you want to enable Code Coverage for Linux Kernel here is a documentation on how to go about enabling the support using a GCOV virtual filesystem to collect coverage metrics.
Also, assuming you are cross compiling for a different architecture then probably you will have to use a cross-gcov tool to collect the coverage metrics, after you have captured the *.gcno files after execution.


EF Core DB-first: How to delete dependent item without cascade delete?

Question: (Example code is posted at the end.)
I'm using EF Core 5 database-first (i.e. reverse engineered POCOs). When 'deleting' an item in a collection using .Remove(), a subsequent SaveChanges() complains about the orphaned child. Yup, plenty of Q&A can be found about that.
For code-first scenarios, one can add this to the configuration (from here):
modelBuilder.Entity<Child>.HasKey(t => new { t.ParentId, t.ChildId });

but it is not practical for DB-first. If the database has cascade delete set up for the FK relationship (docs reference here), the generated model [correction] does not include
entity.OnDelete(DeleteBehavior.ClientSetNull)

and the delete (using .Remove()) does work, including SaveChanges(). But ...
The problem I face here is that this "solution" requires all our FK relationships to be configured with cascade delete in the database. Yikes!  Data integrity is important to us and safeguarding it with UNIQUE constraints and non-nullable FK relationships has saved us before. Not having cascade deletes set up is a similar safeguard, and using it only for the severed relationship case is arguably overkill.
So, on to the third option: Explicitly delete the orphaned child item, noting that I'm in the second bullet described here. All I need is the good old ObjectContext.DeleteObject() but there is no EF Core equivalent.
Q: How can I delete that child item? And if it is not possible, do I have any other options?
Here is a quick example the brings it to life in code:
//Create a parent with two children
var db = new Context();
var newParent = new Parent() {Name = "NewParent"+DateTime.Now.Second};
db.Parents.Add(newParent);
newParent.Children = new List<Child>() {new Child() {Name="ChildOne"}, new Child() {Name="ChildTwo"}};
db.SaveChanges();
db.Dispose();

//Pick a parent item and delete one child item
var db2 = new Context();
var Parent = db2.Parents.First();
db2.Entry(Parent).Collection(f => f.Children).Load();
var ChildToDelete = Parent.Children.First();
Parent.Children.Remove(ChildToDelete);
db2.SaveChanges(); // -----> FAILS with "The association between entity types 'Parent'
                   // and 'Child' has been severed, but the relationship is either marked
                   //  as required or is implicitly required because the foreign key
                   // is not nullable."

and the tables are essentially
CREATE TABLE [dbo].[Child](
    [ChildId] [int] IDENTITY(1,1) NOT NULL,
    [ParentId] [int] NOT NULL,
    [Name] [nchar](20) NOT NULL,
 CONSTRAINT [PK_Child] PRIMARY KEY CLUSTERED)

CREATE TABLE [dbo].[Parent](
    [ParentId] [int] IDENTITY(1,1) NOT NULL,
    [Name] [nchar](20) NOT NULL,
 CONSTRAINT [PK_Parent] PRIMARY KEY CLUSTERED)

ALTER TABLE [dbo].[Child]  WITH CHECK ADD  CONSTRAINT [FK_Child_Parent] FOREIGN KEY([ParentId])
REFERENCES [dbo].[Parent] ([ParentId])
ALTER TABLE [dbo].[Child] CHECK CONSTRAINT [FK_Child_Parent]

Answer: Instead of removing the Child from the Parent's collection
Parent.Children.Remove(ChildToDelete);

delete the child with
db.Set<Child>().Remove(ChildToDelte);

Comment: Oh!  `ICollection.Remove(T)` vs. `EntityFrameworkCore.DbSet.Remove(T)`. Two quite different `Remove()`'s
Comment: What if you do not have access to the data context? In a DDD based model there is no knowledge or access to persistence from inside the model, so what are the alternatives? Doesn't EF detect the removal of the child from the collection? In my case it does but it tries to set the foreign key to null, even if I set the relationship to cascade or even client cascade. Does this not work at all for database first?
Comment: You don't access the DbContext from the model, but from some service which wraps the DbContext.


How to find the sum of the three digits of a number $N$ that gives the same remainder when $2272$ and $875$ are divided by it

Question: On dividing $2272$ as well as $875$ by three digit number $N$, we get same remainder.  What is the sum of the digits of $N$?
I cannot start hit and trial method here, so how should I do this?
Thanks.
Comment: Hint. What can you say about their difference ?
Answer: You should start by putting "into math" what you know, which is
$2272 = a N + X$
$875 = b N + X$
Here a,b are positive integers and X is the common remainder.
Substracting these two we get
$1397 = c N $
with c a positive integer. There are multiple ways to continue, but the easiest here would be to look at the prime factors of 1397 (because you know you can write 1397 as the product of two integers (c,N))
Comment: Not too systematic, but given 1270+127=1397=127 x 11, netting a 1.


How to solve or workaround the integration?

Question: From statistical mechanics I've found $ \left( c,\alpha \in \mathbb{R}^+ \right) $:
$ lnZ = c\int_0^\infty dx\ x^2ln\left( 1 + e^{-\alpha x^2}\right) $
what I performed a integration by parts to get:
$ lnZ = \dfrac{2\alpha}{3}c\int_0^\infty dx\dfrac{x^4}{1 + e^{\alpha x^2}} $.
Every exercise in quantum gases (fermions/bosons) lead me to this integration in classical limit. I try to solve it via Taylor's polynomium around $x=0$ because it's a integration limit value. The first term which will not vanish (get 0 value in $x=0$) is in $\frac{d^4f}{dx^4}\left( x\right) = \frac{4!}{24!}x^4\ $ what take me a divergence in the integration.
Other way I've tried is apply Taylor's to $ ln\left( 1+e^{-\alpha x^2}\right) $ at $x=0 $ what is the same to span $ ln\left(1+x\right) $ around $ x=1 $:
$ \int ln\left(1+x\right) dx = ln2 +\sum_{k\in\mathbb{N}}\left( -1 \right)^{k+1}\dfrac{\left( x-1 \right)^{k}}{k\left( k+1 \right)} $.
Using test of $\ \ lim_{k\rightarrow\infty}\left| \frac{A_k}{A_{k+1}} \right| < 1 \ \ $ I conclude this converges on $ x\in\left( 0,2\right) $.
My questions:

The integration was solved and the result is valid just for $ x\in\left( 0,2\right) \Rightarrow e^{-\alpha x^2}\in\left( e^{-4\alpha}, 1\right) $. Is this conclusion right?
I feel Like is something going wrong in my solution. Else way to solve this integration or workaround it?
Answer: $\newcommand{\bbx}[1]{\,\bbox[15px,border:1px groove navy]{\displaystyle{#1}}\,}
 \newcommand{\braces}[1]{\left\lbrace\,{#1}\,\right\rbrace}
 \newcommand{\bracks}[1]{\left\lbrack\,{#1}\,\right\rbrack}
 \newcommand{\dd}{\mathrm{d}}
 \newcommand{\ds}[1]{\displaystyle{#1}}
 \newcommand{\expo}[1]{\,\mathrm{e}^{#1}\,}
 \newcommand{\ic}{\mathrm{i}}
 \newcommand{\mc}[1]{\mathcal{#1}}
 \newcommand{\mrm}[1]{\mathrm{#1}}
 \newcommand{\pars}[1]{\left(\,{#1}\,\right)}
 \newcommand{\partiald}[3][]{\frac{\partial^{#1} #2}{\partial #3^{#1}}}
 \newcommand{\root}[2][]{\,\sqrt[#1]{\,{#2}\,}\,}
 \newcommand{\totald}[3][]{\frac{\mathrm{d}^{#1} #2}{\mathrm{d} #3^{#1}}}
 \newcommand{\verts}[1]{\left\vert\,{#1}\,\right\vert}$

$\ds{\ln\pars{Z} = {2\alpha \over 3}\,c
\int_{0}^{\infty}\dd x\,{x^{4} \over 1 + \expo{\alpha x^{2}}}:\
{\LARGE ?}}$.

\begin{align}
\ln\pars{Z} & =
{2\alpha \over 3}\,c\int_{0}^{\infty}\dd x\,{x^{4} \over 1 + \expo{\alpha x^{2}}}
\,\,\,\stackrel{\alpha x^{2}\ \mapsto\ x}{=}\,\,\,
{c \over 3\alpha^{3/2}}\int_{0}^{\infty}
{x^{3/2} \over \expo{x} + 1}\,\dd x
\\[5mm] & =
{c \over 3\alpha^{3/2}}\int_{0}^{\infty}
x^{3/2}\pars{{1 \over \expo{x} + 1} - {1 \over \expo{x} - 1}}
\,\dd x +
{c \over 3\alpha^{3/2}}\int_{0}^{\infty}
{x^{3/2} \over \expo{x} - 1}\,\dd x
\\[5mm] & =
-\,{2c \over 3\alpha^{3/2}}\int_{0}^{\infty}
{x^{3/2} \over \expo{2x} - 1}
\,\dd x +
{c \over 3\alpha^{3/2}}\int_{0}^{\infty}
{x^{3/2} \over \expo{x} - 1}\,\dd x
\\[5mm] & =
-\,{2c \over 3\alpha^{3/2}}\bracks{2^{-5/2}\int_{0}^{\infty}
{x^{3/2} \over \expo{x} - 1}
\,\dd x} +
{c \over 3\alpha^{3/2}}\int_{0}^{\infty}
{x^{3/2} \over \expo{x} - 1}\,\dd x
\\[5mm] & =
{\pars{1 - 2^{-3/2}}c \over 3\alpha^{3/2}}\
\underbrace{\int_{0}^{\infty}
{x^{3/2} \over \expo{x} - 1}\,\dd x}
_{\ds{\underbrace{\Gamma\pars{5 \over 2}}_{\ds{3\root{\pi}/4}}\zeta\pars{5 \over 2}}}\ =
\bbx{{1 - 2^{-3/2} \over 4}\root{\pi}\zeta\pars{5 \over 2}
\,{c \over \alpha^{3/2}}}
\end{align}

See Mellin-type Integrals.
Comment: There's something wrong. I don't understand why MSE-system is repeating my answer.
Comment: Thanks for the solution and most thank you for Mellin-type Integrals citation. I did your steps using $u=\alpha x^2 \Rightarrow x = \sqrt{\frac{u}{\alpha}}$ and it's missing a factor $ \frac{1}{\sqrt{\alpha}} $.
Comment: @EnriqueRené Fixed the  $\displaystyle\alpha$-missing factor. Thanks.


onClick change list styles

Question: Let's say I have a simple list:

1

2

3

Can I onClick of one "li" change styles of all li's except the one clicked?
So if I click "li" number 2, then the list will look like:

1

2

3

So if I click on first "li" then it will have clicked class, while others will be notClicked.
In case you want to play with it, here's jsbin: http://jsbin.com/ucuca4/edit
Make either in Prototype or plain JavaScript.
Answer: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

        <title></title>

                1

                2

                3

Answer: Why change the style of the other? You may want to change the style of the clicked element.
If so, you can use jQuery for that
Example:

element 1

element 2

element 3

$('.notClicked').click(function()
{
    $(this).addClass('active');
});

Comment: because I need to change others too :)
Comment: So you want the others to have a different class also when an element is clicked?
Answer:

1

2

3

Comment: Changing class using the setAttribute method is not supported in Internet Explorer 7 and below. Always work with className DOM attribute.
Comment: @Peter Mortensen: I saw you love to format question and answer good great way.

onClick change list styles


How do I stretch nav bar up while leaving logo where it is?

Question: I'm wanting the blue on the navigation bar to go to the top so it covers the grey but not so it covers the border, I also want the logo to remain where it is.
Code is here. http://pastebin.com/YDM1PFMe
Comment: Change margin-top to padding-top on your .sideimage class.
Answer: You need to change the margin-top to a padding-top otherwise the margin is just pushing the content down 50px.
.sideimage {
    text-align: center;
    padding-top: 50px;
}

Here's a JS Fiddle https://jsfiddle.net/0w742c4f/1/
Answer: Remove the margin here:
.sideimage {
    text-align: center;
    //margin-top: 50px;
}

See fiddle: https://jsfiddle.net/DIRTY_SMITH/7oe5kh9L/35/
and I think your desired effect would be to use padding-top instead:
.sideimage {
    text-align: center;
    padding-top: 50px;
}

See fiddle: https://jsfiddle.net/DIRTY_SMITH/7oe5kh9L/36/


How to make the function of the planes from the lorenz attractor

Question: How can I make the equation for the planes of the wings of the lorenzattractor,
I know that the critical point should be used.
But I don't know how I should make this plane, the figure shows in yellow which plane I want.
Answer: The "wings" don't lie in a plane; the predominantly blue portion on the right of your image seems to indicate that clearly. You can linearize the system at the unstable fixed points to figure out how the system behaves like a linear system near those points, though. The plane that I suspect you are talking about is somewhat akin to a tangent plane to a surface.
To do this, first define
$$
 \vec{F}(x,y,z) =
  \left(\begin{matrix}
    u(x,y,z) \\
    v(x,y,z) \\
    w(x,y,z)
\end{matrix}\right)
 =
\left(\begin{matrix}
    \sigma(y-x) \\
    x(\rho-z)-y \\
    xy-\beta z
\end{matrix}\right),
$$
then compute the Jacobian of this function
$$
  \frac{\partial (u,v,w)}{\partial (x,y,z)} =
  \left(\begin{matrix}
    \partial u/\partial x & \partial u/\partial y & \partial u/\partial z \\
    \partial v/\partial x & \partial v/\partial y & \partial v/\partial z \\
    \partial w/\partial x & \partial w/\partial y & \partial w/\partial z
  \end{matrix}\right)
  =
\left(
\begin{matrix}
 -\sigma & \rho-z & y \\
 \sigma & -1 & x \\
 0 & -x & -\beta \\
\end{matrix}
\right).
$$
Next, plug one of the fixed points
$(x,y,z)=\left(\pm\sqrt{\beta(\rho-1)},\pm\sqrt{\beta(\rho-1)},\rho-1\right)$ and the parameters you're using into the Jacobian. Finally, compute the eigen system of the evaluated Jacobian matrix. If all goes well, one eigenvalue should be real and negative, while the other two should be complex conjugates. The real and imaginary parts of the complex eigenvector should be parallel to the plane of rotation of the linearized system. Taking the cross product of those vectors, we can generate the vector shown in the image below:

I emphasize again, though, that the "wing" of the attractor is not contained in a plane.
Comment: @MarkMcClure thanks a lot, now I understand it much better ;)
Comment: So when you use a lineairisation then de eigenvector of the real eigenvalue stands perpendicular to the plane of rotation, but this eigenvector does not stand perpendicular to the plane of rotation in the not-lineairised system? Why don't the wings form a plane?
Comment: Some of the "eigenvector" should be "eigenvalue". It is the left eigenvector to the real eigenvalue that gives a linear form that annihilates the other right eigenvectors. The transpose of that is really perpendicular to their plane. The right eigenvectors/eigenspaces are seldom orthogonal.
Comment: @Dr.LutzLehmann You are right of course. I have edited the post to use the real and imaginary parts of one complex eigenvector.
Comment: @Mari3 No, the real eigenvector is not necessarily perpendicular to the plane of rotation. I have edited my post to reflect the correct approach.
Comment: @Mari3 I'm not sure why you think the wings form a plane - or where you got that idea, as the picture clearly indicates they don't. The point is that *near the fixed point*, the system is well approximated by the linear system. They are not the same system, though, and they are not even close once you move away a bit from the fixed point.

It's a bit like looking at the graph of a function together with a tangent line at a point $x_0$. Near $x_0$, the two are very close but the graph of the function certainly need not be contained in the line.