How to select data after specific character

Question: I want to skip the first dash to choose data from the second dash.
I have used below function from which I am getting the only FLR
replace(right([Bin Code], charindex('-', reverse([Bin Code]))),'-','')

The cell contains this value

0771-B-3RD-FLR

Desired Output

3RD-FLR
Answer: If it's always from the second hyphen onwards you want (your description is a bit contradictory), you could use STUFF and a couple of nested CHARINDEX functions:
SELECT STUFF(V.S,1,CHARINDEX('-',V.S,CHARINDEX('-',V.S)+1),'') AS NS
FROM (VALUES('0771-B-3RD-FLR'))V(S);

Answer: One method is just to munch the string one hyphen at a time:
select t.*, v2.bin_code
from t cross apply
     (values (stuff(t.bin_code, 1, charindex('-', t.bin_code), '')
     ) v(bin_code)(bin_code) cross apply
     (values (stuff(v1.bin_code, 1, charindex('-', v1.bin_code), '')
     ) v2(bin_code)(bin_code) ;

Comment: There's quite a few syntax errors in that one Gordon. You're missing some right parenthesis, you've declared the column name twice, and your aliases are inconsistent.


Does akka send own messages to custom actor by own initiative?

Question: I'm creating some actor which should wrap all the incoming messages with its own message and forward them further.
Unfortunately I don't have any common base class for user messages so I'm going to catch them with Object.class
Now I'm not sure if Akka can send its own messages to my Actor. I don't want to occasionally forward some system message which addressed to my wrapper actor.
Answer: Akka does internally send messages to your actors. These messages extend the internal SystemMessage trait. As the description in the source code states, system messages form their own queue in each actor's mailbox and are handled separately from other messages. We can trace the processing of these messages in Mailbox and ActorCell.
When your forwarding actor receives a SystemMessage, that message is not wrapped and forwarded. Akka handles these messages internally, so your forwarding actor's behavior won't disrupt this system-level activity.
Answer: class WrapAndForwardActor extends Actor {
  override def receive: Receive = {
    case _ => {
      // blocking
      // do whatever you want to do with the incoming message
      sender forward "WrappedMessage"
    }

    case "AnotherExample" => {
      // non blocking
      val sendTo = sender()

      // do whatever you want to do with the message
      // non blocking futures

      //when future is complete
      sendTo forward "WrappedMessage"
    }
  }
}

Comment: Thanks for the answer, but it's not clear what it's about ...
My problem is: forwarding relevance - I want to forward the messages that was send by users only (custom messages) but not framework's messages. And I'm not sure does the framework can send something like this at all to user-defined actor. So, If yes - the simple "forward them all" is not appropriate strategy.


Omit the Front Page when Using Contextual Filters?

Question: Content on my site is set up via taxonomy term, and I've created a view using contextual filters which does a fabulous job of sorting all the content to the appropriate page.
However, on the front page we want to present that content differently, so I have created a block which presents anything marked "front" to appear inside it.
The two are mutually exclusive, as I have filtered the data so that ONLY front page stuff appears in the block, and NO front page items appear in the page view.
This is problematic, however, as some of these highlighted items should appear on other pages in the Web site.  Removing the 'exclude home' filter from the page view, however, makes the page view of items marked "front" appear beneath the block, which we don't want.
In order to get the content on the home page AND elsewhere content owners are required to enter the data twice -- unless I can get this fixed.
Any ideas?
Thanks!
Answer: First : NEVER enter data twice. You're sure you'll regret it sooner or later, and it's always the sign something's wrong with the design.
As for your problem, you could probably set up a Views Attachment or a plain other view to add nodes with different criteria.
Or perhaps you could use Flag or another module of that kind to differenciate your nodes more precisely ?
Comment: Thank you - we know twice entering data is wrong, which is why we want to get away from this.  :)                                                                                Adding an additional view doesn't work because the "default" view appears beneath the block view or attachment, so I'm getting duplicate data.  I'm now toying with telling drupal just not to print nodes on the home page using hide(content[node]) (with proper coding) - however, this prohibits the nodes in the block view from showing, too.  Any other ideas?  Many thanks...
Comment: The solution should be data based, not display based. I still don't understand why you can't code different views or displays (views' terminology) for the non-front pages.


How convince Security auditors to change frequent password change policy?

Question: I am a new Junior IT Manager in a small company of around 500 employees and the current policy regarding passwords has enforced password expiration within 30 days, with a password history of 5.
As you can understand, this leads to people having passwords like January16 and the like, passwords on sticky notes on their screens blah blah blah... The usual when it comes down to these policies.
What would be ideal as far as I can tell would be a 10 character length password with capitals, small letters numbers and symbols.
Since I presume there are people in here that are security auditors, and also others that have way more experience on these matters, I ask you this.
What can I present to the auditors next time they come around, so that they would allow us to change the policy for password expiration to 1 year?
Off the top of my head I would provide them data regarding the strengths of a long and complex password, as well as data from brute-force password retrieval apps in regards to how many p/s they can achieve with state of the art hardware, as well as a script that will run once every day to show if there are any new accounts in AD that have been created to work as a security measure in case someone does manage to break in to the network and create their own account.
Any assistance will be much appreciated.
Comment: Just a small point: Auditors check that a particular set of controls is in place. They are not usually the ones who set policy, they only check that the policy is being followed. You should determine who _does_ set the security policy, and speak directly to them.
Comment: In my experience monthly password changes are pretty standard, yearly password changes are unheard of.
Comment: One other item of importance: Are there any regulatory bodies (PCI-DSS, HIPAA, etc) in play that dictate this password policy?
Comment: Maybe search the web for more supporting arguments before beginning the conversation.
Answer: The first thing that I would do is find out who actually sets the security policy.  That info in-hand, sit down and talk with them.  Ask what the goals of the security policy are, what is hoped to gain from it, and how the current policies achieve that goal.  The most important part of this is that you listen to their answers.
There are probably more secure means to achieve your aims.  First, having more characters trumps upper/lower/number/special-char requirements.  https://xkcd.com/936/ and https://www.explainxkcd.com/wiki/index.php/936:_Password_Strength should be sufficient primer.
Even more secure is using 2FA in place of straight passwords.
As mentioned, having a frequent password change will lead to an increase of forgotten / mistyped passwords.  This will manifest in an increase in password-related calls to the helpdesk, or increases in written or predictable passwords.

The most important part of this conversation is to understand the goals, understand how the current policies are thought to meet those goals, and to work with your teammates (remember, it's all one company...) by avoiding being confrontational or insulting.


Gitosis installation error (AssertionError)

Question: I am trying to set up a Git server in Ubuntu, but I can't get past this issue. I'm trying to add my public key to Gitosis thusly (as every tutorial so far has instructed me to do):
sudo -H -u git gitosis-init < /tmp/pcalves.pub

But keep getting hit with the same error messages:
Reinitialized existing Git repository in /var/git/repositories/gitosis-admin.git/
Reinitialized existing Git repository in /var/git/repositories/gitosis-admin.git/
Traceback (most recent call last):
      File "/usr/local/bin/gitosis-init", line 9, in <module>
        load_entry_point('gitosis==0.2', 'console_scripts', 'gitosis-init')()
      File "/usr/local/lib/python2.6/dist-packages/gitosis-0.2-py2.6.egg/gitosis/app.py", line 24, in run
        return app.main()
      File "/usr/local/lib/python2.6/dist-packages/gitosis-0.2-py2.6.egg/gitosis/app.py", line 38, in main
        self.handle_args(parser, cfg, options, args)
      File "/usr/local/lib/python2.6/dist-packages/gitosis-0.2-py2.6.egg/gitosis/init.py", line 140, in handle_args
        run_hook.post_update(cfg=cfg, git_dir=admin_repository)
      File "/usr/local/lib/python2.6/dist-packages/gitosis-0.2-py2.6.egg/gitosis/run_hook.py", line 43, in post_update
        config=cfg,
      File "/usr/local/lib/python2.6/dist-packages/gitosis-0.2-py2.6.egg/gitosis/gitdaemon.py", line 79, in set_export_ok
        assert ext == '.git'
    AssertionError

Even though the first two lines show the expected result, it doesn't seem to be working, as afterwards, if I try to clone the repository in my local machine, I get this:
fatal: 'gitosis-admin.git' does not appear to be a git repository
fatal: The remote end hung up unexpectedly

Comment: Fixed the issue by using Gitolite instead.
Answer: Old question, so just answering for the archives.
Check the names of directories in /var/git/repositories/; make sure that all the git repositories end with .git.


Attaching 'active' class to faqfield expanded question

Question: I am using the FAQ Field module my project which utilizes the jQuery Accordion UI and HTML definition lists, and I am wondering how I can attach an 'active' field to the expanded question. I would like to know so I can show/hide an up/down caret next to each of the questions based on it's active (expanded) state.  I am using Drupal 7.  Thank you.
Answer: This functionality is provided by FAQ Field using the jQuery Accordion UI.
In Structure > Content Types > Your Content type > manage display (admin/structure/types/manage/[your_content_type]/display), if you change your FAQ field display settings from Definition List to Accordion, an up/down caret is shown next to each question.

If you click on the gear icon corresponding to your FAQ Field you can configure which question is active by default, as well as whether the questions are collapsible.

Result:

The Accordion setting also adds the class ui-state-active to the active question element (an h3) and the class ui-accordion-content-active to the active answer element (a div).


JPA: primary key violation when saving an entity with many to one

Question: I have 2 JPA Entities
@Entity
@Data
public class Config {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    private String data;

    @ManyToOne(cascade= CascadeType.ALL)
    private Tenant tenant;
}

@Entity
@AllArgsConstructor
class Tenant {
    @Id
    private String tenantID;
}

and a repository
interface SolmanConfigPrivateRepository extends CrudRepository <Config, Long> {

}

I create new entities with the following code
public void addConfig(Config config){
    String tenantId = userProvider.get();
    config.setTenant(getCurrentTenant());
    Tenant tenant = new Tenant(tenantId);
    dbRepository.save(config);

}

I manage to save a Config using the save method of the repository.
If I try to save a new Config with the same tenant, I get an error
 Unique index or primary key violation: "PRIMARY_KEY_9 ON PUBLIC.TENANT(TENANTID)

How can I tell JPA to not try to create a new Tenant if there is already another one in the database (but to reference the existing one instead)?
Comment: show the method in which you construct the entities and invoke the save
Comment: I edited my question
Answer: You're violating hibernate session. What you have to do, is to find Tenant from db by id, set entity picked up from the db (that certain reference) and then save. Otherwise, Hibernate will try to save instead of update.
public void addConfig(SolManConfig solManConfig){
    String tenantId = userProvider.get();
    solManConfig.setTenant(getCurrentTenant());
    Tenant tenant = tentantRepository.findOne(tenantId);
    dbRepository.save(solManConfig);
}

Spring data JPA has one method for save and update. It's save. When you pass a new object, it saves, otherwise it updates. What does it mean 'new object'? It means, an object which hasn't been extracted from the db.
Comment: Tenant tenant = tentantRepository.findOne(tenantId); does nothing to solManConfig. Did you mean:
Tenant tenant = tentantRepository.findOne(tenantId);
solManConfig.setTenant(tenant );
dbRepository.save(solManConfig); ?
Comment: @hipokito it does. You need to set cascades and eventually refresh the entity
Answer: How is the tenant id set? It's obviously not generated (according to the JPA annotations), so I suppose you set it manually?
If you don't set it at all, the tenantID will be null, thus when inserting another tenant (which then also has tenantID null), the unique constraint will be violated.
Comment: I set it manually through the constructor (I've just edited my question)


In any tree, what is the maximum distance between a vertex of high degree and a vertex of low degree?

Question: In any undirected tree $T$, what is the maximum distance from any vertex $v$ with $\text{deg}(v) \geq 3$ to the closest (in a shortest path sense) vertex $y$ with $\text{deg}(y) \leq 2$? That is, $y$ can be leaf.
It seems to me that this distance can be at most $\dfrac{\text{diam}(T)}{2}$, and furthermore that the maximum distance will be attained from a graph center. Is this true? There's probably simple argument for it somewhere.
Answer: In answer to the first version of the question (between any $v$ and any $y$):
------------------------------------------------------<
y is at the left, v is at the vee
The answer to the second version of the question is yes.  Suppose that $v$ were more than $\frac{D}{2}$ away from all leaves, where $D$ denotes the graph diameter.  Pick two of the branches leading from $v$.  Each of them contains at least one leaf.  The shortest path between these leaves passes through $v$, and is of distance more than $D$, being the sum of two distances each more than $\frac{D}{2}$.  This is a contradiction.
The bound given is tight, by considering the Y graph on four vertices.
Comment: @BobWhiz, the vee at the end is a degree 3 vertex, with two leafs hanging off of it.
Comment: @BobWhiz, the question you asked was clear, and I believe I answered it.  The question you mention in this comment is a distinctly different question.
Answer: In your second question (shortest path to vertex of degree $\le 2$), the bound $\operatorname{diam}(G) / 2$ holds, simply by noticing that the ends of the longest path in a tree are leaves, and the "worst" that a graph can do is have the vertex of degree $3$ or higher right in the center.  But in fact, this holds for the shortest path from any vertex of to vertex of degree $1$.
Can we do better?  No, in fact.  Take a look at a tournament bracket, for example (just delete the leaves on one side to create a unique center).  Viewed as a tree, all the vertices are of degree $3$ except for the leaves, which are all at least distance $d/2$ from the center of this modified graph.


the same certificates are sold at different prices?

Question: I've encountered so many times with this situation.
For example everybody know if I buy a Positive SSL for a year from a reseller, its price is about $5.95 . If I buy the certificate from CA directly, its price is $49 for a year.
I'm really wondering why?

Exchange rates
Through reduced costs (from $49 to $5.95 ? really?)

Or what else is there?
I couldn't find any advantage buying from CA directly.
Comment: marketing as it is
Comment: When you buy from the CA directly, they use premium multiplication to generate the signatures.
Answer: The reseller pre-purchases thousands of them at once. Additionally, the issuing CA use the resellers to do what's called "Market Segmentation". In other words, there are people who are happy to pay $49/cert and those that are happy to pay $490/cert and those that only want to pay $4.95/cert. By selling the certs at a really low price, they capture all the different segments of the market.
Rest assured, the bits that you're transmitting on a $4.95 cert are encrypted at the same level as $49 cert.
Comment: @Paul sure some of them offer insurance and others offer more detail in the certificate (and other things like EV). But the _encryption_ is identical.
Comment: @Paul I can think of only two guarantees you need, one of which is completely outside the control of the CA and one which is only partly so. You'd want a guarantee that no CA is going to issue a rogue certificate for your domain. And you want a guarantee that the root of the CA you choose is trusted by all leading browsers and remain so for the lifetime of the certificate.
Comment: I thought some of the more expensive ones offered some sort of financial guarantees? Not that I'm saying this makes it worth it, just sayin'...


Prove that $T$ is linear, one to one and onto.

Question: Consider the function $T:\mathbb R^2 \to \mathbb R^2$ given by $$T \begin{pmatrix} \begin{bmatrix} x \\ y \end{bmatrix} \end{pmatrix} = \begin{bmatrix} 2x+y \\ -3x \end{bmatrix}$$ Prove that $T$ is linear, one-to-one, and onto. Here is what I 've got so far:
Let $u,v \in \mathbb R^2$ such that $u = \begin{bmatrix} u_1 \\ u_2 \end{bmatrix}$ and $v = \begin{bmatrix} v_1 \\ v_2 \end{bmatrix}$ then,
$$T(u + v) = T\begin{pmatrix} \begin{bmatrix} u_1 \\ u_2 \end{bmatrix} + \begin{bmatrix} v_1 \\ v_2 \end{bmatrix} \end{pmatrix} =\ldots \text{ (skipping tedious steps)} \ldots = T(u) + T(v) \to $$ preserves addition and,
$$T(ru) = T\begin{pmatrix} r \begin{bmatrix} u_1 \\ u_2 \end{bmatrix} \end{pmatrix}= \ldots = rT(u) \to$$ preserves scalar multiplication $\therefore T$ is linear.
To prove it is one-to-one I believe I need to show that it is impossible for $u=v$ right? on this i am not positive. Also to prove that it is onto I am pretty sure I need to show that $sp(T) = sp(\mathbb R^2)$ again not really sure so I don't know where to start.
Any help will be greatly appreciated.
Edit 1:
please correct me if im wrong here:
Let $T(v)=0$, then $0=T\begin{pmatrix} \begin{bmatrix} v_1 \\ v_2 \end{bmatrix} \end{pmatrix} = \begin{bmatrix} 2v_1 + v_2 \\ -3v_2 \end{bmatrix}$, so $2v_1 + v_2=0$ and $-3v_1=0$
$\therefore v=\begin{bmatrix} 0 \\ 0 \end{bmatrix} = 0$ and $T$ is one-to-one
Comment: It is enough to show the kernel is trivial: $T(x)=0\Rightarrow x=0$
Comment: @Ranc that proves one to one correct?
Comment: Yes, in the finite dimensional case; If $T\colon E\rightarrow E$ is a linear map, then **if** $T$ is $1-1$ then it must be onto. This is due to the relation: $\dim E = \dim \mathrm {Im} T +\dim \ker T$
Answer: The matrix of $T$ is
$$A = \begin{bmatrix}
&2 &1 \\
&-3 &0
\end{bmatrix}$$
The kernel of $T$ is $\bf0$, because the only solution to $A * [x,y]^T = \bf 0$ is $x=y=0$. Because
$$
\operatorname{dim}\,\operatorname{ker}\,A + \operatorname{dim}\,\operatorname{rank}\,A = \text{# of columns of $A$},
$$
it follows that $\operatorname{dim}\,\operatorname{rank}\,A = 2$. Thus $A$ is invertible, so $T$ has an inverse — that is, $T$ is an injection and a bijection.
Answer: Hint:

One-to-one: Let $u, v$ as you have them. Show that $T(u)=T(v) \implies u=v$. You will need to solve a two-by-two system of equations.
Onto: Show that $\dim \Im(T)=2$. How? By finding two vectors in the image of $T$ that are linearly independent. For example: what is the image of the vector $e_2=\begin{bmatrix} 0 \\ 1 \end{bmatrix}$ under $T$? Can you find another one, say $z$ so that $T(e_2)$ and $T(z)$ are linearly independent (and therefore span $\mathbb R^2$)?

Of course as @kevinzakka comments, it suffices to show that $T$ is one-to-one. This is equivalent to $\dim Ker (T)=0$ and hence by the Rank - nullity Theorem you can conclude that $\dim \Im (T)=2$.
Comment: Since the image and the co-image are the same, all you have to show is one or the other. Usually proving it is one-to-one is easier.
Answer: Solve $2x+y = w, -3x=z$ for $x,y$ to get $x=-{1 \over 3} z$ and $y={2 \over 3} z+w$.
Hence for any $(w,z)$ there is a unique $(x,y)$ such that $T(x,y) = (w,z)$.
It follows that $T$ is injective and surjective.


React js Validation for Range (Max and min values for field ) Using Formik

Question: I'm trying to make a validation using React and Formik. I wanted to achieve that the max digit is only 3 and the max range should be only to 100 and minimum should be 1.
How can i achieve this in react js.
Comment: Does this answer your question? [React Validation Max Range Using Formik](https://stackoverflow.com/questions/62611150/react-validation-max-range-using-formik)
Answer: you can use validate prop of the Field component by passing a validation function to it.
import React from "react";
import ReactDOM from "react-dom";
import { Formik, Field, Form } from "formik";

function validate(value) {
  let error;
  if (value.length > 3) {
    error = "max digits 3";
  } else if (parseInt(value) > 100 || parseInt(value) < 1) {
    error = "range is 1 to 100";
  }
  return error;
}
const Basic = () => (

    <Formik
      initialValues={{
        num: ""
      }}
      onSubmit={(values) => {
        // same shape as initial values
        console.log(values);
      }}
    >
      {({ errors, touched }) => (
        <Form>
          <Field type="number" name="num" validate={validate} />
          {errors.num && touched.num && (

{errors.num}

          )}
        </Form>
      )}
    </Formik>

);

ReactDOM.render(<Basic />, document.getElementById("root"));

Answer: There are many form schema validations libraries available out there one of the simpler one is Yup.
Take a look at this guide on how to use yup with formik


Proving a norm inequality for general matrices

Question: I am currently doing exercises from Trefthen and Bau's numerical linear algebra.
This problem has two parts.
For the first part, I have managed to prove that if a set $S$ of complex numbers is contained in no half-plane disjoint from the origin, there is no polynomial $p(z)=az+1$ for which $ \sup_{z\in S} |p(z)| < 1 $.
I am stuck on the second part. It says let $A$ be a square matrix, not necessarily normal, whose spectrum satisfies the property in the first part (is not contained in any half-plane disjoint from the origin). We are asked to show there is no polynomial $p(z)=az+1$ for which $ \lVert p(A) \rVert < 1 $. Here the norm is the operator norm induced by the Euclidean norm (2-norm of the matrix).
I have no idea how to proceed with the second part as $A$ is given to be general. I do not know much if anything about the norm of a polynomial of a matrix. I would appreciate any and all help with this and thank all helpers.
Answer: Hint: For any matrix $M$ with eigenvalue $\lambda$, we have $\|M\| \geq |\lambda|$. What can you say about the eigenvalues of $M = p(A)$?
Comment: Thank you very much, it is clear now


NVidia DIGITS DetectNet alternatives

Question: I am looking for detection/localization CNNs to run within the NVidia DIGITS training platform.  So far it seems they only support their homebrew DetectNet for this purpose.  Looking around it seems that other SOTA networks such as faster-RCNN, SSD, and YOLO might compete with DetectNet in terms of performance and accuracy, but it does not look like they currently have any support in DIGITS.  (Faster-RCNN has a fairly popular implementation, but it is run out of a version of  Caffe not supported by DIGITS.)
If anyone has had any success obtaining and using SOTA detection networks with NVidia DIGITS, would you mind supplying links/documentation regarding?
Comment: With all due respect, is that relevant to the question?  I don't need to use DIGITS, but if somehow it is possible I would like to know.
Answer: Currently, NVIDIA provides NVIDIA Transfer Learning Toolkit which is useful for training CNNs. NVIDIA provides SSD, Faster RCNN, DetectNet, etc. You can find more here: https://developer.nvidia.com/transfer-learning-toolkit

NVidia DIGITS DetectNet alternatives


Matrix product including skew-symmetric matrices

Question: Consider the following real matrix
$M:=Jxkx^\top J^\top\in\mathbb{R}^{n\times n}$
where $J\in\mathbb{R}^{n\times n}$ is skew-symmetric, $k\in\mathbb{R}_{>0}$, $x\in\mathbb{R}^n$. It turns out, via software calculation, that this matrix always has a zero eigenvalue, independently from the (positive) value of $k$. Can anyone provide a proof (or at least an explanation) of this?
Comment: Since $M = k(Jx)(Jx)^T$ is an $n\times n$ rank-one matrix it is not full rank and hence always has a zero eigenvalue.
Comment: You mean that you ran a few tests and each time it had a zero eigenvalue, or you were able to show that for any $n$, and any appropriate entries, it has a zero eigenvalue?
Comment: Which is the consideration that allows to claim that M is rank-one? Which properties of skew symmetric matrices have to be used to prove it?
Comment: @dave I meant that I ran a few tests..
Comment: @Daniele The matrix $M$ is the outer product of the vector $Jx$ with itself, hence it has rank one. It doesn't matter that $J$ is skew-symmetric.
Answer: If $n=1$, since $J$ is skew-symmetric, $J=0$, hence the eigenvalue is $0$.
If $n>1$,
$$M=k(Jx)(Jx)^T$$
(credit: K. Miller)
Note that $Jx \in \mathbb{R}^{n \times 1}$, hence $rank(Jx) \leq 1$, hence $rank(M) \leq rank(Jx) =1$. and hence the $nullity(M)>1$.
Hence one of the eigenvalue is $0$.


Probability and Given

Question: Question: in the following problem, can given be flipped?
$\Pr(A\cap F)=\Pr(A)\cdot \Pr(F\text{ given }A)=?$
Can I switch to get the same answer:
$\Pr(A\cap F)=\Pr(A)\cdot P(A\text{ given }F)=?$
Answer: No, because it won't be true anymore. But think about the original formula as a template:
$$\Pr(A\cap F)=\Pr(A)\cdot \Pr(F\mid A).$$
If you want $F$ to be "given", then you need to substitute $F$ for each $A$ of the formula and at the same time substitute $A$ for each $F$ of the formula. Note also that order doesn't matter for intersection. So you can get that
$$\Pr(A\cap F)=\Pr(F\cap A)=\Pr(F)\cdot \Pr(A\mid F).$$

Probability and Given


Encapsular conjunto de tags HTML no VS Code ("ctrl + alt + enter" no Sublime Text)

Question: Editando arquivos HTML no Sublime Text eu posso encapsular um conjunto de tags ou texto apenas selecionando o bloco e apertando Ctrl+Alt+Enter e digitando em seguida qual a tag que eu quero usar para encapsular o bloco. Gostaria de fazer o mesmo no Visual Studio Code mas até agora não faço a menor ideia.
Comment: Se você usa o Emmet dá pra selecionar o texto, pressionar `Ctrl + Shift + P` e digite `wrap`. Uma das opções é fazer o wrap com uma expressão do Emmet.
Comment: Obrigado, funcionou, só que na verdade eu procurava um atalho de teclado mais prático.
Comment: Fiz essa mesma pesquisa há um tempo e, na época, não havia um atalho nativo. O que você pode fazer é adicionar o comando acima ao arquivo de atalhos.
Comment: @fernandosavio jovem, to usando a extensão que citei ai na resposta, tem sido bastante útil, as vezes te interessa.
Comment: Já positivei. Eu uso muito pouco essa _feature_ então vou deixar favoritado pra quando precisar. Valeu Hugo!
Answer: Eu uso esse extensão htmltagwrap vc pode encontrar aqui: https://marketplace.visualstudio.com/items?itemName=bradgashler.htmltagwrap
Essa extensão já vem com um atalho definido, basta selecionar o bolco de texto que quer encapsular e apartar Alt + W como vc pode ver no Gif abaixo

Editando o atalho
Se quiser mudar o atalho original para um que mais te agrade bastar ajustar aqui

Agora pesquise e edite o novo atalho
Answer: Você pode fazer isto definindo um atalho para a função emmet wrap do Visual Studio Code:

Vá em Code -> Preferences -> Keyboard Shortcuts.
Busque por emmet wrap.
Clique no sinal de mais + da opção Emmet: Wrap with Abbreviation.
Adicione o atalho que você deseja apertando CTRL+ALT+ENTER, e depois ENTER para confirmar.
Agora basta selecionar um pedaço de código HTML e usar o atalho. Uma caixa de texto irá aparecer para você escrever a tag que deseja envolver o texto.


When to add an additional "service" or BLL layer?

Question: I've got a Web API controller such as:
<code>    [HttpGet]
    [Route("accounts", Name = "GetAccounts")]
    public async Task<IHttpActionResult> GetAccounts()
    {
        var query = Request.RequestUri.PathAndQuery.Split('/')[2];

        var response = await Client.HTTPCLIENT.GetAsync(Client.HTTPCLIENT.BaseAddress + query);

        if (!response.IsSuccessStatusCode)
        {
            return NotFound();
        }

        var readAsAsync = response.Content.ReadAsAsync<object>();
        if (readAsAsync == null)
        {
            return NotFound();
        }

        var result = await readAsAsync;
        return Ok(result);
    }
</code>
My question is whether I should be simplifying the controller and pushing this logic into a new service/business logic layer?
My use case is to have this code run within a microservice on service fabric.
Would it be redundant / unnecessary complexity to add another layer to this architecture, is there a benefit?
Comment: You should use an another layer for complex logic, and large application, and for separate busness logic and presentation logic (like MVC)
Comment: When using service fabric you are probably looking for a micro services architecture. You can use a stateful service to store and retrieve data or a stateless service with a db as backend for example. or a stateless/stateful service for some business logic. It depends on your view of how big a microservice is. So tell me, why did you choose service fabric instead of, lets say, a web app?
Comment: in service fabric a common scenario is to run the api's on a node type with other specs that a node type which runs compute services. Without knowing you exact requirements it is hard to tell.
Comment: What logic? The "NotFound" logic?
Comment: @Mardoxx, no, specifically var response = await Client.HTTPCLIENT.GetAsync( ......... what if perhaps i had to make a call to a third party right after this line and aggregate and then return the results? in this case would i factor out all of this into a separate AccountService?
Answer: As far as I can tell, the only thing this controller does is make a call to another service and return the results. I don't see anything here that you can extract to another service.
I would always ask, what benefit are you getting out of having more services and at what cost? A round trip to a service is relatively expensive in terms of physical machine resource usage, development costs, and maintenance.


What is the Windows equivalent of CloudInit for initialization of Amazon EC2 instances?

Question: Is there a way to hook into the first-boot process of a new Windows Amazon EC2 instance to run initialization scripts? We would like to automate the setup of our instances without resorting to creating our own custom AMIs.
The Amazon Linux AMI's have CloudInit to make this easier. Is there an equivalent for Windows?
Answer: I know I tried looking for one for awhile. Then I finally decided to create my own open source one for everyone else to use.
http://cloudinitnet.codeplex.com/
Answer: I havent found one yet, but the way i was looking at this was to instance data option. The plan, which has not yet been put to the test, was as follows:

build a basic Windows Image (ok, i know you mentioned you didn't want to do this, but this is the best option i can think of).
the image should only have a basic Windows service which calls out to the instance data URL (http://169.254.169.254/latest/user-data). this should be in a format that the service knows about (XML is probably best). the data should point to URLs to exes, msis, etc, that you want to install.

This is the only option, other than creating your own fully custom AMI, i can think of. you might not get it to install SQL server (though, unattended install might be an option...) but installing basic tools, IIS, etc, could be easy enough to do.
Hope this helps.


jQuery press keyboard key on interval

Question: I thought this would be simple, but I can't figure it out.
I want to simulate keypress on some keyboards keys (i.e, the arrows), on a time interval.
So this is what I've done :
var typer = function(){
    var e = jQuery.Event("keypress");
    var keys = [37,38,39,40];
    var key = keys[Math.floor(Math.random()*keys.length)];
    e.which = key;
    $(document).trigger(e);
    console.log(e);
};
setInterval(typer, 500);

FYI, the log returns :
jQuery.Event {type: "keypress", timeStamp: 1395335870282, jQuery20002915873059537262: true, which: 37, isTrigger: 3…}

Any help? :)
Answer: Bind the event first.
Try this: http://jsfiddle.net/aamir/E53s8/
$('body').keydown(function(e){
    var keys = [37,38,39,40];
    if( $.inArray(e.which, keys) != -1 ) {
        alert('Arrow keys pressed');
    }
});

var e = jQuery.Event("keydown");
e.which = 38;
$('body').trigger(e);

jQuery press keyboard key on interval


Overwriting value of a key in module.exports

Question: I'm trying to store a value in a Helper file, which is calculated after the initial require of the Helper, and the value doesn't change from undefined (because it was unknown to start with).
Is there any way I can overwrite this value to use elsewhere?
helper.js:
module.exports = {
    key:value
}

setup.js:
var helper = require("./helper.js");

... // hit a url and get a value
helper.key = newValue;

usage.js:
var helper = require("./helper.js");

console.log(helper.value) // prints the original value

Flow
setup.js -requires-> helper.js
usage.js -requires-> helper.js

I've read that module.exports is seemingly read-only, but surely there must be a way to do this.
Also, is it possible to add to module.exports after the initial creation?
module.exports["key"] = value;

Thanks in advance, seems like it should be simple but it's a roadblock for me.
EDIT: Ignore the second question, I have gotten this work (about the module.exports["key"]).
Answer: I am not sure there is an issue here. May be I don't understand the loading flow and there is some crazy scope configuration...
You can do it like this and you can alter the exports (whether this is a feature, is a different matter).
Imagine these modules:
test1.js
module.exports = {
    a: '1'
}

test2.js
var test1 = require('./test1');

module.exports = function() {
    test1.a = test1.a + '2';
    test1.b = 100;
};

test3.js
var test1 = require('./test1');

module.exports = function() {
    test1.a = test1.a + '3';
    test1.b = 200;
};

test4.js
var test2 = require('./test2')();
var test3 = require('./test3')();
var test1 = require('./test1');

console.log(test1);

The output, when running node test4 is:
{ a: '123', b: 200 }

or, if you switched the order of loading of modules 2 and 3 in module 4:
var test2 = require('./test3')();
var test3 = require('./test2')();
var test1 = require('./test1');

console.log(test1);

it would become:
{ a: '132', b: 100 }

Comment: This is what I expected, but for some reason it seems to not be overwriting the value in the helper.
Comment: I've tested just now. Are you sure the configuration of your modules loading is the same?
Comment: One sec, let me take a look at it again
Comment: Is it significant you're changing the values from within module.exports in test2/3.js?
Comment: Nope. Would net the same exact result - **output wise** (granted, you'd not have to *invoke* the modules in *test4*.
Comment: So you're saying if I require my helper, and do `helper.key = newValue` it should work?
Comment: Well, if the above fits you... I am not sure how it wouldn't work for you.
Comment: let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/43090/discussion-between-zackehh9lives-and-zenmaster)


Sort by count SQL reporting services

Question: I have a simple query in a tabloid control that gets all the leads in one month. I then use the tabloid control to group them into lead source. And then I have an associated count column. I want to sort my report on the count descending, without doing it in the query. I keep getting an error saying you cannot sort on an aggregate.
Thanks.
Answer: you can do one more thing..
just write your query in subquery part and write order by clause in outer query.
(suppose you have group by query as follow-
select lead_source, count(*) cnt
from your_table
group by lead_source

)
so you can do as follow -
select lead_source, cnt from (
    select lead_source, count(*) cnt
    from your_table
    group by lead_source
    )
order by cnt

this your_table and group by column list you have to edit accordingly your table structure ..
Comment: Well, you can do "order by count(*)" in the original query.  Whether or not you can do "order by cnt" depends on the database, and is not supported in SQL Server.
Comment: @GordonLinoff: It is, actually. The `ORDER BY` clause is [processed at a later stage](http://msdn.microsoft.com/en-us/library/ms189499.aspx "SELECT (Transact-SQL)") than the `SELECT` clause, so column aliases are accessible there. And [here's an illustration](http://sqlfiddle.com/#!3/767bc/2).
Comment: As a matter of fact, you don't need to use a subquery, you could add `order by cnt` to the original query and it would work just as well. Anyway, I'm not sure if this is what the OP wants, as they specifically said they didn't want to sort the rows in the query.
Comment: Andriy, you are correct.  There are some versions of databases that haven't supported it in the past, but it appears that the standard is to allow aliases in order by.

Sort by count SQL reporting services


A nice use of $AM GM HM$ inequality

Question: Let $a+b+c = 20$. Then what is the minimum value of $1/a + 9/b + 36/c$ .In this question minimum value is asked. How to approach it as we can find maximum value by applying $GM $ and $HM$ inequality.
Comment: Why tag arithmetic-geometry?
Comment: are $a,b,c$ assumed to be positive?
Comment: Yes they are positive
Comment: Sorry friend for wrong tagging
Comment: Welcome to math.SE: since you are new, I wanted to let you know a few things about the site. In order to get the best possible answers, it is helpful if you say in what context you encountered the problem, and what your thoughts on it are; this will prevent people from telling you things you already know, and help them give their answers at the right level. Also, many find the use of imperative ("Prove", "Solve", etc.) to be rude when asking for help; please consider rewriting your post. Also, this page may be of use to you: codecogs.com/latex/eqneditor.php.
Comment: Just remember to write code inside the dollar signs, for example do not write \frac{1}{2} but write $\frac{1}{2}$ - otherwise your code will not be interpreted.
Answer: We have,
$$ a + b + c = 20 $$
rewriting as -
$$ a + (b/3 + ... 3 times) + (c/6 + ... 6 times) = 20 \tag 1$$
now, we have to find -
$$ 1/a + (3/b + .. 3 times) + (6/c + ... 6 times) \tag 2$$
Since a,b,c are all positive numbers, we can apply AM > HM. Treat (2)/10 as AM and 10/(1) as HM -
$$ \frac{(2)}{10} \ge \frac {10}{(1)} $$
Solve for minimum value of (2). Equality holds.
Comment: Thanks for the help and suggestions
Comment: you're welcome. Just to remind you, you can mark this answer as correct if you believe that it answers your question.

A nice use of $AM GM HM$ inequality


Oracle - generate a running number by group

Question: I need to generate a running number / group sequence inside a select statement for a group of data.
For example
Group   Name   Sequence
1       a      1
1       b      2
1       c      3
2       d      1
2       e      2
2       f      3

So for each group the sequence should be a running number starting with 1 depending on the order of column"Name".
I already pleayed around with Row_Number() and Level but I couldn't get a solution.
Any idea how to do it?
Comment: Can you add a table, what you already played around with, the results, and how it's not working because of what you'd like to see instead?
Comment: https://stackoverflow.com/questions/51895196/oracle-sql-conditional-ranking - This link may useful to you
Answer: Analytic functions help.
SQL> with test (cgroup, name) as
  2    (select 1, 'a' from dual union all
  3     select 1, 'b' from dual union all
  4     select 1, 'c' from dual union all
  5     select 2, 'd' from dual union all
  6     select 2, 'e' from dual union all
  7     select 2, 'f' from dual
  8    )
  9  select cgroup,
 10         name,
 11         row_number() over (partition by cgroup order by name) sequence
 12  from test
 13  order by cgroup, name;

    CGROUP N   SEQUENCE
---------- - ----------
         1 a          1
         1 b          2
         1 c          3
         2 d          1
         2 e          2
         2 f          3

6 rows selected.

SQL>

Comment: Perfect, "partition" was the missing link, thank you so much :)
Answer: Try this
SELECT
       "Group",
       Name,
       DENSE_RANK() OVER (PARTITION BY "Group" ORDER BY Name) AS Sequence
FROM   table;

Comment: This won't work if there are duplicate `NAME` values in a `GROUP` as `RANK`/`DENSE_RANK` will give them the same values. Also `GROUP` is a keyword so you need to use double-quotes around it to be a valid identifier.
Comment: Yes, If there is duplicate values in 'Name' it won't work


How can I capture Mouse Events (mouseDown and mouseUp) on an NSButton?

Question: This is what I wnat to do and I couldn't yet.
Hope you can help me.
I have a button and a table. And I want to edit table content when I press this button.
When I press my button in a mouseDown event I want to capture that event and, let's say, get the actual time. And when I release the button in a mouseUp event I want to get que actual time again and update a row in my table.
For example:
1- Press button (with out releasing it, capture mouseDown event): get actual time, let's say: 18:10:23.
2- Release button (capture mouseUp event): get actual time, let's say: 18:10:33.
3. Update my table:
<code>-------------------------            -------------------------
|_#_|__start__|___end___|    ==>     |_#_|__start__|___end___|
| 1 |00:00:00 |00:00:00 |            | 1 |18:10:23 |18:10:33 |
-------------------------            -------------------------
</code>
How should I do this?
My principal problem is that NSButton doesn't capture both mouseDown and mouseUp event.
Answer: In the mouseDown: you fetch events until you see a corresponding mouseUp event.
Here's a blog entry with examples.
Answer: I could solve this
<code>- (void)awakeFromNib
 {
       [_myButton sendActionOn:NSLeftMouseDownMask];
 }
</code>
and using what wil said


Do not nest type warning (C#)

Question: I have the following code in a class to setup a serial port even handler.
I get two warnings; CA1034 (Do not nest types), which tells me to make my delgate private (which will stop me being to setup the even handler in inherited classes), and CA1009 (declare the second parameter of the event as an EventArgs, or a instance of a type that extends EventArgs, named 'e'), which I don't understand.
My code is below
myPort.DataReceived += new SerialDataReceivedEventHandler(port_OnDataRecived); //Setup when port is opened

private void port_OnDataRecived(object sender, SerialDataReceivedEventArgs e)
{
        int lengthToRead = myPort.BytesToRead;
        byte[] rxBytes = new byte[lengthToRead];
        myPort.Read(rxBytes, 0, lengthToRead);
        PacketReceived(rxBytes, e);
}

public delegate void PacketReceivedEventHandler(object sender, byte[] packet);
public event PacketReceivedEventHandler OnPacketReceived;

public virtual void PacketReceived(byte[] packet, EventArgs e)
{
        if (OnPacketReceived != null)
        {
            OnPacketReceived(this, packet);
        }
}

I have been looking at MSDN articles and some SO questions, but I can't relate the suggested fixes back to my own code.
This answer sort of makes sense, but converting my code to look like it leads to
OnPacketReceived(this, packet);

being replaced with
handle(this, new PacketReceivedEventHandler();

which takes an argument (void (object, byte[]) target) (that's where I get stuck). As for trying to fix the CA1034 warning I don't even see how what I have written is a nested type and the MSDN article doesn't contain a example of how to fix the rule violation.
Comment: Try by removing the delegate and the event and using an `EventArgs` where `PacketReceivedEventArgs` is a class that extends `System.EventArgs` and contains properties for the information you need
Answer:
I don't even see how what I have written is a nested type

You've declared your delegate type (PacketReceivedEventHandler) within your class. That's one type nested inside another. Just move the declaration outside your existing class declaration.
For the other warning, you'd want to create a PacketEventArgs class deriving from EventArgs and containing the packet data as an extra property. At that point, you could use an EventHandler<PacketEventArgs> and not declare your own delegate at all.
Additionally:

Your current way of checking handler nullity is broken as it could change from being non-null to null between calls.
Normally the event would be called PacketReceived and your method would be OnPacketReceived (and protected), rather than the other way round.

With all this in place, you'd have:
public event EventHandler<PacketEventArgs> PacketReceived;

protected virtual void OnPacketReceived(byte[] packet)
{
    var handler = PacketReceived;
    if (handler != null)
    {
        handler.Invoke(this, new PacketEventArgs(packet));
    }
}

Or in C# 6, using the null conditional operator to make the implementation simpler:
public event EventHandler<PacketEventArgs> PacketReceived;

protected virtual void OnPacketReceived(byte[] packet)
{
    PacketReceived?.Invoke(this, new PacketEventArgs(packet));
}

Comment: PacketEventArgs would be the class that implements EventArgs? That would take a byte[] as an argument.
I'm trying to work out how to change the SerialDataReceivedEventHandler as `PacketReceived(rxBytes, e)` no longer takes a SerialDataReceivedEventHandler as an argument.
Comment: @Mike159: Well, it would derive from `EventArgs`, yes. From `port_OnDataRecived` you'd call `OnPacketReceived(txBytes)`.
Comment: How do I then set up the even outside the class? With delegates it is `Class.Event += new Class.Delegate(methodToGoTo);` but the delegate no longer exists.
Comment: @Mike159: Well I'd use a method group conversion, so just `Class.Event += methodToInvoke;`. But if you *want* to use the C# 1 syntax, you'd use `Class.Event += new EventHandler(methodToInvoke);`. It sounds like you could do with reading http://csharpindepth.com/Articles/Chapter2/Events.aspx
Comment: Using `Class.Event += methodToInvoke;` how do I pass the byte array to my method?
Clearly I do need to read that article...
Comment: @Mike159: That's just the subscription to the event. That's not actually *invoking* the method - that happens when the event is raised. Yes, I strongly suggest you read my article or another on event handling basics - I think you're a bit confused about how it all fits together at the moment.
Comment: Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/99953/discussion-between-mike159-and-jon-skeet).
Comment: I think the point I am getting stuck at is `PacketReceived?.Invoke(this, new PacketEventArgs(packet));`

Outside of the class how to I actually access the packet? The original delegate method assigned a method to the event which is called when data is received (the packet is then passed to be used). Now I can't assign my method because it is expecting a byte array when it is being assigned.
Comment: @Mike159: Outside the class, you would have an event handler which would receive the `PacketEventArgs`, (as the second parameter) and then access the `Data` property (or whatever) you'd add to `PacketEventArgs`. You'll need to change the method you're subscribing with to have an appropriate signature.
Comment: Thanks. Now it compiles and I can step through it this method makes a lot more sense.

Do not nest type warning (C#)


How can I upload 1000s of nodes per hour to a live drupal 7 site and avoid deadlocks?

Question: Not too long ago I wrote about deadlock here: PDOException: SQLSTATE[40001]: Serialization failure: 1213 Deadlock found when trying to get lock;
Despite everything my development team tries to do, we still get errors like this:

PDOException: SQLSTATE[40001]: Serialization failure: 1213 Deadlock found   when trying to get lock; try restarting transaction: INSERT INTO     {location_instance} (nid, vid, uid, genid, lid) VALUES (:db_insert_placeholder_0, :db_insert_placeholder_1, :db_insert_placeholder_2, :db_insert_placeholder_3, :db_insert_placeholder_4); Array ( [:db_insert_placeholder_0] => 1059 [:db_insert_placeholder_1] => 1059 [:db_insert_placeholder_2] => 0 [:db_insert_placeholder_3] => cck:field_item_location:1059 [:db_insert_placeholder_4] => 1000 ) in location_save_locations() (line 974 of /var/www/website.com/sites/all/modules/location/location.module).

Despite the specific table in that example, we get this error on other tables.
Here is my situation. I have taken a large University project. At any given time there are 50,000 campus residents who use the system daily.  In addition to that, I am migrating 100s of 1000s of items of content both manually and through custom module code (migration from the old university data) to this new Drupal 7 site.
This error is killing us, to the point where we are almost ready to scrap the last years worth of work and go with something else if Drupal cannot handle this type of load.
But that is more or less my question -  How can Drupal handle this type of load?  How can I organize my work flow to be able to handle this much activity? Is this a Drupal issue? A database issue?
Specifically, I am running Ubuntu, LAMP stack 16GB RAM. I am open to any suggestion whether it be Drupal related, database related, server config related, or a different work flow to work within Drupal's capabilities, so feel free to suggest anything if you have experience with this much activity.
Comment: There is an article about importing large dataset http://evolvingweb.ca/story/import-hundreds-thousands-records-15-seconds-custom-entities
Comment: Thank you for that. It's very encouraging to see that volumes of data can indeed be imported almost instantaneously.  However, what about the issue of individual users posting through their own accounts through the node forms? As I dig and dig more into this problem, the rhetorical questions in my head grow, "Can Drupal handle this much live traffic? If not, then what is the point?"  Aside from the imports, we have a team of about 20 who are adding content normally through their accounts. Can Drupal 'node save' really only  handle 20 simultaneous users adding data at a time?
Comment: We tested our Drupal site with Apache JMeter using MySQL and PostgreSQL. For MySQL our results were about 20 nodes. For PostgreSQL results were much better.
Answer: I work for Stanford university and have been doing similar things. We constantly have to load over 100,000+ nodes on a regular basis. We have been working on our own custom loading code for 2 years now have been able to speed up the process quite a big using pcntl_fork. The only thing you have to remember is to close all socket connection before invoking the fork. For example you have to close you mysql connection, memcache connection and even mongo connection. Drupal will automatically create new connections when one doesn't exists. As far as the deadlock problem, we were able to fix that issue by putting innodb_locks_unsafe_for_binlog = 1.
Comment: are you loading those in in  batch with custom code or using some of drupal's API functions like node_save? Or a migration type module?  Also is the code you mentioned available for public view? Would be nice to see how pcntl_fork is integrated with drupal to see you you guys have overcome this obstacle. Thanks for the binlog tip!
Answer: The answer is: Configure your MySQL my.cnf file correctly.
After a little over a week of research, I have found that Drupal 7 can indeed handle this much concurrent input traffic.
These Deadlock PDOExceptions were related to the MySQL my.cnf file not being optimized correctly. With help from the Drupal High Performance group and other sources, our team has not had one single Deadlock happen since implementing the new configuration settings for MySQL. We tested our batch scripts to simulate up to 500 current users saving content with no problem.  Check out the thread here.
http://groups.drupal.org/node/260938
Specifically, Dalin suggested using a wizard to get a base configuration file based on the server specs and table types. After using this, even without further tweaking, the deadlocks stopped. Here is a link to the wizard if you would like to try it: https://tools.percona.com/wizard
I'll be happy to post the my.cnf file if anyone would find it helpful.
Although the Deadlock problem is no longer an issue, we are now getting this error very frequently:
PDOException: SQLSTATE[42000]: Syntax error or access violation:
1305 SAVEPOINT savepoint_1 does not exist: ROLLBACK TO SAVEPOINT savepoint_1;
Array ( ) in file_usage_add() (line 661 of /var/www/website.com/includes/file.inc).

Could this be a mysql configuration issue as well?
Comment: We're starting to see that error ourselves.  Did you ever find an answer to your question?
Answer: http://dev.mysql.com/doc/refman/5.0/en/innodb-deadlocks.html this mysql page  suggests what to do when you encounter the deadlock.
By fine tuning your mysql configuration will help you to solve this issue.


Left align in inline node

Question: So I've got a row of text with a leading icon.  I need the text to multi-line align left while the icon remains centered vertically with relation to the text.

    My block of long text that will go multiline when the window is resized

Let me attempt to explain with some ASCII. I put a border on the row to help visualize it. 'O' is the icon.
+--------------------------------+
|     My block of long text that |
|  O  will go multiline when the |
|     window is resized          |
+--------------------------------+

+-----------------------------------------------------------------------------+
|  O  My block of long text that will go multiline when the window is resized |
+-----------------------------------------------------------------------------+

Unfortunately, my company's stuck (for the time being) using a home-brewed web framework that limits my use of javascript.  The goal here is to have this working with straight CSS, which I have full access to.  I've messed with floats, clears, inline, inline-block, block, margins, etc.  My front-end-fu is quite weak, so I need some help from some of you ninjas out there.
The overall point here is to make this look nice when the window is wide on desktop and when it's narrow on mobile.
TIA!
Comment: Do you have any relevant code you could add?
Comment: Are you able to set the height of the div that contains the icon and paragraph? Also, you're basically just going to set the icon to be  a box at a certain size so the paragraph knows never to go into that space.
Comment: Not that I can think of.  Perhaps just making it clear the div will be growing and shrinking.  Anything in particular you'd like to know about the context?
Comment: @slime I can set the height on both.  I can also set the width on the icon, but don't want to on the paragraph.
Answer: This could be one solution:
.icon {
  width: 25px;
}

.otherspan {
  width: calc(100% - 25px);
}

This way your icon will always take up a fixed width and the text span will shrink as the viewport shrinks.
Answer: Here's how I would do it...
HTML

My block of long text that will go multiline when the window is resizedMy block of long text that will go multiline when the window is resizedMy block of long text that will go multiline when the window is resizedMy block of long text that will go multiline when the window is resized

CSS
* {
    box-sizing: border-box;}

div {
    display: block;
    background: #ddd;
    padding: 25px;}

.icon {
    display: inline-block;
    background: black;
    vertical-align:middle;
    height: 20px;
    width: 20px;}

p {
    display: inline-block;
    vertical-align: middle;
    width: calc(100% - 20px);
    padding-left: 25px;}

Comment: This works, but I've already chosen the other one.  I'll upvote as consolation. Thanks for your help!
Answer: If I understand you correctly though, this is what you are trying to do?
Where the

 is your image

.image {
    height:150px;
    width:150px;
    background-color:grey;
}

            Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur porttitor rhoncus porta. Phasellus porttitor magna sed diam ullamcorper tincidunt. Maecenas tempor molestie iaculis. Fusce ultricies elit et commodo faucibus. Quisque vel velit id urna tincidunt pharetra. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Nunc in est nec magna pulvinar pellentesque. Donec ac dui lacinia, blandit nulla vel, eleifend mi. Integer non tellus at massa ornare feugiat id a enim. Suspendisse vel placerat orci. Morbi vitae nulla sed augue tristique sollicitudin sed ut lacus. Mauris vulputate placerat tincidunt. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Vivamus ultrices in nulla blandit molestie. Praesent vel nisl rutrum, maximus mauris egestas, consequat enim. Nulla eget dapibus arcu.

Comment: Ahh yes, tables.  I would have gone with this, but @dfsq's solution worked without them.  Thanks for the answer.
Answer: One solution would involve positioning of the icon relative to the div with vertical alignment.

div {
    background: #EEE;
    position: relative;
    padding-left: 28px;
    min-height: 26px;
    line-height: 26px;
    margin-bottom: 10px;
}
.icon {
    display: inline-block;
    width: 24px;
    height: 24px;
    background: url(https://cdn1.iconfinder.com/data/icons/hawcons/32/698572-icon-6-mail-envelope-closed-24.png) no-repeat 0 0;
    position: absolute;
    left: 0;
    top: 50%;
    margin-top: -12px;
}

    My block of long text that will go multiline when the window is resized

    My block of long text that will go multiline when the window is resized

    My block of long text that will go multiline when the window is resized

Left align in inline node


AWS S3 bucket permissions

Question: I've created AWS s3 buckets with several thousand objects, initially the access policy was restricted to authenticated users, but later due to some requirement we need to make all objects in this bucket publicly visible. For this we have made the following changes.

Added new permission set "Everyone" with "List" access.
Added new policy to bucket.

**
<code>{
    "Version": "2012-10-17",
    "Id": "Policy1111",
    "Statement": [
        {
            "Sid": "makeitpublic",
            "Effect": "Allow",
            "Principal": "*",
            "Action": "s3:GetObject",
            "Resource": "arn:aws:s3:::bucketname/*"
        }
    ]
}
</code>
**
After this I can see some objects in bucket are publicly accessible while others are not. My question is after make this bucket "Public" will the new permissions will be applied to all existing objects or only to the newly uploaded objects ?
If yes then is there any way to bulk change permission of objects in a bucket.
Comment: I think your Principal should be `*` and you should also have a `*` after your bucketname in the Resource, so `"arn:aws:s3:::bucketname/*"`
Comment: Thanks for pointing out, well both are *. I've corrected in the question.
Comment: Are you able to share any of the initial policies that were applied before the decision to grant public/anonymous access?  Were there any explicit deny policies?
Comment: Well there were no policies before this, currently this is the sole policy in place.
Answer: I think you should check the S3 web console under the Permission tab to verify the older objects policy.
Normally API issued policy are valid for newly uploaded objects, but changing the bucket permission via web console should fix it.

AWS S3 bucket permissions


How to restore Jesson's value and put it into outside variable

Question: I have a problem with this code
I manage to take the values from the json and put them into variables but I can not use them outside the function
what am i doing wrong ?
var sensor_name1;
var lat1;
var lng1;
var sensor_name2;
var lat2;
var lng2;
var sensor_name3;
var lat3;
var lng3;

 $(function (){
 var $sensors = $('#sensors');

 $.ajax({
 type:'GET',
 url:'http://127.0.0.1:5000/',
 success: function(sensors){
 $.each(sensors, function(i, sensor) {
 if (i==0){
 $sensors.append(sensor_name1=sensor.name, lat1=sensor.lat, lng1=sensor.lng);
 }
 if(i==1){
 $sensors.append(sensor_name2=sensor.name, lat2=sensor.lat, lng2=sensor.lng);
 }
 if (i==2){
 $sensors.append(sensor_name3=sensor.name, lat3=sensor.lat, lng3=sensor.lng);
 }

 });

console.log('sensor one : ',sensor_name1, lat1, lng1);
console.log('sensor tow : ',sensor_name2, lat2, lng2);
console.log('sensor three : ',sensor_name3, lat3, lng3);

  }
 });

});

Answer: Hi and welcome on Stack Overflow :)
JavaScript Ajax is asynchronous and you execute console.log() before these variables receive a value.
But in your case you pass to append() which accepts a htmlString, Element, Text, Array or jQuery parameter a assignment of value expression. You don't append a child, but you declared it using append()
You must have to wait for response from server and after use that.
$(function () {
    var $sensors = $('#sensors');

    $.ajax({
        type: 'GET',
        url: 'http://127.0.0.1:5000/',
        success: function (sensors) {
            $.each(sensors, function (i, sensor) {
                let sensorInfo = 'sensor #'+i+': '+sensor.name+' '+sensor.lat+' '+sensor.lng;

                console.log(sensorInfo);
                $sensors.append('
'+sensorInfo+'
')
            });

        }
    });

});

Greetings, plum!
Sources:
Asynchronous on MDN: https://developer.mozilla.org/en-US/docs/Glossary/Asynchronous
jQuery Docs: https://api.jquery.com/jQuery.get/#jQuery-get-url-data-success-dataType
Comment: I tried it but now it does not read the Jesson at all
Before that I received a response from the server and managed to put the value of the jason in variables but only that they are within the function
Comment: You are trying to get to something that will be in the future, this is response. If you want to access a data outside the function and after assignment you must assign value to global scope. Look at this example (https://jsbin.com/kezolisuqo/edit?html,js,console,output) and read more about [scopes](https://stackoverflow.com/questions/500431/what-is-the-scope-of-variables-in-javascript) and [closures](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures).


From 32 + 32 bit to double

Question: for some reason I need to retrieve a double value from two 32 bit. Let me explain:
On the server side they send a double value formatted like this:
<code>  // C/C++ = SERVER
  double big;
  big = 12345.67890;
  unsigned int *pi = (unsigned int *)&big;

  unsigned int x = pi[0];
  unsigned int y = pi[1];
</code>
they send from the server to the client a double formatted with two unsigned int (x and y, 32 bit each in my case).
On the client side (JAVA) I need to build again the double value from the two unsigned integers received. I tried this without success:
<code>// double double64 = buffer2.getDouble();
ByteBuffer buffer = ByteBuffer.allocate(16);
buffer.putLong(my_int_x);
buffer.putLong(my_int_y);
buffer.flip();
double double64 = buffer.getDouble();
</code>
maybe because I'm receiving a 32 bit integer and I use "putLong"?
Comment: A long is 64 bits in Java. Is there something like putInt you could use instead?
Comment: As an example of this, item 4 in http://www.viva64.com/en/a/0004/ warns about this point
Comment: @Jorge_B: I used "like this" not by case ... I've just sent a PoC code to try to explain my problem in few lines of code.
And just fyi the server is multiplatform and servers something like half million request every day ... but thanks for your advice ;-)
Comment: Maybe not a fortunate comment at all, let me make it more constructive: I see a portability threat in assuming things about the size of a type in C, since every data type has not had the same size historically in all architectures and implementations of C.  However, if it is not exactly your production code, then there is no threat
Answer: To convert two ints (containing double data) into a double, you don't need a temporary buffer. You can do this:
<code>long doubleBits = my_int_x & 0xFFFFFFFFL;
doubleBits <<= 32;
doubleBits |= my_int_y & 0xFFFFFFFFL;
double myDouble = Double.longBitsToDouble(doubleBits);
</code>
However, check how you are reading my_int_x and my_int_y in your Java program. Maybe you can get a double directly at that moment (ideally, you should).
Comment: I don't see any endianness problem here ... double type representation is standard (IEEE 754) and on the java side there is not endianness involved, we just copy two buffer.

From 32 + 32 bit to double


What is a Hyper-Sphere?

Question: I am interesting about the geometric properties of 3-D spheres and I know nothing about hyper-spheres. Please can you describe me, what is a hyper-sphere?
Answer: A  hypersphere (or $n$-sphere) is the set of points in $n$-dimensional space such that the distance from the point to the origin is constant:
$$
\{ x \in \mathbb R^n : | x | = c \}
$$for some constant $c$.
The most common use of the word refers to the $n = 4$ case.
Comment: There is some more information here:
http://mathworld.wolfram.com/Hypersphere.html
Comment: Why special on n=4 case?
Comment: Just because that is one more dimension then we have in our universe.  It is the first "weird" dimension, when we can no longer have a true mental picture of it.  Similar to a "hypercube" in four dimensions; note that the picture here cannot possibly be four dimensional, and yet it tries to represent a four dimensional shape:
http://en.wikipedia.org/wiki/Hypercube

What is a Hyper-Sphere?


Tem como fazer uma MAPA DE CALOR em uma imagem?

Question: Eu estou utilizando a planta de uma casa, dentro das peças da casa, possuem sensores. Eu quero fazer um mapa de calor, mapeando os locais onde mais se disparam os sensores, mas não sei por onde começar. Eu estou tentando fazer umas gambiarras com CSS, mas pelo que pesquisei, se usa JavaScript, só que ainda to perdido nisso
Comment: Refaça sua pergunta sendo mais objetivo, não sabemos se você quer construir uma aplicação que gere um mapa de calor para qualquer imagem inserida ou simplesmente editar apenas uma imagem.
Comment: O que acha de fazer um contator de cada sensor na casa, ai vai ter a quantidade, pode usar essa quantidade para escurecer a cor, pode fazer isso via javascript, pesquise sobre.
Agora voce vai ter um sensor em cada ponto da sua planta definida no seu css por id, via javascript voce pode manipular isso.
Answer: Existem várias maneiras de implementar um heatmap. Caso você queira utilizar algo já pronto, Heatmap.js é uma biblioteca javascript que faz exatamente isso. De acordo com sua documentação, a biblioteca suporta até 40.000 pontos por mapa.
Este é um exemplo que pode lhe ser útil.


Why responsive email works well on litmus test, but broken after sending it

Question: I am testing a responsive email template named "Sidebar Hero" provided by ink, here's the link.
And when I test it at litmus, the screenshots at android and apple show that responsive works great as expected. Here's my test's screenshots: android4.0, and iPhone. You can check others android and iPhone aside.
But when I sent it from client(like thunderbird, outlook), the responsive broken. The email looks like a mess. Here's the scrrenshot:

How code was produced:
I download the template code directly from template page, and then use inliner tool provided by Ink too to make style inline. And then nothing. Everything done. In case you need my code
What I miss Or Any unaware mistakes that I make?
Anyone can help. Thanks very much !
Answer: Are you sending it through a corporate MS Exchange network? Sounds similar to an issue I had a while ago where the Exchange server at my work was stripping my media queries. Maybe try sending to a different email address on a different non-corporate domain to see if it makes a difference.
Comment: John is going in the right direction here. You should be sending it through a proper email service provider. Outlook and thunderbird will totally screw with your media queries (and HTML I've seen links not work). Look into services like MailChimp and Campaign Monitor. They are designed to send HTML emails properly.
Comment: Not all. I sent it through Gmail too and other email server(163 etc). Not luck also. Do you have some can work to let me know and have a try? Thanks :D
Comment: Where are you sending it from?  Are you using an email service provider or are you pasting your code into Outlook?
Comment: @DarrylVos. Thanks. I will try MailChimp and Campaign Monitor as Darryl suggest. I sent email using thunderbird and outlook. Maybe they did trim my code. :D
Comment: @John, I paste my code into outlook and thunderbird. I will try services like MailChimp and Campaign Monitor suggested by Darryl Vos.
Comment: @DarrylVos, you give me a big help. Campaign Monitor do the right thing !! Thanks. :D
Answer: Having a similar issue...
In the docs it recommends using the Block grid for Gmail (Mobile, iOS, Android) because it is still flexible without using media queries. Also check out the compatability table right above the "Sub Grid" header.
Apparently the main caveat for using the block grid instead of the default one is:
"Make sure that there isn't any whitespace between your  elements, otherwise Thunderbird will add a gap between your block-grid elements."
Answer: For floating two columns on top of each other ink template it's using column splitting instead of table aligning.
An issue that I found regarding this method is that display-block or float:left on "td" is not working for some android versions because the Doctype gets stripped.
The solution is to use "th" instead of "td" and to make sure to override the font-weight and align for "th", cause by default it's bold and center.


How to use GADTs in Hugs

Question: I'd like to write a Haskell program that uses GADTs interactively on a platform not supported by GHCi (namely, GNU/Linux on mipsel).  The problem is, the construct that can be used to define a GADT in GHC, for example:
data Term a where
    Lit :: Int ->  Term Int
    Pair :: Term a -> Term b -> Term (a,b)
    ...

doesn't seem working on Hugs.

Can't GADTs really be defined in Hugs?  My TA at a Haskell class said it was possible in Hugs, but he seemed unsure.
If not, can GADT be encoded by using other syntax or semantics supported by Hugs, just as GADTs can be encoded in ocaml?
Comment: @is7s: how can I do that? Currently I run hugs with option `-98`.
Comment: Folks -- GHC-specific language extensions are not available in Hugs.
Answer: GADTs are not implemented in Hugs.
Instead, you should use a port of GHC to mips if you are attempting to run code using GADTs. Note that you won't be able to use ghci on all platforms, due to lack of bytecode loading on more exotic architectures.
Comment: Some GADT examples can be translated to type classes, http://martijn.van.steenbergen.nl/journal/2009/11/12/gadts-in-haskell-98/
Comment: Thanks, I will use ghc once I finish writing my code.  However, when you're halfway it might be useful to have an interpreter.  Do you have an answer to the question 2, about encoding GADTs in Haskell'98?
Answer: Regarding your question 2 (how to encode GADT use cases in Haskell 98), you may want to look at this 2006 paper by Sulzmann and Wang: GADTless programming in Haskell 98.
Like the OCaml work you're referring to, this works by factoring GADTs through an equality type. There are various ways to define equality type; they use a form of Leibniz equality like for OCaml, which allows to substitute through any application of a type operator at kind * -> *.
Depending on how a given type checker reason about GADT equalities, this may not be expressive enough to cover all examples of GADTs: the checker may implement equality reasoning rules that are not necessarily captured by this definition. For example, a*b = c*d implies a = c and b = d: this form of decomposition does not come if you only apply type constructors at kind * -> *. Later in 2010, Oleg discussed how you can use type families to apply "type deconstructors" through Leibniz equality, gaining decomposition properties for this definition -- but of course this is again outside Haskell 98.
That's something to keep in mind for type system designers: is your language complete for leibniz equality, in the sense that it can express what a specialized equality solver can do?
Even if you find an encoding of the equality type that is expressive enough, you will have very practical convenience issues: when you use GADTs, all uses of equality witness are inferred from type annotations. With this explicit encoding you'll have much more work to do.
Finally (no pun intended), a lot of use cases of GADTs can be equally expressed by tagless-final embeddings (again by Oleg), that IIRC can often be done in Haskell 98. The blog post by Martin Van Steenbergen that dons points to in its reply's comment is in this spirit, but Oleg has considerably improved this technique.

How to use GADTs in Hugs


Is this melody aligned with this drum beat? If so/not - why (not)?

Question: I wasn't entirely sure how to ask this question, so I'll use visual references.
Please look at this piano roll picture: the green "blocks" represent the notes of a melody, the purple ones - the hits of the snare, and the orange ones - the hits of the kick drum. The tempo of the song is 158 BPM, and the vertical red lines represent each beat of the metronome.
Now, my question is: is the melody aligned well with the drums? If so, what makes it so? If not, how would the "blocks" need to be moved? Must each of these vertical lines mark the beginning of a new note in order for this to be OK? What if that messes up my melody? Would I have to rearrange the drum beat pattern if I wanted to keep this melody? Where can I read up on the theory behind this?
Thanks for your help!
Comment: how does it sound?
Comment: It's impossible to tell without hearing it if it's in time, because different sounds that you use to play these notes will have different envelopes - and those different envelopes will require the underlying note data to be slightly different to achieve the similar senses of timing.
Comment: it would help people determine if it sounded good, but i was more asking you if you thought it sounded good. i don't think there are any rules that determine what a good alignment between melody and drums is. just go with what you think sounds good.
Comment: Hi, thanks for commenting. Are you asking me to upload a recording of this?
Comment: All right, here's a larger part of that melody with kick, snare and hat (ind you, this is unmixed, without all of the effects, etc.): https://www.dropbox.com/s/ssnab3j30zd1hpq/CotW.wav?dl=0

@b3ko I think it sounds ok, but I'm deaf when it comes to rhythm plus I really thought there was some piece of music theory or another that determined it (i.e. like you can't take a melody, create a second track with just any notes and call that a harmony).
Comment: i'll have to check the link out later. harmony is created by stacking notes up into chords, not really by matching it up with percussion. there is the concept of harmonic rhythm but that has more to do with how quickly the chords change, and less about how they line up with the drums.
Answer: I think it sounds great, but it really depends on a few things. What style of music are you going for? Out of context this sounds more like an improvisatory solo than strictly a melody, is that the kind of vibe you want?
This, when written out into musical notation, would be quite syncopated (the guitar line at least). However in juxtaposition to the very rhythmic drum beat I think it works very well.
Comment: thanks very much for the kind words. The style is supposed to be heavy/power metal. The "melody" is supposed to be a stand-in for vocals (and the whole things is supposed to be a demo of sorts to lure potential victims/bandmates ;) )  Re: syncopation, via Wikipedia: "syncopation involves a variety of rhythms which are in some way unexpected which make part or all of a tune or piece of music off-beat" ... so the clip I uploaded IS off-beat but that isn't necessarily a bad thing? Also, in the "melody", I'd like to extend the note at 0:09, but I'm afraid I'd go even further off-beat.
Comment: Sorry I wasn't thinking and didn't realize you wouldn't know what syncopation was. Syncopation is a very common technique used to throw off our sense of the beat, used as early as Mozart, or possibly before (off the top of my head I can't remember), but used very commonly in jazz.
Comment: I think a great experiment for you would be to line the start of every green bar (guitar) up with every red vertical line, which is technically a beat, and see how it sounds. I don't think it would be any better but it might give you an idea of what you're dealing with. SO many things can influence what sounds 'rhythmic', including the way an instrument attacks a note and how long it takes to sounds. for example, hit a note on a piano and it sounds almost immediately, but hit a gong and it takes a few seconds to reach max volume. These would all show up as a green bar in your program anyway.


InvalidateRect then Cimage.Draw()

Question: I try to create small animation (a moving PNG object) using:
pDC -> GetWindow() -> InvalidateRect(lpRect); // Clear old Draw()
image.Draw(pDC -> GetSafeHdc(),MyBmpFile::Instance() -> getxDest(), MyBmpFile::Instance() -> getyDest(),50,50); // Draw my CImage
MyBmpFile::Instance() -> Update(pDC); // change xDest, yDest to new one, and move lpRect to new position

As long as I do not use invalidate() the PNG is drawing, but I need to clear the old one before I draw the next one. When the above code compiles, there is nothing in my dialog window.
Comment: You ought to write your answer as an answer to flag the question as been answered.
Answer: Ok the answer was simple : http://msdn.microsoft.com/en-us/library/6yz8we9y(v=vs.80).aspx
I just need to UpdateWindow() after invalidate();

InvalidateRect then Cimage.Draw()


What's the theory behind switching modes during a passage?

Question: Look, at the following two chord progressions:

(1) Dm C Bb Am Gm F Em Am
(2) Dm C Bb Am Gm F E  A

Now, for the first six measures in both (1) and (2), we're just playing chords contained inside the Dm scale (D E F G A Bb C). However, I find (2), where I at the end deviate from the Dm scale, more pleasant than (1), where I just keep to the Dm scale all way through. In (2), I find that what sounds best is to use some kind of arabic sounding scale (E F G# A B C D) and (A Bb C# D E F G) for the last two chords when improvising over them.
Is there any theory that can back up my inuition? What is happening here? Why am I switching modes instead of just sticking to the Dm scale?
Answer: In (2) the E and A chords constitutes dominants for respective following chord. Especially with the scales you mention which entails the minor sevenths. The E7 is a secondary dominant and the A7 is the dominant of Dm.
Dominants are associated with a strong urge to resolve to their next chord in the circle of fifths. This particular sequence, E7 A7 Dm (or V7/V-V7-i) is a very common cadence that your ears likely favor before the much less resolve prone sequence of Em7 Am7 Dm.
(I'm here assuming you repeat the chord sequence or at least go on to a following Dm.)
EDIT:
The scales you list (mixolydian b2 b6) I believe is the natural consequence of making the E and A chords dominant - with a major third (and a non-flatted fifth, and a minor seventh) - while otherwise sticking to the Dm tonality.
Answer: Note that in your progression (1) the Em chord is not actually in the Dm scale. The equivalent Dm chord here would actually be a diminished triad Eo = E-G-B♭.
In D minor key, the classic ii-V-i cadence would be Eø-A7-Dm, where Eø is a half-diminished chord.
When you use A7 vs Am as the V chord, this is now a D harmonic minor scale. I tend to think of the harmonic minor scale as "normal (melodic) minor, except when on the V chord".
Comment: From my understanding of D minor, both Bb and B are in it. I'd call both Em and E° as being in the Dm scale. Now D natural minor/D Aeolian only accepts E°...
Answer: The non-diatonic major 3rds of the last two chords are both "leading tones" that resolve to the roots (tonics) of the immediately following chords, i.e. G#(Maj 3rd) => A(Tonic), and C#(Maj 3rd) => D(Tonic), if you added the min 7th (dominant 7th) to each chord (D added to E = E7 and G added to A = A7) it would create a tri-tone (very unstable/restless/dissonant/tense) together with the 3rd of the respective chord (G# and D = tri-tone / C# and G = tri-tone). This resulting tension creates a sense of movement... or maybe unsettledness or "dissonance" that tends to want to "resolve" in a certain way. With the G# & D in a E7 the G# => A and the D => E; in the same way the C# and G want to go to D and A (respectively) because of the tension introduced by the tri-tone.
Incidentally... the last 3 chords are properly represented by V/V => V => i... (or V7/V => V7 => i if you want to add the dominant 7ths).
My own opinion here is that you can literally play anything you want to over the dominant 7th chords as long as you resolve it to the following chord... i.e. for E7: G# dim arpeggio, E "super-locrian/altered scale" (7th "mode" of melodic minor), octatonic scales (whole-half, half-whole) based off the previous leading tone (diminished arp. again), whole-tone, chromatic, different pentatonic scales, chromatic/diatonic passing tones, appoggiaturas, etc... (personally I tend to be adventurous here and have a completely "anything goes" attitude… even something completely random as long as you bring it back home at the right time, in the case of E7 to A come back to A maj and then go "out" again until you need to resolve when you hit dmin)... look for chromatic resolutions back to the diatonic sound or most strongly to a chord tone of the following chord (most of this can pretty much be explained by the concept of tri-tone substitution... an inverted tri-tone is still a tri-tone and implies another possible root or tri-tone above/below the root of the V which ends up being a half-step above the "tonic" or root of the target chord).
Basically your desire to add the G# and C# over the E and A is simply a desire to play the right quality of 3rd (maj vs. min) on top of the maj E and A chords (you are simply matching the scale/mode to the chord or "playing the changes", a very common and accepted technique for improvisation over chord changes). Note that you'll want to return to G and C natural over the dmin at the end... remember G# resolves to A (G natural is reintroduced as the 7th of A7) and C# wants to go to D (and C natural comes back as the 7th of D). If you don't change these notes in the way you've described you'll hear the clash of a minor 2nd over each... G# against G and C# against C... although, like I said, you can get away with it if you do it the right way (left unchanged they would be a #9th altered dominant sound and turn into dominant 7ths of the following chord... but if you don't play the tri-tone and then resolve it as well they're more likely to sound odd... so if you want to play the G and C as a #9 tonality you still need to add the G# and D as well as the C# and G respectively to E and A).
I should probably add that my answers here in relation to tri-tone sub. theory would be identified as more "Jazz" than "Classical", although personally I don't like drawing a distinction.
Answer: You establish Dm during your song, in both lines. The second last chord is expected to be Eº or Eø diatonically, but instead you use

Em for the first line (so Bb in the scales becames altered Bb->B)
E for the second line (so Bb and G became Bb->B and G->G#)

For the first line you are stepping within minority from an A natural minor scale to an A melodic minor scale (V grade, Mixolydian b6), but I think it's safer to simply say we are modulating from natural minor to dorian. If it's a temporal "chromatic" modulation or not, we can only tell by hearing the overlapped melody notes (since we don't know in which mode does the ambiguous Em plays).
For the second line you are stepping within minority from an A natural minor scale to an A harmonic minor scale (IV grade, Dorian#4, the "Romanian" scale), which is normally more "hearable" as it keeps the (b3,)b6 alteration structure for which the minor scales have sense when harmonizing in thirds. You can assume the Harmonic minor function as you end with an A (probably it's not casual, you felt it was called), which specially if its A7, claims for the Dm again (V7-I is the typical cadence for Hm).
This is same use as in Tico-Tico Na fubá (typical accordion song):  Dm-A7-Dm. Gm-Dm,  E7-A7-Dm (in D as yours) [it certainly has these romanian fanfar feel]
Tico-Tico Na Fubá
Am-E7-Am, Dm-Am, B7-E7-Am
You are moving in fifths taking profit of this V7-I power V7-of-V7-of-I, V7-of-I, I, it's like a modal interchange in between the harmonic scale. Blues uses oftenly this principle as well.
E G# B D   = E7          = V7 of Am
| V   V  |
E A  C (D)   = Am(add11)   = I  of Am
Leading note is clear, semitone moving creates a perfect fit strength, as G# moves to A whilst B does the same to C, and meanwhile the other notes are fixed.
Answer: The question is more 'should I stick in one mode/key' throughout a piece of music'?   And the answer is 'Of course not! Whatever gave you that idea?'
Show me any song, with any chord progression, I'll find a way of fitting it into 'theory', whether it's all in one mode, moves to another one, 'borrows', 'planes', 'pivots' or just plain jumps into unknown territory for a dramatic contrast.  I can help you to label a pleasing sequence, so you can use it again.  But this doesn't give you permission to use any particular sequence. Your ear and brain does that.
'Theory describes, it does not command'.  I'm going to keep saying that until it sinks in :-)


IEnumerable.Except() between different classes with a common field

Question: Is it possible to use Except() for two List's that have two different classes but a common field? I have List<User1> and List<User2> collections. They have different properties except Id column and I want to find the different records between them using this Id column. I'm trying to use List<>.Except() but I'm getting this error:

The type arguments for method 'System.Linq.Enumerable.Except(System.Collections.Generic.IEnumerable, System.Collections.Generic.IEnumerable)' cannot be inferred from the usage. Try specifying the type arguments explicitly.

Here's what I'm trying:
List<User1> list1 = List1();
List<User2> list2 = List2();
var listdiff = list1.Except(list2.Select(row => row.Id));

What am I doing wrong?
Comment: Please read [this](https://blog.mariusschulz.com/2011/08/08/why-enumerableexcept-might-not-work-the-way-you-might-expect) famous blog to understand the internals of `Enumerable.Except()` method.
Answer: List1 contains instances of User1 and List2 contains instances of User2.
What type of instance should be produced by list1.Except(list2.Select(row => row.Id))?
In other words if type inference was not available, what would you replace var with?
If User1 and User2 inherit from the same ancestor (with ID), use List<User> instead.
Otherwise:
var list2Lookup = list2.ToLookup(user => user.Id);
var listdiff = list1.Where(user => (!list2Lookup.Contains(user.Id))

Comment: +1 if you make the lookup on `list2` instead of `list1`. Or without the lookup `var listdiff = list1.Where(user => !(list2.Any(user2 => user2.Id == user.Id));`
Comment: Note that this doesn't have exactly the same semantics as `Except`. `Except` returns the "set difference" of the two sequences; that is, only unique items from the first sequence are returned (and, obviously, only returned if they're not in the second sequence). http://msdn.microsoft.com/en-us/library/system.linq.enumerable.except.aspx
Comment: Yes, the problem here is that the sequences are heterogeneous so we need to get down to a 'common ground'
Comment: Yup noticed that mistake a couple of minutes ago
Comment: Excellent. I was looking for using Except() but it seems you can't use it if you don't have a common ground for both classes. I'd like to know why you chose to use LookUp<> though?
Comment: To speed up the check whether list2 also contains the current element (list2Lookup.Contains(user.Id)).
Comment: Worked great for me, cheers guys! Still marveling at the power of LINQ when you properly bend it to your will :-)
Answer: Not Except, but the correct results and similar performance:
// assumes that the Id property is an Int32
var tempKeys = new HashSet<int>(list2.Select(x => x.Id));
var listdiff = list1.Where(x => tempKeys.Add(x.Id));

And, of course, you can wrap it all up in your own re-usable extension method:
var listdiff = list1.Except(list2, x => x.Id, y => y.Id);

// ...

public static class EnumerableExtensions
{
    public static IEnumerable<TFirst> Except<TFirst, TSecond, TKey>(
        this IEnumerable<TFirst> first,
        IEnumerable<TSecond> second,
        Func<TFirst, TKey> firstKeySelector,
        Func<TSecond, TKey> secondKeySelector)
    {
        // argument null checking etc omitted for brevity

        var keys = new HashSet<TKey>(second.Select(secondKeySelector));
        return first.Where(x => keys.Add(firstKeySelector(x)));
    }
}

Answer: Briefly, make lists to be List<object> and use C# feature from .NET 4.0: dynamic.
Example:
var listDiff = list1
    .AsEnumerable<object>()
    .Except(list2
        .AsEnumerable<object>()
        .Select(row => ((dynamic)row).ID));

Comment: Sorry forgot to add that I'm using v3.5
Answer: If you just want the Ids in list1 that are not in list2, you can do:
var idsInList1NotInList2 = list1.Select(user1 => user1.Id)
                                .Except(list2.Select(user2 => user2.Id));

If you need the associated User1 objects too, here's one way (assuming Ids are unique for a User1 object):
// Create lookup from Id to the associated User1 object
var user1sById = list1.ToDictionary(user1 => user1.Id);

// Find Ids from the lookup that are not present for User2s from list2
// and then retrieve their associated User1s from the lookup
var user1sNotInList2 = user1sById.Keys
                                 .Except(list2.Select(user2 => user2.Id))
                                 .Select(key => user1sById[key]);

EDIT: vc74's take on this idea is slightly better; it doesn't require uniqueness.
Answer: public static IEnumerable<TSource> Except<TSource, CSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> TSelector, IEnumerable<CSource> csource, Func<CSource, TKey> CSelector)
    {
        bool EqualFlag = false;
        foreach (var s in source)
        {
            EqualFlag = false;
            foreach (var c in csource)
            {
                var svalue = TSelector(s);
                var cvalue = CSelector(c);
                if (svalue != null)
                {

                    if (svalue.Equals(cvalue))
                    {
                        EqualFlag = true;
                        break;
                    }
                }
                else if (svalue == null && cvalue == null)
                {
                    EqualFlag = true;
                    break;
                }
            }
            if (EqualFlag)
                continue;
            else
            {
                yield return s;
            }
        }

    }

Answer: Try
list1.Where(user1 => !list2.Any(user2 => user2.Id.Equal(user1.Id)));

Comment: Welcome to [so]! Why does this work? Those who can answer that question for themselves probably don't need someone else's code.


Why does this JavaScript cause a "Permission Denied" error in IE

Question: The following code throws a Permission Denied error in IE, citing jQuery (1.6.2) line 6244 Char:2:
function addAgreement() {
    var url = window.location.toString();
    var pieces = url.split('/');
    var site_url = url.replace(pieces[pieces.length -1], '');
    $('.login').append('

');
    $('#dialog').load(site_url + '?page_id=443');
}

$('#dialog').dialog({
    width: 800,
    position: 'top',
    modal: true,
    buttons: {
        "Agree": function() {
            agreed = true;
            var val = $('#registerform').attr('action') + '&agreed=1';
            $('#registerform').attr('action', val);
            $(this).dialog("close");
            $('#registerform').trigger('submit');
        },
        "Disagree": function() {
            agreed = false;
            $(this).dialog("close");
        }
    }
});

It works in Firefox — is this something to do with same origin policy? jQuery is being served by Google CDN.
UPDATE
The content being loaded is a WordPress page which also contains includes for cufon-yui.js (served locally). I have tried serving jQuery locally too (i.e not from the Google CDN) and this made no difference.
UPDATE 2
Removing the following script tags from the loaded page stops the error from appearing.

Comment: possible duplicate of [jQuery load() throws "permission denied" error in IE](http://stackoverflow.com/questions/1954740/jquery-load-throws-permission-denied-error-in-ie)
Comment: It is not a same domain issue. Is the html being returned valid html, meaning, no run-away attribute strings(missing trailing quote) and tags are opened and closed properly? also, are you positive that the code only fails when this code is included? There is a bug in 1.6.2 that causes IE to fail when a background image is on the body tag.
Comment: the html body and head will be removed from the resulting html when you use .load() because those tags already exist on the page requesting the html. that wouldn't cause this error.
Comment: The content being loaded in the load call is on the same subdomain as the calling page so I'm not sure if that is it.
Comment: Thanks. It looks like the content being loaded is NOT valid html and does not contain HTML, BODY, HEAD tags etc.Removing the load() call DOES clear the error.
Comment: However, even if I ensure the markup being loaded is valid, I'm still getting the error :(
Comment: Have added a further update which seems to pinpoint cufon-yui as the cause, though not sure why.
Answer: For AJAX requests, www. is seen as a sub-domain and breaks the same-origin policy for the xmlhttprequestobject.  Make sure the domain in your AJAX request matches the domain of the page and your javascript file.


Debian 10, very slow disk i/o, related to software raid

Question: Hey got a server here that's gotten very slow on disk i/o, mdstat mentions something about a check, but I can't find anything about that when googling for it. What is it doing here?
root@tynix /home/vintagestory/trailer/server # cat /proc/mdstat
Personalities : [raid1] [linear] [multipath] [raid0] [raid6] [raid5] [raid4] [raid10]
md2 : active raid1 sda4[0] sdb4[1]
      1073610560 blocks super 1.2 [2/2] [UU]
      [===================>.]  check = 99.4% (1067845568/1073610560) finish=1.6min speed=59370K/sec

md3 : active raid1 sda5[0] sdb5[1]
      1847478528 blocks super 1.2 [2/2] [UU]

md0 : active raid1 sdb2[1] sda2[0]
      8384448 blocks super 1.2 [2/2] [UU]

md1 : active raid1 sda3[0] sdb3[1]
      523968 blocks super 1.2 [2/2] [UU]

unused devices: <none>

Answer: It's checking the software array integrity by sequentially reading all of the sectors on each disk member. That's why the disk i/o is slow - iostat -xd 1 will probably show %busy at 99-100%.
Comment: Thanks for the answer. Is that on a cronjob or whats the trigger for this?