text:
Q: What's an example of a Monad which is an Alternative but not a MonadPlus? In his answer to the question "Distinction between typeclasses MonadPlus, Alternative, and Monoid?", Edward Kmett says that

Moreover, even if Applicative was a superclass of Monad, you'd wind up needing the MonadPlus class anyways, because obeying
empty <*> m = empty

isn't strictly enough to prove that
empty >>= f = empty

So claiming that something is a MonadPlus is stronger than claiming it is Alternative.

It's clear that any applicative functor which is not a monad is automatically an example of an Alternative which is not a MonadPlus, but Edward Kmett's answer implies that there exists a monad which is an Alternative but not a MonadPlus: its empty and <|> would satisfy the Alternative laws,1 but not the MonadPlus laws.2  I can't come up with an example of this by myself; does anybody know of one?

1 I wasn't able to find a canonical reference for a set of Alternative laws, but I lay out what I believe them to be roughly halfway through my answer to the question "Confused by the meaning of the Alternative type class and its relationship to other type classes" (search for the phrase "right distributivity").  The four laws I believe ought to hold are:

*

*Right distributivity (of <*>):  (f <|> g) <*> a = (f <*> a) <|> (g <*> a)

*Right absorption (for <*>):  empty <*> a = empty

*Left distributivity (of fmap):  f <$> (a <|> b) = (f <$> a) <|> (f <$> b)

*Left absorption (for fmap):  f <$> empty = empty
I'd also happily accept being given a more useful set of Alternative laws.
2 I know that there's some ambiguity about what the MonadPlus laws are; I'm happy with an answer that uses left distribution or left catch, although I would weakly prefer the former.

A: The clue to your answer is in the HaskellWiki about MonadPlus you linked to:

Which rules? Martin & Gibbons choose Monoid, Left Zero, and Left Distribution. This makes [] a MonadPlus, but not Maybe or IO.

So according to your favoured choice, Maybe isn't a MonadPlus (although there's an instance, it doesn't satisfy left distribution). Let's prove it satisfies Alternative.
Maybe is an Alternative

*

*Right distributivity (of <*>): (f <|> g) <*> a = (f <*> a) <|> (g <*> a)
Case 1: f=Nothing:
(Nothing <|> g) <*> a =                    (g) <*> a  -- left identity <|>
                      = Nothing         <|> (g <*> a) -- left identity <|>
                      = (Nothing <*> a) <|> (g <*> a) -- left failure <*>

Case 2: a=Nothing:
(f <|> g) <*> Nothing = Nothing                             -- right failure <*>
                      = Nothing <|> Nothing                 -- left identity <|>
                      = (f <*> Nothing) <|> (g <*> Nothing) -- right failure <*>

Case 3: f=Just h, a = Just x
(Just h <|> g) <*> Just x = Just h <*> Just x                      -- left bias <|>
                          = Just (h x)                             -- success <*>
                          = Just (h x) <|> (g <*> Just x)          -- left bias <|>
                          = (Just h <*> Just x) <|> (g <*> Just x) -- success <*>

*

*Right absorption (for <*>): empty <*> a = empty
That's easy, because
Nothing <*> a = Nothing    -- left failure <*>

*

*Left distributivity (of fmap): f <$> (a <|> b) = (f <$> a) <|> (f <$> b)
Case 1: a = Nothing
f <$> (Nothing <|> b) = f <$> b                        -- left identity <|>
                 = Nothing <|> (f <$> b)          -- left identity <|>
                 = (f <$> Nothing) <|> (f <$> b)  -- failure <$>

Case 2: a = Just x
f <$> (Just x <|> b) = f <$> Just x                 -- left bias <|>
                     = Just (f x)                   -- success <$>
                     = Just (f x) <|> (f <$> b)     -- left bias <|>
                     = (f <$> Just x) <|> (f <$> b) -- success <$>

*

*Left absorption (for fmap): f <$> empty = empty
Another easy one:
f <$> Nothing = Nothing   -- failure <$>

Maybe isn't a MonadPlus
Let's prove the assertion that Maybe isn't a MonadPlus: We need to show that mplus a b >>= k = mplus (a >>= k) (b >>= k) doesn't always hold. The trick is, as ever, to use some binding to sneak very different values out:
a = Just False
b = Just True

k True = Just "Made it!"
k False = Nothing

Now
mplus (Just False) (Just True) >>= k = Just False >>= k
                                     = k False
                                     = Nothing

here I've used bind (>>=) to snatch failure (Nothing) from the jaws of victory because Just False looked like success.
mplus (Just False >>= k) (Just True >>= k) = mplus (k False) (k True)
                                           = mplus Nothing (Just "Made it!")
                                           = Just "Made it!"

Here the failure (k False) was calculated early, so got ignored and we "Made it!".
So, mplus a b >>= k = Nothing but mplus (a >>= k) (b >>= k) = Just "Made it!".
You can look at this as me using >>= to break the left-bias of mplus for Maybe.
Validity of my proofs:
Just in case you felt I hadn't done enough tedious deriving, I'll prove the identities I used:
Firstly
Nothing <|> c = c      -- left identity <|>
Just d <|> c = Just d  -- left bias <|>

which come from the instance declaration
instance Alternative Maybe where
    empty = Nothing
    Nothing <|> r = r
    l       <|> _ = l

Secondly
f <$> Nothing = Nothing    -- failure <$>
f <$> Just x = Just (f x)  -- success <$>

which just come from (<$>) = fmap and
instance  Functor Maybe  where
    fmap _ Nothing       = Nothing
    fmap f (Just a)      = Just (f a)

Thirdly, the other three take a bit more work:
Nothing <*> c = Nothing        -- left failure <*>
c <*> Nothing = Nothing        -- right failure <*>
Just f <*> Just x = Just (f x) -- success <*>

Which comes from the definitions
instance Applicative Maybe where
    pure = return
    (<*>) = ap

ap :: (Monad m) => m (a -> b) -> m a -> m b
ap =  liftM2 id

liftM2  :: (Monad m) => (a1 -> a2 -> r) -> m a1 -> m a2 -> m r
liftM2 f m1 m2          = do { x1 <- m1; x2 <- m2; return (f x1 x2) }

instance  Monad Maybe  where
    (Just x) >>= k      = k x
    Nothing  >>= _      = Nothing
    return              = Just

so
mf <*> mx = ap mf mx
          = liftM2 id mf mx
          = do { f <- mf; x <- mx; return (id f x) }
          = do { f <- mf; x <- mx; return (f x) }
          = do { f <- mf; x <- mx; Just (f x) }
          = mf >>= \f ->
            mx >>= \x ->
            Just (f x)

so if mf or mx are Nothing, the result is also Nothing, whereas if mf = Just f and mx = Just x, the result is Just (f x)


text:
Q: How to automatically run apps in iphone? I want to open the YouTube app on my iPhone 7 at 8 am every day and open the first video in the list. How can I accomplish this?

A: Using the example in your question, if you're wanting this to happen automatically without some sort of user intervention, then I doubt this is going to be possible. This is because of security restrictions in place to protect your privacy, data, etc. For example, being able to open the YouTube app would require the iPhone being unlocked, so it's not something that can be set to just happen at 8am every day with or without you.
If you're talking about a way to quickly do this sort of thing with a single tap of a button, then you may want to check out Apple's Workflow app.
It does take a bit of exploring and getting used to, but once you create a workflow it can be launched from the Today Widget or even be exported as a standalone app on your home screen, amongst other options.
I don't think the exact example you give in your question would be possible, at least not yet, but Apple is working very hard on increasing the functionality of both Siri and Workflow to incorporate better integration within and between apps. It's a case of 'watch this space'.
But, even with the current version, I've seen people achieve some pretty cool workflows, so it may be possible to do what you want if you find the right app. By this I mean that there's a Workflow Action Extension that allows workflows to be run from other apps - so if you could find an alarm app that uses this extension I suppose in theory you could use that to trigger your workflow automatically because it'd be an alarm going off.
Finally, if the example you gave in your question is actually all you're wanting to achieve, there are many 3rd party alarm apps that play YouTube videos at the allocated time. You could check to see if any of these will play whatever video is first on the YouTube list.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Box Rectangle Calculation for Arc For common MoveTo(x0, y0), ArcTo(x1, y1, x2, y2, radius) methods;
After a drawing process how can i calculate box rectangle for drawn path with known x0, y0, x1, y1, x2, y2 and radius values ?

A: Are MoveTo and ArcTo here similar to the PostScript commands moveto and arct or arcto?  If so, you will have to calculate where the line between (x0,y0) and (x1, y1) intersects the line between (x1, y2) and (x2, y2), then compute the distance along these lines to the endpoints of the arc, find the center of the arc, then apply the techniques in the post linked to by Unreason.  It is not a simple calculation.  You might want to refer to a linear algebra textbook that deals with this kind of geometry.


text:
Q: Como é possível fazer uma Activity aparecer apenas uma vez para o usuário? Meu plano é o seguinte: No meu projeto eu tenho 2 Activitys; Essas duas activitys são apenas de boas vindas para o usuário, então eu precisaria que ela aparecesse apenas na primeira vez que o usuário iniciasse o aplicativo.
Eu comecei a estudar Shared Preferences, mas os materiais que eu acho por aí são apenas sobre como fazer Login/Senha para o usuário. Não encontrei nenhuma demonstração de como realizar o meu problema. Eu posso usar o Shared Preferences? De qual forma?

A: Não é diferente de sistemas de login como você encontrou ou como sugerido. Supondo que você tenha um BoasVindasActivity e um MainActivity (este último definido como principal no seu arquivo manifest), tem algo assim no MainActivity:
SharedPreferences sharedPrefs = getApplicationContext().getSharedPreferences(NOME_PREFS, Context.MODE_PRIVATE);

if (!sharedPrefs.getBoolean("primeiroAcesso", false)) {
    Intent intent = new Intent(this, BoasVindasActivity.class);
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
    startActivity(intent);
    finish();

    return;
}

Ou seja, se entrou no main e não tem o primeiroAcesso salvo nas preferências do usuário, vai para a tela de boas-vindas. Caso contrário, no seu BoasVindasActivity você salva essa opção em algum momento para abrir a principal:
SharedPreferences.Editor editor = sharedPrefs.edit();
editor.putBoolean("primeiroAcesso", true);
editor.commit();

Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
finish();

A mesma verificação no início você também pode fazer na BoasVindasActivity, para evitar abrir esta tela caso já esteja salvo.


text:
Q: Improving WP_Query for performance when random posts are ordered I have made a new query after I've asked a question about my query_posts code... you guys didn't find that great, so I decided to change that.
I made this:
$page = (get_query_var('paged')) ? get_query_var('paged') : 1;
$rand = new WP_Query("showposts=10&orderby=rand&paged=$page");
while($rand->have_posts()) : $rand->the_post();

My question is: how can I improve this?
Isn't it better to use an array? So the same code, with an array or not?
So like this:
$rand = new WP_Query( array(
    'showposts' => '10',
    'orderby' => rand
) );

Would this make my performance better?
And I read something about adding:
'update_post_meta_cache' => false

To improve the performance if terms are not going to be used. My question: what are terms anyway? Are they trying to say tags and / or categories with this?
Edit:
function random_posts( $query ) {
    if ( $query->is_home() && !$query->is_paged() && $query->is_main_query() ) {
        $query->set( 'orderby', 'rand' );
    }
}

What if I would use this? Do I have to change my WP_Query or do I have to remove it? I don't get what pre_get_posts does actually.

A: The problem with orderby rand is that on most setups the database will load all posts into memory, then randomly order them, and return what you asked for. It's that loading into memory that makes the query super slow/expensive
Also yes, terms are individual categories and tags, where category is a taxonomy, and the 'development' category is a term in that taxonomy.
Finally, your initial code snippet implies you're using a page template or attempting to override what's shown on the page. This is bad as it discards the main query and launches a second query. The cost of the first query still occurs, but it's discarded so it's a waste of time. This is why query_posts is considered harmful, replacing it with a custom WP_Query loop doesn't fix that. Consider using pre_get_posts instead to intercept the main query and change it


text:
Q: Ansible: execute roles with specific tag Facing one issue related to tags in roles. i have specified one tag(create) to run and other tag should skip, but both the tag are executing, can someone explain how to solve this issue.
roles_main.yml
---
- name: roles
  hosts: "{{ host }}"
#  hosts: localhost
  gather_facts: False
  become: yes
  tasks:
  - import_role:
      name: "{{ role_name }}"
    tags: "{{ tag_name }}"

linux/main.yml
---
- name: in file
  import_tasks: in.yml
  tags: create
  delegate_to: localhost

- name: out file
  import_tasks: out.yml
  tags: get
  delegate_to: localhost

ansible-playbook roles_main.yml -e host=localhost -e ritm_ticket=test1 -e role_name=linux -e tag_name=create -v

A: You need add the argument "--tags" (or --skip-tags) to specify the tag you want to run ie:
ansible-playbook roles_main.yml -e host=localhost -e ritm_ticket=test1 -e role_name=linux -e tag_name=create -v --tags=create

For more information:
https://docs.ansible.com/ansible/latest/user_guide/playbooks_tags.html

A: There are 3 special keywords for tags:

*

*tagged: run only tagged tasks.

*untagged: run only untagged tasks.

*all: run all tasks.

By default, Ansible runs as if --tags all had been specified.
You don't pass any tag as argument so ansible runs with --tags all and execute all tasks and import both in.yml and out.yml.
if you want to use Tags feature of ansible you have you pass --tags or --skip-tags arguments.
As your play depend on the value of a variable, an alternative solution can be using Conditionals statements.
You can change your scripts to:
roles_main.yml
---
- name: roles
  hosts: "{{ host }}"
#  hosts: localhost
  gather_facts: False
  become: yes
  tasks:
  - import_role:
      name: "{{ role_name }}"
    when: tag_name == "create"

linux/main.yml
---
- name: in file
  import_tasks: in.yml
  when: tag_name == "create"
  delegate_to: localhost

- name: out file
  import_tasks: out.yml
  when: tag_name == "get"
  delegate_to: localhost

That should work.
Good luck!


text:
Q: Is my interpretation of a quantum field correct? In classical mechanics, the phase space of a single particle is given by the position $x=x(t)$ and its momentum $p=\dot{x}(t)$. More generally, a particle is described by generalized coordinates $q$ and $p = \dot{q}$. In quantum mechanics, this two objects become operators $\hat{x}$ and $\hat{p}$ by means of canonical quantization. Now, observables in QM are represented by operators (as the position and momentum mentioned before) because these are objects that we measure, so operators are closely connected to the act of measuring some physical quantity of the system, even if theoretically one can only calculate mean values.
In QFT, classical fields become operators, or quantum fields. Take a scalar field $\phi(x,t)$ for example. We can interpret $x$ as an index label instead of a coordinate, say $\phi(x,t) = \phi_{x}(t)$. The idea of QFT is to turn each field $\phi_{x}(t)$ into an operator.
Question: Is the interpretation in the second case analogous to the one in the first case (QM)? In other words, $\phi_{x}(t)$ become operators because we are thinking of each $\phi_{x}(t)$ as an observable, i.e. something we can measure at every fixed $t$?

A: The issue with this way of viewing things is that while a quantum field can be an observable, as it happens with the electric and magnetic fields, it needs not be an observable, as it happens with the electron field. Perhaps the best way to view a quantum field is rather as a building block for the interaction hamiltonian (and possibly other observables), which is convenient because of its simple transformation properties under Lorentz transformations.
This point of view is heavily emphasized in Weinberg's "The Quantum Theory of Fields", Volume 1. In the first five chapters Weinberg tackles the problem of how to write down interaction hamiltonians which give rise to a Lorentz covariant ${\cal S}$-matrix which further obey the cluster decomposition principle, which roughly speaking, states that experiments conducted far apart must give uncorrelated results. I shall outline the main ideas, but I highly encourage you to study these chapters.
These two conditions imposes constraints on the possible interaction hamiltonians $V$ and in that case, as is always a good idea, Weinberg follows a "criterium of simplicity". In other words: find the simplest way to construct such $V$ obeying the constraints imposed.
It turns out that:

*

*The Lorentz covariance property of the ${\cal S}$-matrix elements can be most simply implemented by writing down $V$ as the integral of a density. In the interaction picture $$V(t) = \int{\cal H}(t,\mathbf{x})d^3\mathbf{x},\quad U_0(\Lambda,a) {\cal H}(x)U_0^{-1}(\Lambda,a)={\cal H}(\Lambda x+a),\quad  [\mathcal{H}(x),{\cal H}(x')]=0,\quad (x-x')^2>0$$

*The clustering property of the ${\cal S}$-matrix can be most simply implemented by writing down $V$ as a polynomial in the creation and annihilation operators of the asymptotic multiparticle states, with all creation operators to the left of all annihilation operators and with a coefficient containing a total momentum conservation Dirac delta distribution times some sufficiently regular function of the momenta.
Quantum fields then appear as the simplest solution to combine points (1) and (2). To implement (2) you write down ${\cal H}(x)$ as a polynomial in creation and annihilation operators with the regularity conditions obeyed and with $x$-dependent coefficients. Now you need to implement (1). But as it stands it will be quite painful to implement (1) because the creation and annihilation operators do not transform simply under conjugation by Poincaré transformations.
Weinberg then proposes to "repackage" the creation and annihilation operators into objects which transform simply under the Poincaré group. More precisely, instead of working with the bare $a(\mathbf{p},\sigma,n)$ and $a^\dagger(\mathbf{p},\sigma,n)$ you define objects $$\phi_{\ell}^+(x)=\sum_{\sigma n}\int d^3\mathbf{p} u_\ell(\mathbf{p},\sigma,n;x)a(\mathbf{p},\sigma,n),\quad \phi_{\ell}^-(x)=\sum_{\sigma n}\int d^3\mathbf{p} v_\ell(\mathbf{p},\sigma,n;x)a^\dagger(\mathbf{p},\sigma,n),$$
where we demand that these objects transform simply under the Poincaré group: $$U_0(\Lambda,a)\phi_\ell^\pm(x)U_0^{-1}(\Lambda,a)=\sum_{\bar \ell}D_{\bar \ell \ell}(\Lambda^{-1})\phi_{\bar \ell}(\Lambda x+a),$$
where $D_{\ell \bar{\ell}}(\Lambda)$ are finite-dimensional representations of the Lorentz group.
To give one very basic intuition: what is the easiest way to construct scalars? Obviously by contracting tensors, like $p_\mu p^\mu$, $J_{\mu\nu} J^{\mu\nu}$, etc. Take a time to convince yourself that this is the basic idea here. The tensors like $p^\mu$ and $J^{\mu\nu}$ transform in a simple way, as will transform the $\phi_\ell$, and we know how to couple then to form scalars, like the $\phi_\ell$.
This is an outline to show you that quantum fields appear as the building blocks for your interaction hamiltonian (and possibly other observables). Therefore while they can be seem as observable, teaching yourself from the start that they are observables can be misleading.

A: That is completely correct. For a real scalar field $\phi$, you can think of the "states" in quantum field theory as being "wave functionals." At a fixed time $t$, they take in a field configuration $\phi(\vec{x})$ and output a complex number. In other words, if $\phi(\vec x)$ is a classical field configuration,
$$
\phi : \mathbb{R}^3 \to \mathbb{R},
$$
that is
$$
\phi \in C^\infty(\mathbb{R}^3)
$$
then the quantum state is a wave functional $\Psi[\phi]$
$$
\Psi :  C^\infty(\mathbb{R}^3) \to \mathbb{C}.
$$
Then, $|\Psi[\phi]|^2$ has the intepretation of being the probability density of the field "having the values $\phi$", much like how in regular quantum mechanics, $|\psi(q)|^2$ is the probability density that the particle is located at position $q$. The operators $\hat \phi(\vec x)$ and $\hat \pi(\vec x)$ now have the definitions
$$
\big( \hat \phi(\vec x) \Psi \big) [\phi] = \phi(\vec x) \Psi[\phi]
$$
and
$$
\big( \hat \pi(\vec x) \Psi \big) [\phi] = \frac{\hbar}{i} \frac{\delta}{\delta \phi(\vec x)} \Psi[\phi]
$$
where $\frac{\delta}{\delta \phi(\vec x)}$ is the functional derivative of the functional $\Psi$ with respect to the variable $\phi(\vec x)$. This is just like the definition of $\hat q$ and $\hat p$ in quantum mechanics.
If we come up with some Hamiltonian $\hat H$, then this wave functional of field configurations on a time slice will evolve in time via the Schrodinger equation.


text:
Q: Have uniformly set sized divs move to available space above I have 4 block divs of uniform sizes 1x1, 2x1, 1x2, 2x2. I need these to fill the space on the page from top to bottom. So far I have them just float left and gets me about 70% there, but I need so if theres a 1x1 space for the next 1x1 size div to move to that space, if theres a 3x1 space to move a 2x1 div and a 1x1 div etc.
Current state: https://jsfiddle.net/grk7bdub/5/

.box {
  float: left;
  /*display: inline-block;*/
  box-sizing: border-box;
  -webkit-box-sizing: border-box;
  -moz-box-sizing: border-box;
  border: solid;
  border-color: white;
  padding: 5px;
}

.box1x1 {
  height: 200px;
  width: 200px;
  color: white;
  background-color: red;
}

.box2x1 {
  height: 200px;
  width: 400px;
  color: white;
  background-color: blue;
}

.box2x2 {
  height: 400px;
  width: 400px;
  color: white;
  background-color: green;
}

.box1x2 {
  height: 400px;
  width: 200px;
  color: white;
  background-color: orange;
}

hello

hello

hello

sup

hello

hello

hello

hi

sup

Nothing fancy. How would I have it so the DIVs can move freely to fill space if it exists, the DIVs don't need to end up in a strict final order but if a general starting order could be specified that'd be great.


text:
Q: Is there a way to upload image as binary data on pre-signed s3 PUT url using Axios or XHR 1) Code to generate s3 URL
      const file = req.files ? req.files.filename || null : null
      const extension = path.extname(file.name)
      const client = new S3Client()

      const params = {
        Bucket: S3_BUCKET, // env variable
        Key: `tmp/photos/image_file.png`,
        ContentDisposition: 'inline',
        ContentType: file.mimetype,
        Body: file.data
      }

      const command = new PutObjectCommand(params)
      const presignedS3Url = await getSignedUrl(client, command, { expiresIn: 3600 })

I am able to upload image with this CURL request
curl --location --request PUT $presignedS3Url \
--header 'Content-Disposition: inline' \
--header 'Content-Type: image/png' \
--data-binary '@/Users/name/Downloads/image-file.png'

Not able to upload using axios
      const imageFile = fs.readFile('/Users/filepath/image-file.png')
      const bufferString = Buffer.from(imageFile, 'base64')

      await axios.put(presignedS3Url, {
        data: bufferString
      }, {
        headers: {
          'Content-Type': file.mimetype,
          'Content-Disposition': 'inline'
        }
      })

How to use Axios or XHR to upload image?

A: Hope this helps
  const fs = require('fs/promises');
  const imageFile = fs.readFile('/Users/filepath/image-file.png')

  await axios.put(presignedS3Url, imageFile, {
    headers: {
      'Content-Type': file.mimetype
    }
  })

A: While generating presigned URL use this
    const params = {
        Bucket: S3_BUCKET, // env variable
        Key: `tmp/photos/image_file.png`
      }

To upload use XMLHttpRequest
    const s3Url = uploadedImageResponse?.item?.url || ''
    const xhr = new XMLHttpRequest()
    xhr.withCredentials = false

    xhr.upload.onprogress = event => {
      if (event.lengthComputable) {
        const percentComplete = (event.loaded / event.total) * 100
        progressHandler(percentComplete, fileName)
      }
    }
    xhr.onreadystatechange = async function () {
      if (xhr.readyState === 4) {
        if (xhr.status === 200) {
          await successHandler(uploadedImageResponse, fileName)
        } else {
          errorHandler('Error uploading file', fileName)
        }
      }
    }
    xhr.open('PUT', s3Url)
    xhr.send(file.file)


text:
Q: Matrix with eigenvalue pairs $\pm\lambda$ Consider a real differentiable function $f:\mathbb{R}\to\mathbb{R}^N$ and define a matrix $A_{ij}=\mathbb{E}[\frac{\partial}{\partial x}[f_i(x) f_j(x)]]$ where the expectation is with respect to some measure on $f$'s domain. As it is symmetric all its eigenvalues are real, and I would like to derive conditions on $f$ so that if $\lambda$ is an eigenvalue of $A$ then $-\lambda$ is also an eigenvalue. That is, I ask:

*

*Q1: When do the eigenvalues of $A$ can be paired as $\pm\lambda$?

*Q2: If there a nessesary and sufficient condition on $f$ so that this will be the case?

Thanks!
EDITED: changed $A$'s definition to include expectation over $x$; otherwise the second question is meaningless.

A: Assme that your measure is in the form $d\mu=\phi(x)dx$, with $d\mu(\mathbb{R})=1$. Then $A_{i,j}=\int(f_if_j)'\phi(x)dx=-\int f_if_j\phi '(x)dx$ if $\phi$ tends quickly to $0$ at infinity and if $\phi '$ exists. A necessary condition is $trace(A)=0$, that is $\int (\sum_if_i^2)\phi '(x)dx=0$. This condition is sufficient when $n=2$. If, for instance, $\phi(x)=e^{-|x|}$, then the condition is $\int_0^{\infty}\sum_i(f_i^2(x)-f_i^2(-x))e^{-x}dx=0$. Yet, the general case seems to me very difficult especially if $d\mu$ is not given.


text:
Q: Img load and nested divs I'm trying to implement a newsfeed. When the page first loads 20 news items with friend pic data etc. load and all is well.
Then when the user updates their status, I want to show this and any new friend status in the newsfeed. This is the structure I want to create dynamically
...

John Smith

And I've been able to create the img part with this jQuery:
function showStatus(data){
    var jsondata = $.parseJSON(data);
    $('#doNews').empty();
    $('#doNews').append($('
', {"class": "newsList", id: "theNews"}));
    $.each(jsondata, function(i, item){
        $('')
            .load(function(){
        $(this)
            .appendTo($('#theNews'))
            .wrap($('
', {"class": "newsItem"}))
            .wrap('
');
      });
});
//  $('#theNews li').each(function(){
//      $(this).append($('
', {"class": "st-col1"}));
//  });

$("#statustext").val('');
}

However, the commented out part doesn't seem to work (b/C the page has already loaded?) And if I put it in the load function, the
 gets attached to the img which is not what I want.

A: You create the lis in the image load callback so then add the div to the li there.
$('')
    .load(function(){
        $(this)
            .appendTo($('#theNews'))
            .wrap($('
', {"class": "newsItem"}))
            .wrap('
')
            .closest('li')
            .append($('
', {"class": "st-col1"}));
      });
});

A: Try
function showStatus(data){
    var jsondata = $.parseJSON(data);
    $('#doNews').empty();
    $('#doNews').append($('
', {"class": "newsList", id: "theNews"}));
    $.each(jsondata, function(i, item){
        $('')
        .load(function(){
            $('
', {"class": "newsItem"})
            .append($('
', {"class": "st-col2"}).append(this))
            .append($('
', {"class": "st-col1"}))
            .appendTo('#theNews');
        });
    });
    //  $('#theNews li').each(function(){
    //      $(this).append($('
', {"class": "st-col1"}));
    //  });

    $("#statustext").val('');
}


text:
Q: Can I take derivative of a function that represents a piece of music? Can I take the derivative of a function that represents a piece of music? The music is given in .mp3, .midi or whatever comes in handy.

A: In Mathematica, you can read in .wav files using Import. Since the data is then a discrete data sequence, you can't take a real calculus-style derivative, but you can take the derivative numerically, for instance, using functions like Differences and DerivativeFilter (thanks Jens). In fact, the derivative operation is a kind of high-pass filter, which will augment the noise and remove the low frequencies. You can listen to the changed sound using SampledSoundFunction or by saving the result out to a .wav file using Export. There are plenty of other ways you can manipulate the sound: LowpassFilter and HighpassFilter come to mind.


text:
Q: Excel - Sorting a list with multiple rows per entry Is there any way to sort a list in excel if the list is not 1 row per entry. The entries could be 2+ rows
Unsorted:
      A       B       C

1   Entry3
2            Data1  Data2
3            Data3  Data4
4   Entry1
5            Data5  Data6
6   Entry2
7            Data7  Data8

Sorted:
      A       B       C

1   Entry1
2            Data5  Data6
3   Entry2
4            Data7  Data8
5   Entry3
6            Data1  Data2
7            Data3  Data4

A: You need a magic trick. ;)
For the Pledge, you first fill in the areas underneath each Entry with the duplicate of the header Entry. Basically, A1:A2 should have Entry1, A3:A4 should have Entry2, and A5:A7 should have Entry3.
The following subroutine does the above.
Sub Pledge()
    Dim LRow As Long: LRow = Range("B" & Rows.Count).End(xlUp).Row
    Dim CurrentName As String
    CurrentName = ""
    For Iter = 1 To LRow
        If Range("A" & Iter).Value <> "" Then
            If Range("A" & Iter).Value <> CurrentName Then
                CurrentName = Range("A" & Iter).Value
            End If
        Else
            Range("A" & Iter).Value = CurrentName
        End If
    Next Iter
End Sub

Screenshot:

For the Turn, we just sort the ranges according to column A. This is fairly simple.
Sub Turn()
    Range("A:C").Sort Range("A1"), xlAscending
End Sub

Screenshot:

But it's never over, right? You don't clap yet, not until it's brought back. Here's the Prestige.
Sub Prestige()
    Dim LRow As Long: LRow = Range("B" & Rows.Count).End(xlUp).Row
    Dim CurrentName As String
    CurrentName = ""
    For Iter = 1 To LRow
        If Range("A" & Iter).Value <> "" Then
            If Range("A" & Iter).Value = CurrentName Then
                Range("A" & Iter).Value = ""
            Else
                CurrentName = Range("A" & Iter).Value
            End If
        End If
    Next Iter
End Sub

And there you go. Paste the above in a module and call one by one, or modify them yourself inside one subroutine. This part, I leave to you. :)
Sub GrandIllusion()
    Pledge
    Turn
    Prestige
End Sub


text:
Q: I Could not host my Laravel App on server? i hope you can help me with that stuff
so i completed a client's laravel app and tried to host it on the client's server but it was not working , it was showing the error

End of script output before headers: index.php

i hope you help me solve the problem
Server is Runing on CentosLinux Os:
Apache v : 2.4
php v : 7.2
Mysql v :10.1

My Application is Built on : Laravel Framework v7.2

A: Laravel 7 needs php >= 7.2.5
Take a look to the server requirements in Laravel 7 docs


text:
Q: How to convert image pixel to latitude and longitude We are developing an android application for showing an image with geo referened with .jgw and .prj file as below. we want to identify the geo location coordinate of image coordinate(in pixel) that user touched on the image. How we can use image cordinate to find ts relative latitude and longitude using java in android.
We tried proj4 java library for android but it seems incorrect when we find the distance of two point and we couldn't trace where is the issue.
Below are our .jgw and .prj file
JGW File
0.00000180562999999
0
0
-0.00000180562999999
76.882389 (dummy location due to NDA)
8.572607 (dummy location due to NDA)
PRJ File
GEOGCS["GCS_WGS_1984",DATUM["D_WGS84",SPHEROID["WGS84",6378137,298.257223563]],PRIMEM["Greenwich",0],UNIT["Degree",0.017453292519943295]]

A: You have world files (.jgw) and projection definition files (.prj).
World file values:
Line 1: A: pixel size in the x-direction in map units/pixel
Line 2: D: rotation about y-axis
Line 3: B: rotation about x-axis
Line 4: E: pixel size in the y-direction in map units, almost always negative
Line 5: C: x-coordinate of the center of the upper left pixel
Line 6: F: y-coordinate of the center of the upper left pixel

You can convert pixel coordinates to map coordinates (longitude, latitude assuming the projection is always WGS84 / EPSG 4326) using some simple maths:
mx = C + px * A + py * B
my = F + px * D + py * E

Where mx, my = map coordinates and px, py = pixel coordinates.
In your case, as the rotation terms are zero, the equation becomes:
mx = C + px * A
my = F + py * E

Which means x or y coordinate of top left corner + image coordinate * pixel size.

A: You can use GDAL, for which bindings are available in a variety of languages including Java.  The tool gdaltransform will do exactly what you want.    You can also use gdallocationinfo. This will give you both the pixel value and its coordinates.


text:
Q: Why doesn't my cart collection increment as expected? I am trying to create a button where if the user clicks the "add to cart" button on the site, the counter at the button for "items in cart:" goes up. Right now it is not doing that. I am new to Vue therefore any help would be appreciated :)
Here is my app.components.js file
const Library = Vue.component('Library', {
    // this function is run AFTER the props have been passed in
    data() {
        // without chaining
        // let libraryCollection = new LibraryCollection();
        // libraryCollection.addItem(new Book('Interaction Design', 200));
        // libraryCollection.addItem(new Movie('Paw Patrol!', 78));
        // libraryCollection.addItem(new Movie('Harriet', 122));
        // libraryCollection.addItem(new Book('Brown Bear, Brown Bear', 0));

        return {
            //library: libraryCollection
            library: new LibraryCollection()
                .addItem(new Book('Interaction Design', 200))
                .addItem(new Movie('Paw Patrol!', 78))
                .addItem(new Movie('Harriet', 122))
                .addItem(new Book('Brown Bear, Brown Bear', 0))
        }
    },

    template: `

        <library-item v-for="item in library" :item="item"></library-item>

Checked out: {{library.checkedOutItems().length}}

    `
})

const LibraryItemComponent = Vue.component('LibraryItem', {
    // values/bindings passed to this component
    props: {
        item: Object
    },

    computed: {
      typeOfItem(){
          return this.item.constructor.name;
      }
    },

    // the view
    template: `

              <component :is="typeOfItem" :item="item"></component>

              <button @click="item.checkOut()" class="btn btn-secondary">Check Out</button>
              <button @click="item.checkIn()" class="btn btn-secondary">Check In</button>
              <button @click="EventBus.$emit('addItem', item)" class="btn btn-secondary">Add to Cart</button>
              <button @click="item.favorite()" class="btn btn-secondary">{{item.isFavorite ? 'Unfavorite' : 'Favorite'}}</button>

        `,
});

const BookComponent = Vue.component('Book', {
    props: {
        item: Book
    },

    template: `

{{item.title}}

Pages: {{item.pages}}

        `,
});

const MovieComponent = Vue.component('Movie', {
    props: {
        item: Movie
    },

    template: `

{{item.title}}

Running Time: {{item.runningTime}}

        `,
});

const Cart = Vue.component('Cart', {
    // this function is run AFTER the props have been passed in
    data() {
        // without chaining
        // let libraryCollection = new LibraryCollection();
        // libraryCollection.addItem(new Book('Interaction Design', 200));
        // libraryCollection.addItem(new Movie('Paw Patrol!', 78));
        // libraryCollection.addItem(new Movie('Harriet', 122));
        // libraryCollection.addItem(new Book('Brown Bear, Brown Bear', 0));

        return {
            //library: libraryCollection
            cart: new CartCollection()
        }
    },

    template: `

        <cart-item v-for="item in cart" :item="item"></cart-item>

Items in cart: {{cart.length}}

    `
})

This is my app.models.js file
function LibraryCollection(){
    this.__proto__ = []; // as of ES6 (2015)

    this.addItem = function(item){
        this.push(new LibraryItem(item));

        // allows us to chain methods
        return this;
    }

    this.checkedOutItems = function(){
        return this.filter(function(item){
            return !item.isAvailable();
        })
    }
}
// current and pre-ES6
LibraryCollection.prototype = [];
LibraryCollection.prototype.constructor = LibraryCollection;

// let divs = $('div');
// divs.hide().show().html('asdf');
function LibraryItem(media){
    // list of possible values (enum)
    const STATUSES = {CHECKED_OUT: 'out', CHECKED_IN: 'in', LOST: 'lost'}

    // decorating/adding functionality to an existing object
    media.status = STATUSES.CHECKED_IN;
    media.isFavorite = false;

    // methods
    media.checkIn = function(){
        this.status = STATUSES.CHECKED_IN;
    }

    media.checkOut = function(){
        this.status = STATUSES.CHECKED_OUT;
    }

    media.isAvailable = function(){
        return this.status === STATUSES.CHECKED_IN;
    }

    media.favorite = function() {
        this.isFavorite = !this.isFavorite;
        return this.favorite;
    }

    return media;
}
function CartCollection(){
    this.__proto__ = []; // as of ES6 (2015)

    this.addItem = function(item){
        this.push(item);
        console.log(this);

        // allows us to chain methods
        return this;
    }
    this.removeItem = function(libraryItem){
        let index = this.indexOf(libraryItem);
        this.splice(index,1);
    }
}
// current and pre-ES6
CartCollection.prototype = [];
CartCollection.prototype.constructor = CartCollection;


text:
Q: Enlazar Consultas SQL Server y MySQL Tengo que relacionar datos de una DB SQL Server y otra MySQL. Me gustaría poder hacer consultas varias directamente a las bases de datos sin tener que hacer exportaciones/importaciones de datos.
Con Access puedo  hacerlo, pero es lento, y el editor es tremendamente malo. Además, si es posible, me gustaría poder hacerlo en linux.
Estoy probando el DBeaver, pero solamente puedo realizar las consultas por separado (o no encuentro cómo enlazarlas).
Algo así es lo que quisiera:
select * from DBSQLSERVER.dbo.tabla_1 t1
inner join DBMYSQL.tabla_2 t2 on t1.id=t2.id;


text:
Q: order from collectionType in symfony2 I'm new to symfony2 and I'm just trying to figure how the framework functions.
I have the following relationship:
1 palette(Palette entity) contains exactly 256 plumes(LogicalPlume entity)
( which refers to a color(PhysicalPlume entity) ).
PS: the ID of the row in db is set as auto-increment,
but the index of logicalPlume and physicalPlume is set manually (0->255).

I set the relationship in my entities as oneToMany and ManyToOne.
I created the PaletteType as having a CollectionType:
$builder->add('logicalPlumes', 'collection', array(
  'type' => new LogicalPlumeType($profile_id),
  'label' => 'plumes'
));

and the LogicalPlumeType
$profile_id = $this->profile_id;

$builder->add('physicalPlume', 'entity', array(
  'class' => 'DessinPlumeBundle:PhysicalPlume',
  'query_builder' => function(EntityRepository $er)  use ($profile_id) {
     return $er->createQueryBuilder('pp')
                            ->where("pp.profile = :profile")
                          ->orderBy('pp.index', 'ASC')
                     ->setParameter('profile', $profile_id);
   }
));

Eveything is great, the palette object is persisted correctly in the database (except that the objects are not saved in their proper indexes).
Firebug tells me the select beside label '0' has ID of "palette_0".
but I think this actually points to another index in the database, doesnt it ?!
So, when I read the object, I want the plumes returned by INDEX so that I can display them correctly.
For example:
I saved
logicalPlume1 = 10;
logicalPlume2 = 0;   with '0' being the default value.
logicalPlume3 = 9;
logicalPlume4 = 0;
logicalPlume5 = 5;

when i read it back, it shows:
logicalPlume1 = 10;
logicalPlume2 = 5;
logicalPlume3 = 9;
logicalPlume4 = 0;
logicalPlume5 = 0;
pushing all the '0' values to the bottom

I think I should use that CollectionType here, but I have an order to preserve.
How do I do that ?
Do I need to use another type maybe??
thank you.

A: Without seeing your controller code, I would say your cascade persist is not processed in the same order as the non-default values you choose for your form.
Try persisting each plume via foreach or map and see what the indices are.
Please post controller code if you still need help with this.


text:
Q: Create member with description in MDX This is a pretty straight forward question that may or may not be possible but, when you create a measure in a SSAS 2005 cube, there is a description property which can be set, which we've been using in the client application that consumes the cube.
Is it possible to set this description when you create a calculated member through MDX? i.e. something like (although it doesn't work as I get an error saying the syntax near DESCRIPTION is incorrect)
CREATE MEMBER CURRENTCUBE.[Measures].[CalculatedMember] AS
NULL,
FORMAT_STRING = "Percent",
VISIBLE = 1,
DESCRIPTION = "My favourite calcuated measure";

A: On the Calculations Tab - click on the 'Calculations Properties' button.  This is where you can tell SSAS which folder to put your calculations in.  There is a Description column - fill that in, and Bob is your uncle.

A: http://msdn.microsoft.com/en-us/library/ms144787.aspx
The property you are looking for is CAPTION:
CREATE MEMBER CURRENTCUBE.MEASURES.[Test Measure]
 AS 1,
CAPTION = 'My testing measure';

A: As in SSAS 2005 there isn't the CAPTION property, if you must have a caption I could suggest a workaround to try:
Create the member you want, name it as you want and give it the description you want. It doesn't matter what you base it on, but get it as close to the actual desired output as you can.
So, if you create [Measures].[Test] in the cube designer, with "Test Measure" as the description, then you can use SCOPE to overwrite the cell contents with your own calculation at evaluation time:
SCOPE([Measures].[Test]);
 THIS = [Measures].[A] + [Measures].[B];
END SCOPE;

So copy and paste the above into your calculations tab in SSAS designer, note that you will have to go into script view as opposed to form view.
Hopefully you will now have a measure that performs as you want, with the caption that you want. Figuring out the non-empty and getting that all correct may be another story...


text:
Q: Where is MYSQL installed on Mac? I've always used MAMP or XAMPP to install MYSQL so it's been fairly straightforward. The only most I've had to do is create a symbolic link.
I'm now starting to learn Django and I would like to start a new. I uninstalled XAMPP and downloaded MYSQL from dev.mysql.com (64 bit) but I have no idea where it installed it to! I went to the command line and typed "mysql" and received the message "command not found".
Where is MYSQL installed on Mac OSX Lion?
Thanks.

A: Have you tried opening Terminal and typing:

locate mysql

A:
The installation layout is similar to that of a tar file binary
  distribution; all MySQL binaries are located in the directory
  /usr/local/mysql/bin. The MySQL socket file is created as
  /tmp/mysql.sock by default. See Section 2.7, "Installation Layouts".

From: http://dev.mysql.com/doc/refman/5.0/en/macosx-installation.html
It's probably not added to your $PATH, thus why the commands aren't visible in the terminal. Try typing echo $PATH on your terminal to see if /usr/local/mysql/bin is included in the path.
Additionally, on the terminal, you can type which mysql. If that returns nothing your environment is not finding your MySQL binary.


text:
Q: mysql right join as discussed in the example is not giving right result i have a table A with a as a column and table B  as a , name, address
table A has 1,1,2 as input
table B has (1, hello , india), (1,hi, nowhere),( 2,hukka,china) as values
SELECT * FROM a
right join b
on a.a=b.a
and b.a=1
and a.a is not null

its giving me
  a     a   name    address
  1     1   hello   india
  1     1   hi  nowhere
NULL    2   hukka   china

any clues why its still showing me null value for a.a

A: I think you need to use a WHERE clause
SELECT * FROM a
RIGHT JOIN b
ON a.a=b.a
WHERE b.a=1
AND a.a IS NOT NULL

A: Try this
SELECT a.a, b.a, b.name, b.address
FROM a
INNER JOIN b ON a.a = b.a
WHERE b.a = 1 AND a.a IS NOT NULL


text:
Q: Rodar trechos de código em paralelo Olá, eu queria saber como executar uma thread em seguida da outra por um determinado tempo, por exemplo:
Thread x = new Thread(() -> {
// qualquer código, pode ter até um while(true)...
});
Thread x2 = new Thread(() -> {
// qualquer código, pode ter até um while(true)...
});

Tenho uma thread x que deverá rodar por 3s, após esse tempo ela deverá pausar e em seguida a x2 deverá iniciar, mas não pode conter nenhum código adicional dentro do runnable dela.
Agradeço desde já.

A: Caro colega,
O melhor nesse caso é criar uma uma classe que herda Thread e inplementar o método run(){}. Esse método você pode colocar um synchronized no método, dessa forma, quando você pode chamar o método start e para pausar só chamar o método sleep(tempo), passando no parametro o tempo que você precisa que ele aguarde.


text:
Q: why does rpm reinstall executes %postun after %post section I have a sample rpm spec file like
Name:           helloworld
Version:        2.0
Release:        2%{?dist}
Summary:        Simple Hello World rpm
License:        Internal
Source0:        helloworld-src.tar.bz2

%description

%prep
%setup -c -q -T -D -a 0

%build

%install
echo "Install command ..."

%post
echo "post command..."

%postun
echo "postun command..."

%files
%doc
%changelog

When I execute rpm -i helloworld.rpm, the output is
post command...

But when I execute rpm --reinstall helloworld, the output is
post command...
postun command...

Whys is this so? I was expecting postun to be called before post would be called.
Where can I find which scriplets will be called during rpm --reinstall ?

A: It's because reinstall is like an upgrade; the new one gets installed and the old one is uninstalled, triggering the %postun. The full sequence, from Fedora's excellent packaging guidelines, shows you are hitting steps 4 and 11:

*

*%pretrans of new package

*%pre of new package

*(package install)

*%post of new package

*%triggerin of other packages (set off by installing new package)

*%triggerin of new package (if any are true)

*%triggerun of old package (if it's set off by uninstalling the old package)

*%triggerun of other packages (set off by uninstalling old package)

*%preun of old package

*(removal of old package)

*%postun of old package

*%triggerpostun of old package (if it's set off by uninstalling the old package)

*%triggerpostun of other packages (if they're set off by uninstalling the old package)

*%posttrans of new package


text:
Q: Conditional unit checks/tests Suppose that I have this dataset that shows how many items (i.e., Item A, B, and C) are sold in three stores (i.e., Store 1, 2, and 3) between year 2020 to 2021. The dataset looks similar to the table below:
Initial_Data = data.frame(Year= c(2020, 2020, 2020, 2021, 2021, 2021, 2020, 2020, 2020, 2021, 2021, 2021,2020, 2020, 2020, 2021, 2021, 2021),
                     Stores = c('Store 1', 'Store 1', 'Store 1', 'Store 1', 'Store 1', 'Store 1', 'Store 2', 'Store 2', 'Store 2', 'Store 2', 'Store 2', 'Store 2', 'Store 3', 'Store 3', 'Store 3', 'Store 3', 'Store 3', 'Store 3'),
                     Items = c('A', 'B', 'C', 'A', 'B', 'C', 'A', 'B', 'C', 'A', 'B', 'C', 'A', 'B', 'C', 'A', 'B', 'C'),
                     `Units Sold` = c(67, 32, 11, 0, 0, 0, 54, 0, 9, 71, 36, 12, 0, 0, 0, 45, 28, 7)
                     )

Let's say that there has been a glitch in the system that caused some stores to report 0 units sold for ALL items (for example, store 1 in 2021 and store 2 in 2020 reported 0 units sold for all three items). So I want to "flag/identify" these stores to investigate them further. Note that I am only interested in stores that reported zero units sold for ALL THREE ITEMS. For example, store 2 in 2020 reports 0 units sold for item B, but I do not care about that.
So the resulting table should look something like:
Final_Data = data.frame(Year= c(2020, 2020, 2020, 2021, 2021, 2021, 2020, 2020, 2020, 2021, 2021, 2021,2020, 2020, 2020, 2021, 2021, 2021),
                     Stores = c('Store 1', 'Store 1', 'Store 1', 'Store 1', 'Store 1', 'Store 1', 'Store 2', 'Store 2', 'Store 2', 'Store 2', 'Store 2', 'Store 2', 'Store 3', 'Store 3', 'Store 3', 'Store 3', 'Store 3', 'Store 3'),
                     Items = c('A', 'B', 'C', 'A', 'B', 'C', 'A', 'B', 'C', 'A', 'B', 'C', 'A', 'B', 'C', 'A', 'B', 'C'),
                     `Units Sold` = c(67, 32, 11, 0, 0, 0, 54, 0, 9, 71, 36, 12, 0, 0, 0, 45, 28, 7),
                     Check = c('Fine', 'Fine', 'Fine', 'Check', 'Check', 'Check', 'Fine', 'Fine', 'Fine', 'Fine', 'Fine', 'Fine', 'Check', 'Check', 'Check', 'Fine', 'Fine', 'Fine')
                     )

The actual dataset that I'm using represents dozens of stores with more than 10 items and covers multiple years. So it's impossible to check them manually like the example above. That being said, it would be great if your solution could be as "flexible" or "general" as possible. That is, it shouldn't be too "rigid" that it cannot be modified at all and can only be used to address the table above.
Thank you!

A: Seems like you just need you need to group the df by the year and store and then run some logic. Try:
library(dplyr)
Initial_Data |>
  group_by(Stores, Year) |>
  mutate(Check = if(all(Units.Sold == 0)) "Check" else "Fine")


text:
Q: how to multiply two unequal matrices in matlab? c1=[1 2 3 4 5 6];
c2=[4 5 6 7 8 9 10];
c3=[3 5 7 11 12 13];

o1=intersect(c1,union(c2,c3));
o2=intersect(c2,union(c1,c3));
o3=intersect(c3,union(c1,c2));

p=(c1.*c2).*c3;

ND21=1;
ND22=2;
ND23=3;

CIa1=1/(ND21);
CIa2=1/(ND22);
CIa3=1/(ND23);

CIp1=(c1-o1)/p;
CIp2=(c2-o2)/p;
CIp3=(c3-o3)/p;

Eavg1=(Ecur1+Ecur2+Ecur3)/ND21;
Eavg2=(Ecur1+Ecur2+Ecur3)/ND22;
Eavg3=(Ecur1+Ecur2+Ecur3)/ND23;

i want multiply c1 and c2 which is an unequal matrix. I'm getting the following error:
??? Error using ==> times
Matrix dimensions must agree.

Error in ==> batwsn at 13

p=(c1.*c2).*c3;

A: The rule for matrix multiplication is that two matrices can be multiplied only when the number of columns in the first equals the number of rows in the second.  This is a mathematical principle so basically you should not expect MatLab to do it.
The closest you can come is to pad one of the matrices with zeros to get the dimensions to match the rules - but you may not get the results you are expecting.


text:
Q: How to Mock a Service with Moq and Nunit in mvc application - prevent nulls I was under the impression that mocking is faking data calls thus nothing is real.  So when I trying to create my own Unit Test that are very similar to what other developers on my team are doing, I am thinking that this is not correct to be newing up the service.
    [Test]
    public void TemplateService_UpdateTemplate_ContentNameNotUnique_ServiceReturnsError()
    {
        Template Template = new Template()
        {
            TemplateId = 123,
        };

        // Arrange.
        TemplateUpdateRequest request = new TemplateUpdateRequest()
        {
            ExistingTemplate = Template
        };

        var templateRepo = new Mock<ITemplateRepository>();
        var uproduceRepo = new Mock<IUProduceRepository>();

            templateRepo.Setup(p => p.IsUniqueTemplateItemName(215, 456, "Content", It.IsAny<string>())).Returns(false);
            templateRepo.Setup(p => p.UpdateTemplate(request)).Returns(1);

            // Act.
            TemplateService svc = new TemplateService(templateRepo.Object, uproduceRepo.Object);

            TemplateResponse response = svc.UpdateTemplate(request);

            // Assert.
            Assert.IsNotNull(response);
            Assert.IsNotNull(response.data);
            Assert.IsNull(response.Error);

    }

So my issue is with this code:
TemplateService svc = new TemplateService(templateRepo.Object, uproduceRepo.Object);

Should the TemplateService really be newed up?  What "if" the Service ended up hitting a database and/or file system?   Then it becomes an integration test, and no longer a unit test, right?
TemplateResponse response = svc.UpdateTemplate(request);

Also, how do I really control whether this is truly going to pass or not?  It is relying on a service call that I didn't write,  so what if there is a bug, or encounters a problem,  or return NULL, which is exactly what I do not want!  ?

A: If you're testing TemplateService, then YES it should be newed up. How else can you test your actual implementation? The point here is to only test TemplateService and not it's dependencies (unless it's an integrations test).
So if you got a repo like IUProduceRepository it should be mocked, simply to ensure that you're not writing to some database, and to make sure that you can create a specific scenario.
Your goal is to test that TemplateService is doing the right thing, based on a specific scenario. So let's say that your IUProduceRepository is throwing an error that your TemplateServiceshould handle. Then you should mock that error in your IUProduceRepository and test your implementation of TemplateService and make sure that it handles it as expected.
So to answer your questions...

Should the TemplateService really be newed up? What "if" the Service
ended up hitting a database and/or file system? Then it becomes an
integration test, and no longer a unit test, right?

Yes, I would say that it would be an integrations test. You mock things to make sure that the service isn't writing to DB.

Also, how do I really control whether this is truly going to pass or
not? It is relying on a service call that I didn't write, so what if
there is a bug, or encounters a problem, or return NULL, which is
exactly what I do not want! ?

Your goal is to make sure that the class you test is doing what you expect in a specific scenario. Let's say that your repo is throwing an exception for some reason, then you might want to test that your service can handle that (or at least test that it's doing what's expected).
public class TemplateService : ITemplateService
{

    ITemplateRepository _templateRepo;
    IUProduceRepository _produceRepo

    public TemplateService(ITemplateRepository templateRepo, IUProduceRepository produceRepo)
    {
        _templateRepo = templateRepo;
        _produceRepo = produceRepo;
    }

    public TemplateResponse UpdateTemplate(Template template)
    {
        try
        {
            var result = _templateRepo.Update(template);
            return result;
        }
        catch(Exception ex)
        {
            // If something went wrong. Always return null. (or whatever)
            return null;
        }
    }
}

[Test]
public void TemplateService_UpdateTemplate_ShouldReturnNullOnError()
{
    Template template = new Template() // note that I changed the variable name.
    {
        TemplateId = 123,
    };

    // Arrange.
    TemplateUpdateRequest request = new TemplateUpdateRequest()
    {
        ExistingTemplate = template
    };

    var templateRepo = new Mock<ITemplateRepository>();
    var uproduceRepo = new Mock<IUProduceRepository>();

     // Mock exception
     templateRepo.Setup(p => p.UpdateTemplate(request)).Throw(new ArgumentException("Something went wrong");

     // Act.
     TemplateService svc = new TemplateService(templateRepo.Object, uproduceRepo.Object);

     TemplateResponse response = svc.UpdateTemplate(request);

     // Assert.
     // Make sure that the exception is handled and null is returned instead.
     Assert.IsNull(response);
}

The ONLY thing you actually tested in the case above is that your service will return null if there's an error in your repo. That way, you have designed a test for a specific scenario, and made sure that your service is doing what's expected when that scenario occurs.
I know that you specifically mentioned that you didn't want it to return null, but it's more of the concept I'm talking about. So let's say that the repo returns null... Write a test for it. Mock the repo to return null, and then test that your service is doing what it should (logging, etc).

so what if there is a bug, or encounters a problem, or return NULL,
which is exactly what I do not want! ?

That's what unit testing is all about. Find a scenario, and then make sure that the class you're testing is doing it's part. Mock your dependencies to create that specific scenario.
When I write my tests I have a lot of tests that simply asserts that a method was called. Let's say that I have a service, which only responsibility is to call the repo. Then you might want to write three tests

*

*Test that the service actually calls the repo.

*Test that the service does what it's suppose to with the value from the repo.

*Test what happens if the repo throws an exception.

A: A unit test is designed to test a unit of functionality, which often is (but definitely need not be) a single class (since we should follow the Single Responsibility Principle).  Therefore, it's fine to new up the class(es) that you're trying to test - it's the dependencies that you need to mock/stub out, which in your case is what you've done with the two repositories.
Whether your call
TemplateResponse response = svc.UpdateTemplate(request);

ends up hitting the DB is a question of using Dependency Injection correctly - your team needs to be disciplined in using explicit dependencies (ie. the repositories which are constructor injected), and not newing up repositories within a class.
And regarding whether your test is going to pass or not - if the class only has explicit dependencies (which are mocked out in your test), then only the logic within the call will be tested, which is exactly what you want!

A: Interaction testing is a form of unit testing where you provide fake dependencies for everything (or some things, or only the really expensive things like databases or disks, there are a lot of different interpretations regarding this) except the thing you actually want to test.
In your example, you're testing whether the TemplateService code behaves correctly. The test provides fake collaborators (the repositories), which you can setup so they return different things in different tests. That way, you can verify whether the TemplateService behaves correctly under these circumstances.
If your concerns about new-ing up the TemplateService are that there might be some remaining calls to a real database in the TemplateService code itself, that's a design issue of the TemplateService code. Those calls should not happen in the TemplateService but should be implemented on a collaborating object (exactly so you can fake them in focused isolated tests for your service).
Writing a unit test without new-ing up the system-under-test provides zero value. If every object is a fake, how can you test your actual production code?
On your point about how those mocked services are actually implemented (Do they throw nulls? Any bugs? Do they return NULL?), that's a question you can solve by
a) Writing integration tests (warning: this does not scale well, see related reading on why integrated tests are a scam).
or b) using something J.B. Rainsberger calls "Contract tests" (see related reading below) to verify whether the actual collaborator objects actually behave in a way consumers expect them to do.
Related reading:

*

*Classicist vs. mockist testing in Martin Fowlers Mocks Aren't Stubs.

*Integrated tests are a scam by J.B. Rainsberger

*Contract tests by J.B.Rainsberger Who tests the contract tests?

A: I recommend you to read the book The Art of Unit Testing: with examples in C# to learn good practice.
In your example, you are testing TemplateService class.
Your concern is what if TemplateService calls database. It depends on how this class is implemented. From the example and mock setup, I can understand that the details of ITemplateRepository is responsible for database calling and that is why UpdateTemplate and IsUniqueTemplateItemName are mocked.
If you want to avoid the Null check, then you can check whether the svc.UpdateTemplate(request) calls the method UpdateTemplate of ITemplateRepository with its parameter.
It should be similar as follows
templateRepo.Verify(u => u.UpdateTemplate(It.Is<TemplateUpdateRequest>(r => r.ExistingTemplate.TemplateId == 123)),Times.Once);

You can verify other method calls that you have mocked.


text:
Q: MySQL Query Result Offset With Limit With New Result Possibility? I'm working on an application that uses a scroll load system of 20 or so results loading into a feed at a time as you scroll. This feed consists of constantly added user generated content. Which means the result set can change per query that is offset by X.
So let's say we load 20 results, then scroll, another 20, and then before scrolling more to load the next 20, another user has uploaded a new piece of content, which effectively would present a duplicate in the next set of 20 results for the feed because we're using OFFSET to get additional results, and the total result set is getting shifted by 1 with this addition of new content that falls into the conditions of the query.
What is the best and most efficient way around this? We've dabbled with using the id of a row in a where condition to prevent duplicate results, and only using limit without offset for new results fetched.. so we could do WHERE id < 170 LIMIT 20, WHERE id < 150 LIMIT 20, WHERE id < 130 LIMIT 20, etc.. to control and prevent duplciates... HOWEVER, this does not work in every possible scenario as our result sets aren't always ordered with the id column ordered by DESC..
Soo.. what other options are there?..

A: Why are you using the where clause instead of limit with the offset option?  Limit can take two arguments.  The offset argument seems to do exactly what you want.  For instance:
limit 100, 20

Takes 20 rows starting at the 101st row.  Then:
limit 120, 20

Takes 20 rows starting at the 121st row.  (The offsets start at 0 rather than 1 in MySQL counting.)
The one enhancement that you need to make is to ensure that the sort order for the records is stable.  A stable sort is, essentially, one where there are no sort keys with the same value.  To make this happen, just make the id column the last column in the sort.  It is unique, so if there are any duplicate sort keys, then the addition of the id makes the sort stable.

A: You might want to try a database solution.  On the initial request, create and populate a table.  Use that table for the feed.
Make sure the tablename starts with something consistent, like TableToFeedMyApp, and ends with something guaranteed to make it unique.  Then set up a scheduled job to find and drop all these tables that were created earlier than whatever you deem to be a certain interval.


text:
Q: Find states intersecting with Google maps polygon I am looking for a way to identify what underlying states intersect with a Google Maps polygon.  I have the ability to identify if two polygons intersect in Maps, so one non-ideal possibility would be to download state boundary data and check to see if each intersect with the polygon.  This could get time consuming checking a polygon against 50 states in every call and the more precise the state boundary, the longer this would take.  Is there a way natively with the API or a better way to determine the states that are below the polygon?  Thanks in advance for your help.

// variables
var map;
var infoWindow;

// initialize map
initMap();

// initialize map
function initMap() {
  // map
  map = new google.maps.Map(document.getElementById('map'), {
    zoom: 8,
    center: {
      lat: 36.99816565700228,
      lng: -88.9013671875
    },
    mapTypeId: google.maps.MapTypeId.TERRAIN
  });

  // coordinates
  var coords = [{
    lat: 37.47049847079873,
    lng: -89.82421875
  }, {
    lat: 36.760891249565624,
    lng: -90.0164794921875
  }, {
    lat: 36.25313319699069,
    lng: -88.6102294921875
  }, {
    lat: 37.583765767186236,
    lng: -87.6104736328125
  }];

  // Construct the polygon.
  var poly = new google.maps.Polygon({
    paths: coords,
    strokeColor: '#FF0000',
    strokeOpacity: 0.8,
    strokeWeight: 3,
    fillColor: '#FF0000',
    fillOpacity: 0.35
  });

  poly.setMap(map);
}
html,
body {
  width: 100%;
  height: 100%;
  margin: 0;
  padding: 0;
}
div#map {
  border: solid 1px #333;
  width: calc(100% - 4px);
  height: calc(100% - 4px);
}

A: Proof of concept using FusionTables for the state polygons.  The resulting candidate states are:

*

*Arkansas

*Illinois

*Kentucky

*Missouri

*Tennessee

(Arkansas doesn't actually intersect)

  google.load('visualization', '1', {
    'packages': ['corechart', 'table', 'geomap']
  });

  // variables
  var map, infoWindow, layer, geoXml, poly;
  var FT_TableID = '19lLpgsKdJRHL2O4fNmJ406ri9JtpIIk8a-AchA'; // numeric ID 420419;
  var CountryName = "United States of America";

  // initialize map
  google.maps.event.addDomListener(window, 'load', initMap);

  // initialize map
  function initMap() {
    // map
    map = new google.maps.Map(document.getElementById('map'), {
      zoom: 8,
      center: {
        lat: 36.99816565700228,
        lng: -88.9013671875
      },
      mapTypeId: google.maps.MapTypeId.TERRAIN
    });
    infoWindow = new google.maps.InfoWindow();

    // coordinates
    var coords = [{
      lat: 37.47049847079873,
      lng: -89.82421875
    }, {
      lat: 36.760891249565624,
      lng: -90.0164794921875
    }, {
      lat: 36.25313319699069,
      lng: -88.6102294921875
    }, {
      lat: 37.583765767186236,
      lng: -87.6104736328125
    }];

    // Construct the polygon.
    poly = new google.maps.Polygon({
      paths: coords,
      strokeColor: '#FF0000',
      strokeOpacity: 0.8,
      strokeWeight: 3,
      fillColor: '#FF0000',
      fillOpacity: 0.35
    });
    var polybounds = new google.maps.LatLngBounds();
    for (var i=0; i<poly.getPath().getLength();i++) {
      polybounds.extend(poly.getPath().getAt(i));
    }
    poly.bounds = polybounds;

    poly.setMap(map);
    //   SELECT 'name_0', 'name_1', 'kml_4326' FROM 19lLpgsKdJRHL2O4fNmJ406ri9JtpIIk8a-AchA WHERE 'name_0' = 'United States of America' ORDER by 'name_1'
    // Fusion Table data ID
    geoXml = new geoXML3.parser({
      // map: map,
      zoom: false,
      infoWindow: infoWindow,
      singleInfoWindow: true
    });

    DisplayCountry(CountryName);

  }

  function DisplayCountry(CountryName) {
    var FT_Query = "SELECT 'kml_4326' FROM " + FT_TableID + " WHERE 'name_0' = '" + CountryName + "';";
    // var FT_Options = { suppressInfoWindows: true, query:FT_Query };
    FT_QueryObj = {
      from: FT_TableID,
      select: "kml_4326",
      where: "'name_0' = '" + CountryName + "'"
    };
    document.getElementById("FTquery").innerHTML = FT_Query + "
select:" + FT_QueryObj.select + "
from:" + FT_QueryObj.from + "
where:" + FT_QueryObj.where;
    var FT_Options = {
      suppressInfoWindows: true,
      query: FT_QueryObj
    };

    layer = new google.maps.FusionTablesLayer(FT_Options);
    layer.setMap(map);

    FT_Query = "SELECT 'kml_4326' FROM " + FT_TableID + " WHERE 'name_0' = '" + CountryName + "';";
    gpolygons = [];
    FT_QueryObj = {
      select: 'kml_4326',
      from: FT_TableID,
      where: "name_0 = '" + CountryName + "'"
    };
    layer.setQuery(FT_QueryObj);
    document.getElementById("FTquery").innerHTML = FT_Query + "
select:" + FT_QueryObj.select + "
from:" + FT_QueryObj.from + "
where:" + FT_QueryObj.where;
    var FT_Query2 = "SELECT 'name_0', 'name_1', 'kml_4326' FROM " + FT_TableID + " WHERE 'name_0' = '" + CountryName + "' ORDER by 'name_1'";
    document.getElementById("FTquery2").innerHTML = FT_Query2;
    var queryText = encodeURIComponent(FT_Query2);
    var query = new google.visualization.Query('http://www.google.com/fusiontables/gvizdata?tq=' + queryText);

    //set the callback function
    query.send(getData);
  }

  //define callback function, this is called when the results are returned
  function getData(response) {
    if (!response) {
      alert('no response');
      return;
    }
    if (response.isError()) {
      alert('Error in query: ' + response.getMessage() + ' ' + response.getDetailedMessage());
      return;
    }
    FTresponse = response;
    //for more information on the response object, see the documentation
    //http://code.google.com/apis/visualization/documentation/reference.html#QueryResponse
    numRows = response.getDataTable().getNumberOfRows();
    numCols = response.getDataTable().getNumberOfColumns();
    if (numRows <= 1) {
      document.getElementById('sidebar').innerHTML = "no data";
      return;
    }

    //concatenate the results into a string, you can build a table here
    for (i = 0; i < numRows; i++) {
      var name = response.getDataTable().getValue(i, 1);
      var kml = response.getDataTable().getValue(i, 2);
      geoXml.parseKmlString("<Placemark>" + kml + "</Placemark>");
      var firstResults = [];
      gpolygons[name] = geoXml.docs[geoXml.docs.length-1].gpolygons[0];
      if (gpolygons[name].bounds.intersects(poly.bounds)) {
      document.getElementById('intersects').innerHTML += name+"
";
      firstResults[name] = gpolygons[name];
      }
    }
    //display the results on the page

  }
html,
body {
  width: 100%;
  height: 100%;
  margin: 0;
  padding: 0;
}
div#map {
  border: solid 1px #333;
  width: calc(100% - 4px);
  height: calc(100% - 4px);
}


text:
Q: How do I conventionally create a replica of an element as a new element in HTML using JavaScript (jQuery)? Fiddle: https://jsfiddle.net/b8fr76cb/
I would like to effectively create a new box by clicking on the "New" button in the navigation bar. I have seen recommendations online not to make use of long HTML strings and append the element that way, so, as far as my limited knowledge goes, this rules out creating a customised box from the get-go. I, thus, see two options:

*

*Make a replica of the current box (there will always be at least one, since there'll be a default one from the beginning) and adjust the properties as per the individual cases.

*Have a hidden "skeleton" box that I replicate and then adjust the properties as per the individual cases. However, I'm not sure whether this option is conventional or permitted or ugly or any other adjective.
Please advise as to which of these is the better option or if there is a better, more recommendable option.
Here's the HTML for the box:

Title

      <input type="text" class="form-control new-name">

        <button type="button" class="btn btn-default confirm-change-name"></button>
        <button type="button" class="btn btn-default cancel-change-name"></button>

    Entry1
    10

    Entry2
    10

    Entry3
    10

    <button type="button" class="btn btn-success">Button1</button>
    <button type="button" class="btn btn-primary">Button2</button>
    <button type="button" class="btn btn-info">Button3</button>

Here's the skeleton code for the JavaScript function that I need to complete:
$('#new-box').click(function() {
 /* Code to add new box alongside the last one. */
});

A: You could use the jQuery.clone() function.
var element = $(".myBox").clone();
// Do your modifications to the box here.
$(element).find('.removeThisRow').remove(); // For example remove a row from the box
$(element).appendTo('#myBoxContainer');

This should do the trick.

A: working Fiddle : https://jsfiddle.net/b8fr76cb/1/
you could just use a simple statement to get your requirement.
$('#new-box').click(function() {
    $("#first-row").parent().append('
'+$("#first-row").html()+"
");
  });

Use of .parent() to target cloning element and use of .append() to create html tags after the available html code.


text:
Q: How to read an xml file in flex actionscript 3 I want to read an xml file placed in the same folder as the swf. Note however there is no webserver running.
<![CDATA[

            private var my_req:URLRequest = new URLRequest("assets/GmetadOutput.xml");
            private var loader:URLLoader;

            public function startup():void {
            output.text="CheckPoint1"; //This is the only output that displays!
  loader = new URLLoader(my_req);
  output.text="CheckPoint2";
  loader.addEventListener(Event.COMPLETE,eventhandler);
  output.text="CheckPoint3";

  }

  public function eventhandler(ev:Event):void {
  output.text="CheckPoint4";
  output.text= XML(loader.data).string;
  }
        ]]>

So on the on CreationComplete event i call startup();
The Checkpoint1 output displays but none of the other checkpoints are reached?
Can anyone tell me what iam doing wrong or better yet tell me how to read a file placed in the same folder as the swf file!
Thanks

A: Not sure why it's not reaching the second checkpoint... If you comment out loader = new URLLoader(my_req);, does it work?  If not, that's weird.
If you want to load local files in Flex, you sometimes have to set the use-network=false compiler argument (set it to false, it defaults to true).  Here's some info on use-network and security sandboxes.
Let me know if that helps,
Lance

A: When you say 'no webserver running' - I assume you saying that you are running it from a local file? In that case - you should use Adobe Air instead of just Flex - then it will work fine for you.


text:
Q: Delphi android java path error I have a problem which is this:

It's different from this. Delphi was working fine but then I removed the jdk 1.8.0 and I have installed the jdk 1.9.0 because I have to work with IntelliJ IDEA (Java).
Delphi (android) is not working anymore because I've removed ( = uninstalled) the 1.8.0 jdk. How do I fix the problem? How can I tell Delphi to use the new 1.9.0 JDK?

I am using Delphi Tokyo. I have edited the windows PATH variable adding the path to the jdk (C:\Program Files\Java\jdk-9.0.1) but it's not working.


text:
Q: Serilog ForContext not working as expected I am using serilog & SEQ with Autofac (DI) in my project (MVC/ web api etc). Although it's working fine
but not sure it's the right way.
I have few questions. please help
Q1) How can I make LoggerConfiguration is manage via Web.config (appsetting) such as Verbose/Debug etc.
Log.Logger = new LoggerConfiguration()
    .MinimumLevel.Verbose()
    .Enrich.FromLogContext()
    .WriteTo.Seq(serilogUrl)
    .CreateLogger();

Q2) With Everymessage I would like to write userid. I have used push propery with out "using" statement.
see below code
public partial class Repo : BaseRepo<db>
    {
        public Repo(ILogger logger) : base(logger)
        {
            var currentuser = GetUserName();
            LogContext.PushProperty("User Name", currentuser);
            Logger.ForContext<Repo>();
        }
  public void somefunction()
  {
    try{}
    catch(exception e){
          Logger.Error(e, "Message");
        }
  }
}

Q3) In a constructor I have used  Logger.ForContext() assuming this will write class name to each message. but it's not working.
   Logger.ForContext<Repo>()

Note: I am not using asp.net core/.Net core

A: The ForContext returns a new ILogger reference that has the context information being added to the logger, so you have to capture that reference and use that for logging.
e.g.
public class YourClass
{
    private readonly ILogger _log;

    public YourClass(ILogger log)
    {
        _log = log
            .ForContext<YourClass>()
            .ForContext("CurrentUserName", GetUserName());

        // ...
    }

    public void Somefunction()
    {
        try
        {
            // ...
        }
        catch(exception ex)
        {
            _log.Error(ex, "Message...");
        }
    }
}

ps: Given that you're using Autofac, you might be interested in using the Autofac-Serilog integration for contextual logger injection, instead of doing it manually.


text:
Q: Does JQuery have inheritance built into it? Does JQuery have built-in inheritance like prototype?
Just found this Question: JQuery inheritance
My original search criteria failed, and I guess from moderation a stupid question...

A: Before you get down-voted into oblivion, I will tell you. No it does not, since Javascript does not support a class structure, this type of paradigm does not exist in JQuery. There are plugins for it. Good luck.


text:
Q: Как в созданном окошке создать два поля для ввода чисел? Доброго дня! Я сегодня начал разбираться со Swing и хочу спросить: как в созданном окошке создать два поля для ввода чисел ? Я смог только создать окошко выставить ему размеры, расположить в середине экрана, а как теперь в этом окошке создать два поля для ввода чисел. Вычитал про JTextField, но никак не могу его засунуть, чтобы оно работало! Не откажусь от хорошей литературы по Swing или видеоуроков или примеров. Если надо суть программы очень проста: забиваешь числа в эти поля, нажимаешь на кнопку которая будет внизу и программа их умножает!
Если в Java есть что-то лучше чем Swing то скажите, может что-то типа PyQt как для Python

A: Примерно так:
JTextField tf1, tf2;
JPanel panel = new JPanel();
//blah-blah
tf1 = new JTextField();
tf2 = new JTextField();
//blah-blah
panel.add(tf1); //добавляем 1-е поле
panel.add(tf2); //добавляем 2-е поле

Общая канва ясна?
Update
В Java есть масса заменителей Swing - в частности, самый известный из них это SWT на котором собственно написана оболочка Eclipse.
Аналогом Qt/PyQt является Qt-Jambi - правда боюсь, что он еще пребывает в глубокой бете.
A: http://docs.oracle.com/javase/6/docs/api/javax/swing/JTextField.html


text:
Q: Android RecyclerView and CardView LayoutManager always crash in Fragment my app always crash,i try to access a fragment that displays a cardview using RecyclerView.
Here is my Fragment
public class Fragmentone extends Fragment {
    private RecyclerView recyclerView;
    private List<TestBean> listItem;
    private RecyclerAdapter adapter;

    public Fragmentone() {
        // Required empty public constructor
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_fragmentone, container, false);

        recyclerView = (RecyclerView) view.findViewById(R.id.recyclerview);
        initData();

        adapter = new RecyclerAdapter(listItem,getActivity());
        LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
        recyclerView.setHasFixedSize(true);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.setAdapter(adapter);
        return view;
    }

    private void initData() {
        listItem = new ArrayList<>();

        listItem.add(new TestBean("佛山傻逼酒店","二月17号","二月18号","600","已付款"));

    }

}

and this is my adapter
public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.ListViewHolder> {
    private List<TestBean> listitem;
    private Context context;

    public RecyclerAdapter(List<TestBean> listitem, Context context) {

        this.listitem = listitem;
        this.context = context;
    }

    @Override
    public ListViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
        View v = LayoutInflater.from(context).inflate(R.layout.card_item, viewGroup, false);
        ListViewHolder listViewHolder = new ListViewHolder(v);
        return listViewHolder;
    }

    @Override
    public void onBindViewHolder(ListViewHolder holder, int i) {
        holder.tv_roomfee.setText(listitem.get(i).getRoomfee());
        holder.tv_hotelname.setText(listitem.get(i).getHotelname());
        holder.tv_liststate.setText(listitem.get(i).getListstate());
        holder.tv_checkindate.setText(listitem.get(i).getCheckindate());
        holder.tv_lastcheckindate.setText(listitem.get(i).getLastcheckindate());

        holder.btn_paynow.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        });
        holder.btn_cancellist.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        });
    }

    @Override
    public int getItemCount() {
        return listitem.size();
    }

    public class ListViewHolder extends RecyclerView.ViewHolder {

        CardView id_cardview;

        TextView tv_roomfee;
        TextView tv_liststate;
        TextView tv_hotelname;
        TextView tv_checkindate;
        TextView tv_lastcheckindate;

        Button btn_paynow;
        Button btn_cancellist;

        public ListViewHolder(final View itemView) {
            super(itemView);
            id_cardview = (CardView) itemView.findViewById(R.id.id_cardview);
            tv_roomfee = (TextView) itemView.findViewById(R.id.tv_roomfee);
            tv_liststate = (TextView) itemView.findViewById(R.id.tv_liststate);
            tv_hotelname = (TextView) itemView.findViewById(R.id.tv_hotelname);
            tv_checkindate = (TextView) itemView.findViewById(R.id.tv_checkindate);
            tv_lastcheckindate = (TextView) itemView.findViewById(R.id.tv_lastcheckindate);

            btn_paynow.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                }
            });
            btn_cancellist.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                }
            });
        }
    }
}

and this is my cardview's xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="5dp">

    <android.support.v7.widget.CardView
        android:id="@+id/id_cardview"
        android:layout_width="match_parent"
        android:layout_height="200dp"
        android:layout_alignParentStart="true"
        android:layout_alignParentTop="true"
        android:clickable="true"
        android:elevation="8dp"
        app:cardCornerRadius="8dp">

        <RelativeLayout

            android:layout_width="match_parent"
            android:layout_height="match_parent">

            <RelativeLayout
                android:id="@+id/stv_hotelname"
                android:layout_width="wrap_content"
                android:layout_height="50dp">

                <ImageView
                    android:id="@+id/iv_hotelicon"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:src="@mipmap/ic_hotelicon" />

                <TextView
                    android:id="@+id/tv_hotelname"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_centerVertical="true"
                    android:layout_toRightOf="@+id/iv_hotelicon"
                    android:text="佛山精神酒店"
                    android:textSize="18sp" />
            </RelativeLayout>

            <RelativeLayout
                android:id="@+id/rlay_roomfee"
                android:layout_marginTop="30dp"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentRight="true"
                android:layout_marginRight="30dp">

                <TextView
                    android:id="@+id/stv_roomfee"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="¥"
                    android:textColor="#F6070C"
                    android:textSize="18dp" />

                <TextView
                    android:id="@+id/tv_roomfee"
                    android:layout_toRightOf="@+id/stv_roomfee"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:textSize="18sp"
                    android:textColor="#F6070C"
                    android:text="400"
                   />

            </RelativeLayout>
            <RelativeLayout
                android:layout_below="@+id/rlay_roomfee"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentRight="true"
                android:layout_marginRight="30dp">
                <TextView
                    android:id="@+id/tv_list"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content" />
                <TextView
                    android:id="@+id/tv_liststate"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:textColor="#F6070C"
                    android:text="待支付"/>
            </RelativeLayout>
            <RelativeLayout
                android:layout_below="@+id/stv_hotelname"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginTop="20dp"
                android:layout_marginLeft="40dp"
                >
                <TextView
                    android:id="@+id/stv_checkindate"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="入住时间:"/>
                <TextView
                    android:id="@+id/tv_checkindate"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_toRightOf="@id/stv_checkindate"
                    android:text="1月10号"/>
                <TextView
                    android:id="@+id/stv_lastcheckindate"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_below="@id/stv_checkindate"
                    android:text="最晚入住时间:"/>
                <TextView
                    android:id="@+id/tv_lastcheckindate"
                    android:layout_below="@+id/tv_checkindate"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_toRightOf="@+id/stv_lastcheckindate"
                    android:text="1月11号"/>

            </RelativeLayout>
            <RelativeLayout
                android:layout_alignParentRight="true"
                android:layout_alignParentBottom="true"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content">
                <Button
                    android:id="@+id/btn_cancellist"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="取消订单"/>
                <Button
                    android:id="@+id/btn_paynow"
                    android:layout_toRightOf="@+id/btn_cancellist"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="立即支付"/>
            </RelativeLayout>
        </RelativeLayout>

    </android.support.v7.widget.CardView>

</RelativeLayout>

when i note
 LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
 recyclerView.setLayoutManager(layoutManager);

it doesn't crash ,but the cardview does'show


text:
Q: Como fijar el numero de decimales de latitud y longitud de lecturas de gps en android studio Estoy obteniendo lecturas de gps usando estas lineas de codigo:
String mLatitud = String.valueOf(location.getLatitude());
String mLongitud = String.valueOf(location.getLongitude());

El problema esta en que en algunas ocaciones la cantidad de decimales varia de 6 a 15 decimales, yo necesitos que latitud tenga 6 decimales y longitud 5 decimales.
Como puedo hacer eso?

A: Puedes usar la clase DecimalFormat para definir la cantidad de decimales:
Defines el formato de esta forma:
DecimalFormat precisionLatitude = new DecimalFormat("0.000000"); //6 decimales
DecimalFormat precisionLongitude = new DecimalFormat("0.00000");  //5 decimales

Aplicas el formato:
String mLatitud = String.valueOf(precisionLatitude.format(location.getLatitude()));
String mLongitud = String.valueOf(precisionLongitude.format(location.getLongitude()));


text:
Q: Symfony 4 how to specify base path that does not change with the current URL? in symfony I have a script that changes my icon to another by updating the icon image file source located at asset/image.png but this only works on the homepage mysite.com.
If I go to another page with mysite.com/foo the file is 404 showing wrong path like this foo/asset/image.png
Why is it appending foo to the image source path ? How can I fix it please ?
I need a way to specify a base path that does not change with the current url
function foo(){
  $("#foo").fadeToggle(fadeSpeed, function () {
      $("#foo").attr("src", "/asset/image.png")
  })
}

A: The problem was I had no asset management system installed.
Everything was solved after installing asset composer require symfony/asset.


text:
Q: Assigning whole table to some other table Lets assume I have the following table
create table Article
(
  ART_ID        bigint not null auto_increment,
  ART_NAME      varchar(25) not null,
  ART_COST      decimal(8,2) not null,
  ART_DESC      text,
  primary key(ART_ID)
);

and also this table
create table Fruits
(
  FRUITS_ID     bigint not null auto_increment,
  FRUITS_TYPE   varchar(15),
  FRUITS_FROZEN timestamp DEFAULT CURRENT_TIMESTAMP,
  primary key(FRUITS_ID )
);

I want the Fruits table to have all the fields of the table Article. How can I implement this? Should I reference it by some relation or is there another trick?

A: I think what you need here is to add an ARTICLE_ID field to Fruits, and then reference it to Articles.ART_ID via a FOREIGN KEY constraint to ensure data consistency.
Note that this means that for each fruit, to have some "article" fields set, a corresponding record in Articles must exist. If you don't want article fields to be mandatory for a fruit, you can make the ARTICLE_ID field nullable. This still allows a foreign key to be defined, but it will only enforce a reference if the value stored in ARTICLE_ID is not NULL.


text:
Q: How to generate the IAM access tokens for analytics engine requests using python? The documentation for Analytics Engine provides a link to generate a IAM access tokens using the CLI, but I need to generate the token with an API call.  This is the CLI approach:
bx api https://api.ng.bluemix.net
bx login
<enter your credentials>

<If you are part of multiple IBM Cloud accounts, you'll be asked to choose an account for the current session. Also, you'll need to choose an organization and space in IBM Cloud.>

bx iam oauth-tokens

The documentation also states that the Cloud Foundry API is deprecated? How can I generate the IAM access tokens?

A: Here is the code I created in the end ...
Some utility classes for logging and exceptions:
import requests
import json
from datetime import datetime, timedelta

import logging
import os

class Logger:

    def __init__(self):
        format = '%(asctime)s - %(name)s - %(levelname)s - %(message)s'
        logging.basicConfig(format=format)
        self.ch = logging.StreamHandler()

    def get_logger(self, clazz):
        logger = logging.getLogger(clazz)
        logger.setLevel(os.getenv("LOG_LEVEL", logging.INFO))
        return logger

class CloudFoundryException(Exception):

    def __init__(self, message, *args):
        self.message = message
        super(CloudFoundryException, self).__init__(message, *args)

Then a class to do the main work:
class CloudFoundryAPI(object):

    def __init__(self, api_key=None, api_key_filename=None, api_endpoint='https://api.ng.bluemix.net', provision_poll_timeout_mins=30):

        self.log = Logger().get_logger(self.__class__.__name__)
        self.provision_poll_timeout_mins = provision_poll_timeout_mins

        assert api_key is not None or api_key_filename is not None, "You must provide a value for api_key or for api_key_filename"

        # allow tests to override the api_key_filename parameter
        if hasattr(CloudFoundryAPI, 'api_key_filename') and CloudFoundryAPI is not None:
            api_key_filename = CloudFoundryAPI.api_key_filename

        if api_key_filename is not None:
            try:
                with open(api_key_filename, 'r') as api_file:
                    d = json.load(api_file)
                    try:
                        self.api_key = d['apikey']
                    except KeyError:
                        # The attibute name used to be
                        self.api_key = d['apiKey']

            except:
                self.log.error('Error retrieving "apiKey" from file {}'.format(api_key_filename))
                raise
        else:
            self.api_key = api_key

        self.api_endpoint = api_endpoint
        self.info = self._get_info()

    def auth(self):
        self.log.debug('Authenticating to CloudFoundry')
        url = self.info['authorization_endpoint'] + '/oauth/token'
        headers = {
                    'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8',
                    'Accept': 'application/x-www-form-urlencoded;charset=utf-8',
                    'Authorization': 'Basic Y2Y6'
                }
        data = 'grant_type=password&username=apikey&password={}'.format(self.api_key)
        try:
            response = requests.post(url, headers=headers, data=data)
            response.raise_for_status()
        except requests.exceptions.RequestException as e:
            self.log.error('Cloud Foundry Auth Response: ' + response.text)
            # TODO we should define a custom application exception for this
            raise

        self.auth_token = response.json()
        self.expires_at = datetime.now() + timedelta(seconds=self.auth_token['expires_in']/60)
        self.log.debug('Authenticated to CloudFoundry')

    def oidc_token(self):

        self.log.debug('Retrieving IAM token')

        url='https://iam.bluemix.net/identity/token'
        data="grant_type=urn:ibm:params:oauth:grant-type:apikey&apikey={}".format(self.api_key)

        try:
            response = requests.post(url, data=data)
            response.raise_for_status()
        except requests.exceptions.RequestException as e:
            self.log.debug('IAM token response: ' + response.text)
            raise

        self.oidc_token = response.json()
        self.oidc_expires_at = datetime.now() + timedelta(seconds=self.oidc_token['expires_in']/60)
        self.log.debug('Retrieved IAM token')
        return self.oidc_token

    def get_auth_token(self):
        if not hasattr(self, 'auth_token') or not hasattr(self, 'expires_at') or datetime.now() > self.expires_at:
            self.auth()
        return self.auth_token

    def get_oidc_token(self):
        if not hasattr(self, 'oidc_token') or not hasattr(self, 'oidc_expires_at') or datetime.now() > self.oidc_expires_at:
            self.oidc_token()
        return self.oidc_token

    def _request_headers(self):

        auth_token = self.get_auth_token()
        access_token = auth_token['access_token']
        token_type = auth_token['token_type']

        headers = {
            'accept': 'application/json',
            'authorization': '{} {}'.format(token_type, access_token),
            'cache-control': 'no-cache',
            'content-type': 'application/json'
            }
        return headers

    def _request(self, url, http_method='get', data=None, description='', create_auth_headers=True):
        if create_auth_headers:
            headers = self._request_headers()
        else:
            headers = {}
        try:
            if http_method == 'get':
                response = requests.get(url, headers=headers)
            elif http_method == 'post':
                response = requests.post(url, headers=headers, data=json.dumps(data))
            elif http_method == 'delete':
                response = requests.delete(url, headers=headers)

            response.raise_for_status()
        except requests.exceptions.RequestException as e:
            self.log.error('{} : {} {} : {} {}'.format(description, http_method, url, response.status_code, response.text))
            raise CloudFoundryException(message=response.text)

        try:
            self.log.debug('{} : {} {} : {} {}'.format(description, http_method, url, response.status_code, json.dumps(response.json())))
        except ValueError:
            self.log.debug('{} : {} {} : {} {}'.format(description, http_method, url, response.status_code, response.text))

        return response

    def _get_info(self):
        url = '{}/v2/info'.format(self.api_endpoint)
        response = self._request(url=url, http_method='get', description='_get_info', create_auth_headers=False)
        return response.json()

You can then use it like so:
cf = CloudFoundryAPI(api_key="xxxx") # or pass api_key_filename
cf.get_auth_token() # get UAA token
cf.get_oidc_token() # get IAM token