text:
Q: Nested resources in namespace form_for Problem
The form_for helper incorrectly determines the path to my nested resource inside of a namespace. The models in question are: Forum::Thread and Forum::Reply respectively, located in a subfolder called "forum" under my models directory. This is in Rails 3 BETA 3.
routes.rb
  namespace :forum do
    root :to => 'threads#index'
    resources :threads do
      resources :replies
    end
  end

app/views/forum/replies/_form.html.haml
...
  - form_for [@thread, @reply] do |f|
...

app/controllers/forum/replies_controller.rb
...
  def new
    @reply = Forum::Reply.new
  end
...

Error
undefined method `forum_thread_forum_replies_path'

In reference to the line outlined above in _form.html.haml

A: Editted solution in case people don't read the reactions:
<%= form_for [:admin, @person, @image] do |f| %>

Old response:
I have a project with an admin namespace and People and Images resources, this is the way I build my form_for in rails3, I haven't found a way just yet to do it cleaner...
<%= form_for [@person, @image], :url => admin_person_images_path do |f| %>

A: @Douglas: It's not working for me. In my view, the names in routes should be pluralize. When I do like recommended, the error is:
undefined method `admin_admin_person_admin_image_path' for #<#<Class:0x55976d0>:0x55a9bc8>

My solution that worked for New:
form_for @image, url: admin_person_images_path(@person, @image)

My solution that worked for Edit:
form_for @image, url: admin_person_image_path(@person, @image)

Ist there any solution to combine this in one form?
Edit (Solution for a new nested namespaced route in a form):
Now I had the following logic in the routes.rb
resources :mobile_users do
 namespace :candystore do
  resource :transactions
 end
end

The form for new_mobile_user_candystore_transactions is
<%= form_for [@mobile_user], url: mobile_user_candystore_transactions_path(@mobile_user), method: :post do |f| %>

to get to the Candystore::TransactionsController create method and not to e.g the MobileUser create method or Candystore::TransactionsController update method.

A: In Rails 3, the only solution that worked for me correctly (for both new and edit resource) was:
form_for @image, :url => url_for([:admin, @person, @image])

A: None of the answers above worked for me - I have a simple Category / Subcategory relationship which is wrapped by a 'Media' namespace.
So I have namespaced nested resources
  namespace :media do
    resources :categories do
      resources :subcategories
    end
  end

but also namespaced models
class Media::Category < ActiveRecord::Base
end

class Media::Subcategory < ActiveRecord::Base
end

In the end, I ended up with this in the _form for subcategories:
<% theurl = @subcategory.new_record? ? media_category_subcategories_path(@category) : media_category_subcategory_path(@category,@subcategory)
   themethod = @subcategory.new_record? ? "POST" : "PATCH" %>
<%= form_for @subcategory, url: theurl , method: themethod do |f| %>
...
<% end %>


text:
Q: How to verify that the checkbox is checked with rc-forms package? When user is registering, I would like to check that TOS (Terms of service) have been read and accepted. To do that, there is a checkbox on my forms "I accept the TOS"

I'm using rc-form package to validate my reactstrap forms, but I don't find how to verify (via rc-form) that the checkbox is checked. Is there a solution using rc-form to avoid manual tests?
In this sample, tosErrors stay empty even if TOS checkbox is unchecked
onSubmit(e) {
  e.preventDefault();

  this.props.form.validateFields((error) => {
    if (!error) {
      const { register } = this.props;
      const { email, password, read } = this.state;

      //HERE IS A MANUAL TEST BECAUSE rules on checkbox are not working
      if (read) {
        register(email, password);
      }
    }
  });
}

render() {
  //...some code was removed because unuseful for stackoverflow question...
  const { getFieldProps, getFieldError, getFieldValue } = this.props.form;
  const tosErrors= getFieldError("read");

  return (
    <Form onSubmit={this.onSubmit}>
      //... some form elements ...
      <FormGroup check>
        <Col sm={{ size: 8, offset: 4 }}>
          <Label check>
            <Input
              type="checkbox"
              name="read"
              id="read"
              className={tosErrors ? "is-invalid" : ""}
              {...getFieldProps("read", {
                initialValue: read,
                rules:[{"required":true}], <==== THE RULES
                onChange,
                valuePropName: "checked"
              })}
            />
          </Label>
          // BELOW THIS IS ONE OF MY MANUAL TEST because tosErrors stay empty
          {getFieldValue("read") || <HelpBlock color={"danger"}>{t("validators:accept cgu")}</HelpBlock>}
        </Col>
      </FormGroup>
      ... SOME OTHER FORM ELEMENTS
    </Form>
}

rc-form package is using async-validator package

A: Add validator function to you component, before render():
checkIsChecked = (rule, value, callback) => {
    if (value === false) {
        callback("You should agree with Terms of Service!");
    } else {
        callback();
    }
}

And then add validator with this function to rules:
rules: [{ required: true }, {
    validator: this.checkIsChecked,
}],

Hope this will help.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Axis labels doesn't show up seaborn lmplot I am ptrying to plot using following code, but axis labels doesn't show up.
 g = sns.lmplot(x='ANR', y='ANR_mean', data=new_df_L)

def annotate(data, **kws):
    slope, intercept, rvalue, pvalue, stderr = scipy.stats.linregress(data['ANR_mean'], data['ANR'])
    print(rvalue, pvalue)
    ax = plt.gca()
    ax.text(.02, .9, 'r2={:.2f}, p={:.2g}'.format(rvalue**2, pvalue),
            transform=ax.transAxes)
g.set_axis_labels( "ANR Estimated" , "ANR Observed" )

g.map_dataframe(annotate)

plt.show()

Any help much appreciated.


text:
Q: discord.py send BytesIO I am manipulating an image using Pillow, and then want to send it to Discord. My code: https://paste.pythondiscord.com/comebefupo.py
When using image.show(), the manipulated image is shown fine.
however, when I want to upload the image to Discord, the bot gets stuck and no error is thrown:
got bytes from direct image string
got bytes from member/user pfp or str
opened image
opened draw
drew top text
drew bottom text
prepared buffer
prepared file
# Bot just gets stuck here, no errors

According to multiple sources (1, 2), I am doing the right thing by saving the image into a BytesIO stream, and then using seek(0).
According to the documentation for a discord.File, it takes a io.BufferedIOBase which is (I believe) I put in.
EDIT:
saving the image first, and then sending that works.
# Return whole image object
return image

self.convert_bytes(image_bytes, top_text, bottom_text).save('image.png')
await ctx.send(file=discord.File('image.png'))

I have no clue why this works, and the other thing doesnt...

A: I had a similar problem last week, this was the code I used to send the image
with BytesIO() as image_binary:
             image.save(image_binary, 'PNG')
             image_binary.seek(0)
             await ctx.send(file=discord.File(fp=image_binary, filename='image.png'))

A: This is not a full answer but it might help.
image_file = discord.File(io.BytesIO(image_bytes.encode()),filename=f"{name}.png")
await ctx.send(file=image_file )


text:
Q: Retornar Imagem (Blob do Banco de dados) Não estou conseguindo retornar as imagens de um controller. Abaixo explico todos a codificação:
Eu criei um controller, e uma view para esse controller que retorna a imagem que está em um campo blob do Oracle. Ela funcionou, normalmente com o controller e view abaixo:
 public class ImagemController : Controller
    {
        // GET: Imagem
        public ActionResult Index()
        {
            return View();
        }
        public ActionResult GetImagem(int id)
        {
            Entities1 tabela = new Entities1();

            byte[] BlobImg = tabela.DATABINARY.Where(p => p.ID.Equals(843)).Select(p => p.DATA).FirstOrDefault();
            return File(BlobImg, "image/png");
        }
    }
}

View:
@{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

Teste de Imagem

Agora, criei um novo controller, para buscar informações de estoque e neste controller eu tenho o atributo IDBLOB, conforme abaixo:
 public class ProntaEntregaController : Controller
    {
        // GET: ProntaEntrega

      public ActionResult Index()
        {
            Entities1 Estoque = new Entities1();

            List<V500_ESTOQUE_PE_WEB> ProntaE = (from p in Estoque.V500_ESTOQUE_PE_WEB select p).Where(x => x.IDBLOB != null).ToList();

            return View(ProntaE);
        }
    }
}

E fiz a view, conforme abaixo só pra teste, porém, as imagens não são retornadas. Fica apenas um ícone de imagem, como se ela não carregasse (vou colocar só uma parte pra não ficar muito longo):

                    @Html.DisplayFor(d => item.COD_REDUZIDO)

                    @Html.DisplayFor(d => item.TOTAL_KG_PE)


text:
Q: Magento Reindex Products Recently I ran into a problem regarding Re-index in Magento.
My store has around 40,000 products and If I change a status of a single product, changes are not reflected on frontend as it needs reindexing of all Indexes.
Moreoever reindexing takes a hell lot of time (around an hour) and I am thinking of a permanent issue.
What does "Save on Update" mode in Reindex specifies ? Does it help in reindexing while saving the product ?
Whats the difference between manual update and update on save ?
Please help.
Thanks in advance.

A: I assume you mean "Update on Save" when you say save on update, also called as "realtime" mode which triggers the re-indexing of product data every time the product has been saved / updated.
Basically in Magento there are only two modes of re-indexing "Update on Save" (Realtime) and "Manual". Their names speak their mode of behavior quite clearly.
In your case, as you have huge amount of products in your store, do the re-indexing through Magento SHELL commands like the following which in turn saves you a lot of time.
SSH to your store and go to shell folder inside your magento root and re-index one by one or all in one shot
    php indexer.php --reindex  catalog_product_flat
    php indexer.php reindexall

A: Use the "Update On Save" re-indexing mode, it will do re-index on the fly for that single product you have saved.

A: The magento manual (http://docs.magento.com/m2/ce/user_guide/system/index-management-manual.html)
States:
Set Actions to "Reindex Data."
Its too bad the options are not available!  Do you see those options in your admin pages?  If not, is there a reason why it might not show up?
I would like to do update on save, but this is not really practical.  I imported a large number of products from CSV.
I tried running the re-indexer from the command line, but by shell directory is missing.
magento missing shell directory
Well, it looks like I am fresh out of ideas!  Maybe I should just pay Varien to run Magento Enterprise for me.  Afterall, re-indexing is a bit complicated, isn't it?


text:
Q: Update to a specific version of PHPUnit Currently my system installed phpunit is on 4.3.1
Doing phpunit --self-update will update to the latest version of phpunit which is 5.3.* at the moment.
I like to update it to a specific version (4.8.24)
How am I suppose to do this?
Note: I know about the composer option, but I would like to do it on my system installed phpunit.

A: I ended up changing the phpunit.phar file on my /usr/local/share/phpunit/ folder
This dev environment is set up via this http://vccw.cc/ and it installs phpunit 4.3.1, I need 4.8.24 coz I'm doing wordpress plugin unit testing http://wp-cli.org/docs/plugin-unit-tests/ it says there 4.8.* is required.
So here is what I did.

*

*Download latest 4.8.* version of phpunit here https://phpunit.de/

*Rename the phar file to phpunit.phar ( I remove the version section )

*Execute this chmod +x phpunit.phar to make the phar file executable

*Copy the phpunit.phar to /usr/local/share/phpunit/ folder

Note: I remove the old phpunit.phar ( that is the 4.3.1 ) and replace with this new one
Also their is already a symbolic link on /usr/local/bin/phpunit for /usr/local/share/phpunit/phpunit.phar setup by vccw.
I think changing phpunit version can be done too via modifying the provisioning files provided by vccw but I'm not that in to provisioning scripts, only basic knowledge.
I hope this helps other devs, specially windows devs like me working on unix based dev env.
PS. This dev env is only used by me, it isn't version controlled so its ok for me if I make changes to the dev env directly ( not via provisioning scripts provided by vccw )


text:
Q: Recommended Input decoupling capacitors I am using these two ICs in my design:
EEPROM CAV24Cxx and Analog MUX 74HC4851.
What is the value of input decoupling capacitor that I must connect near the Vcc pin?
The recommended value of the input decoupling capacitor on the Vcc pin is not mentioned in the datasheet or is it mentioned by someother name which I didn't see?

A: Decoupling capacitors generally do not need to have a specific value.
Exceptions might be voltage regulators like LDOs which sometimes need a specific value (or a value that must be at least xx nF) for best stability. But your chips are logic chips, these aren't picky in that respect.
Most experienced engineers just use 100nF. If we would be using 82 nF somewhere in the circuit already, but not 100 nF, then we might use 82 nF to minimize the number of different components.
I would advise against using decoupling capacitors smaller than 47 nF and larger than 1 uF but that's just my guess.
Having too many decoupling caps is generally not an issue so if you have the space available feel free to add an extra (space for) a capacitor. It does not mean that a capacitor must be placed there. In commercial products you will see empty spaces on a PCB, an empty space is usually much cheaper than designing and manufacturing a new PCB!
If you're quite unsure and want to keep as many options open as possible and have enough PCB area then add footprints for placing extra and larger size capacitors. That way it will be easy to experiment with different values.
But in general: when not listed use 100 nF and chances are that that will do just fine.


text:
Q: If $X$ is T1 with a non-empty finite open subset, does $X$ have isolated points? Let $X$ be a $T1$ topological space. Call $x\in X$ isolated point if $\{x\}$ is open in $X$.
Assume there is an open, finite subset $\emptyset \ne V \subseteq X$. Does $X$ admit an isolated point?
If necessary, I can assume that $X$ is compact, Hausdorff and extremally disconnected (the closure of every open is again open) (this is the case in the scenario where I need it).
Attempt: I feel like I should somehow be able to prove that $V$ contains an isolated point. I also have the impression that I'm missing something obvious.
Let $U$ be a minimal open subset of $V$ that is open in $V$. Since $V$ is finite and $X$ is $T1$, we have that $G:=U^c \cap V$ is open. Hence, $V = U \cup G$. Somehow I want to show that $U$ is a singelton.

A: If $x \in V$ then $F:=V\setminus \{x\}$ is finite (as a subset of $V$) and so closed (as $X$ is $T_1$). So $\{x\} = V\cap (X\setminus F)$ is open in $X$ and so $x$ is isolated.

A: You are almost there. Make use of the $T1$ property. If $x$ and $y$ are two points in $U$, then you can find an open neighbourhood of $x$ which doesn't contain $y$. Can you contradict minimality with this?

A: In fact, all points of $V$ are isolated in $X$. $V$ with the subspace topology is a finite T1 space and therefore it is a discrete topological space. Therefore $\{x\}$ is open in $V$ for all $x\in V$. Since $V$ is open and $\{x\}$ is open in $V$, $\{x\}$ is open in $X$ as well.


text:
Q: Escaping special characters in web2py database connection strings I am using web2py to connect to a db with an 'at' sign in the password, eg 'P@sswd' .
db = DAL('mysql://user1:P@sswd@localhost/test')

This gets interpreted as a connection to host 'sswd@localhost' using password 'P'.
I have tried the obvious URL escaping technique but this failed:
db = DAL('mysql://user1:P%40sswd@localhost/test')

Is there a resource that explains the escaping conventions used in these URL style connection strings?

A: You should use decode_credentials option:
db = DAL('mysql://user1:P%40sswd@localhost/test', decode_credentials=True)


text:
Q: Booksleeve Redis development guide Is there an article or resource on getting started with BookSleeve Redis? Thanks

A: These are some of the articles/links I read when getting upto speed:
http://marcgravell.blogspot.com/2011/04/async-redis-await-booksleeve.html
http://marcgravell.blogspot.com/2011/07/booksleeve-transactions-hashes-and.html
https://code.google.com/p/booksleeve/
http://redis.io/
besides that, search stackoverflow for related questions:
https://stackoverflow.com/questions/tagged/booksleeve
There is not a ton out there, you need to roll up your sleeves and dig in.

A: Book sleeve is just a wrapper around redis, so any data decisions really relate equally to any redis guide. http://redis.io would be a starting place. In terms of the API, the only things that should need highlighting are:

*

*most operations are async and are exposed via the Task api; this allows a range of usage patterns including (but not limited to) the new "async"/"await" keywords

*the operations are split by data type, so .Strings, .Hashes, etc

*a connection is a thread-safe multiplexer and is designed to be used by multiple callers concurrently - you do not (and should not) need to use a connection scoped per caller

I am interested in what things you would want me to include in more detailed documentation. What would be useful? What is unclear? What do you need?
If you can describe what you need, I can write it :p


text:
Q: how can i use search dropdown list in Titanium I want to use a drop down list with text box searching ability. I am new to titanium, if anyone knows how then please inform me.
var picker = Ti.UI.createPicker({
    bottom : 60,
    width : 150
});
var data = [];
data.push(Titanium.UI.createPickerRow({
    title : 'Bananas'
}));
data.push(Titanium.UI.createPickerRow({
    title : 'Strawberries'
}));
data.push(Titanium.UI.createPickerRow({
    title : 'Mangos'
}));
data.push(Titanium.UI.createPickerRow({
    title : 'Grapes'
}));
picker.add(data);
win1.add(picker);
var button = Titanium.UI.createButton({
    title : 'Login',
    right : 50,
    bottom : 30,
    width : 80,
    height : 60
});

win1.add(button);


text:
Q: Minimal "sumset basis" in the discrete linear space $\mathbb F_2^n$ For a set $C\subseteq \mathbb F_2^n$, let $2C=C+C:=\{\alpha+\beta\colon \alpha,\beta\in C\}$.
I want to find $C$ of the smallest possible size such that $2C=\mathbb F_2^n$. Let $m(n)$ be the size of a minimal $C$. I have found the following bounds:
  $$m(n) \ge B(n):=\frac{1+\sqrt{2^{n+3}-7}}{2} $$
and
  $$ m(n) \le A(n) := \left\{\begin{array}{ll} 2^{\frac{n+2}{2}}-2 & {\rm if}\, n\ge4\,{\rm is}\, {\rm even},\\
2^{\frac{n+1}{2}}+2^{\frac{n-1}{2}}-2 & {\rm if}\, n\ge5\,{\rm is}\, {\rm odd}.
\end{array}\right. $$
It is easy to see that $$\lim_{n\rightarrow\infty}{\frac{A(2n)}{B(2n)}=\sqrt{2}},\quad\lim_{n\rightarrow\infty}{\frac{A(2n+1)}{B(2n+1)}}=\frac{3}{2}.$$The last equations show that there might be some improvements for lower or/and upper bounds.
Also I have found the following results if it can help:$$m(1)=1,m(2)=3,m(3)=5,m(4)=6,m(5)=10,m(6)\in\{12,13,14\}.$$
With great probability $m(6)=14$ (actually I am using randomized algorithm to find possible solutions and it didn't find better results for $n=6$ than 14)․ This
sequence could be either https://oeis.org/A099190 or https://oeis.org/A176747. But unfortunately both are excluded, because for $n=7$ they can't match with it. Also I would like to mention that upper bounds are not the best. For example for $n=7$ computer found $C$ such that $|C|=20$. Also better results were found for $n=8,9,10$.
Actually this problem is related with my thesis and I understand that I should do it myself but I have been thinking about it for about two months and I can't find any clever method to get better bounds. Any hints and suggestions would be very appreciated.
Thanks!

A: This is an open problem well known in coding theory.
Let $m:=|C|$, and write the vectors of your set $C$ as columns of a matrix, say $M_C$. Your condition $C+C={\mathbb F}_2^n$ translates as follows: for any non-zero vector $z\in{\mathbb F}_2^n$, there exists a vector $x\in{\mathbb F}_2^m$ of weight $|x|=2$ such that $M_Cx=z$. As a result, the (linear) code $K_C$ with the parity check matrix $M_C$ (that is, $K_C:=\ker M_C<{\mathbb F}_2^m$) has covering radius $2$: for any given $y\in{\mathbb F}_2^m$, either $y\in K_C$, or one can find $x\in{\mathbb F}_2^m$ with $|x|=2$ and $M_Cx=M_Cy$, and then $M_C(x+y)=0$, showing that $y$ differs from $x+y\in K_C$ in exactly two coordinates. It is also easy to see that the rows of $M_C$ must be linearly independent, so that $K_C$ has co-dimension $m$.
This argument is reversible and it shows that the quantity you are interested in is the smallest possible length of a (linear) code with covering radius $2$ and co-dimension $m$. Denote it by $\ell(m)$. Here is a selection of bounds that can be found in Covering Codes by Cohen, Honkala, Litsyn, and Lobstein (Elsevier 1997):

*

*$\ell(2m)\le 27\cdot 2^{m-4}-1$ for $m\ge 4$ (Theorem 5.4.27);

*$\ell(2m+1)\le 5\cdot2^{m-1}-1$ for $m\ge 1$ (Theorem 5.4.27);

*$\ell(2m+1) \ge 2^{m+1}+1$ for $m\ge 2$ (Theorem 7.2.16).

I am not sure whether any of these estimates have been improved over the last two decades, and also whether any non-trivial lower bound for $\ell(2m)$ is known.


text:
Q: C/C++ - создание графического интерфейса Недавно захотелось начать свой проект, идея есть - а вот с реализацией встал вопрос, в частности с созданием интерфейса.
Я хочу проект писать на Си/C++ и при этом планирую использовать MS Visual Studio 2013. Возможно вы скажете сразу, что бы я использовал Qt, но я его не хочу трогать по двум причинам:

*

*В универе требуют MSVS, курсач на нем будет и т.д.

*Хочу все-таки разобраться для начала с технологиями от Microsoft.
Так вот, немного пошарил в нете, понял что есть такие штуки, как WinForms и WPF. Еще так же есть вариант winAPI. И вот тут у меня ступор - где, что и как?
Помогите разобраться, какие технологии применяются для создания интерфейсов с пом.С++ в MSVS; что лучше использовать на сегодняшний день? А так же посоветуйте нормальную литературу на этот счет.
Проект в рамках университета (небольшая программка по электротехнике для расчета всяких величин по заданой схеме), если это важно.
И все же повторюсь в своем вопросе: что нужно знать и что нужно изучать, что бы начать писать GUI на С++ с пом. Visual Studio?
Спасибо!

A: Самое, что вам ближе - это MFC. WinForms - это не С++, это C++/CLI, который работает на платформе MS .Net Framework.
Беда MFC в том, что это тонкая прослойка над WinAPI там шаг влево-шаг вправо от идеологии фреймворка - пропасть.
Писать годные интерфейсы можно и нужно. Но, к счастью или несчастью, Qt здесь почти безальтернативен. Пусть он превносит в язык расширения в виде сигналов-слотов, как следствие - предобработки исходного кода MOC'ом, но это действительно юзабельный бриллиант в мире C++.
В академических целях, желательно овладевать чистым C++, в разумных пределах - WinAPI. Реальные более-менее сложные, переносимые интерфейсы можно писать wxWidget, GTKmm и иже с ними, just for fun.
Но Qt - это настоящее и будущее C++)
ЗЫ Плагин Qt позволяет писать из-под MSVS. Однако, студия враждебна к юникоду.
A: MFC хорош тем, что

*

*большинство преподавателей больше
   ничем не владеют

*все методички в большинстве вузов написаны на MFC и по нему легко найти нужные вам кейсы.

*через MFC проще понять как работает WinAPI, а эти знания не будет лишними в будущем.


text:
Q: use user32.dll in win ce5.0 I am trying to use sendmessage of user32.dll in an embedded windows ce5.0 computer
the same simple program that I made only for testing the user32 in embedded is working on my windows xp computer.
the app and the dll are in the same folder.
the message I get when it is in win ce5.0 is : Can't find Pinvocke DLL 'user32.dll'
the code : (I find it in the web and used it to try the sendmessage)
    private int SC_MONITORPOWER = 0xF170;
    private int WM_SYSCOMMAND = 0x0112;

    [DllImport("user32.dll")]

    private static extern int SendMessage(int hWnd, int hMsg, int wParam, int lParam);
    private void button3_Click(object sender, EventArgs e)
    {
        SendMessage(this.Handle.ToInt32(), WM_SYSCOMMAND, SC_MONITORPOWER, 2);
    }

can anyone help me with this?

A: SendMessage is defined in coredll.dll in Windows CE. See this link:
http://www.pinvoke.net/default.aspx/coredll.SendMessage

A: Please see user32.dll used instead of coredll.dll in WINCE


text:
Q: Heroku Downgrade PHP Version I set up my app on Heroku PHP 7.2 as requirement:
{
    "name": ".../...",
    "require": {
        "php": "~7.2"
    }
}

Now, I downgraded to 7.1 and adjusted my composer.json and composer.lock:
{
    "name": ".../...",
    "require": {
        "php": "~7.1"
    }
}

But it does not work:
remote: Compressing source files... done.
remote: Building source:
remote:
remote: -----> PHP app detected
remote: -----> Bootstrapping...
remote: -----> Installing platform packages...
remote:        - php (7.2.10)
remote:        - ext-gd (bundled with php)

I played around with different version constraints, it does not help. Additionally, I added the config option to restrict the version.
"config": {
    "platform": {
        "php": "7.1.21"
    }
}

Does not help either.
UPDATE:

*

*I thought maybe multiple buildpacks are the problem so I set up an app with only heroku/php as buildpack.

*I used ^7.1 notation instead of ~7.1

*Both Heroku-16 and -18 seem to be affected

A: You want ~7.1.0, not ~7.1. Those are not the same. This is documented extensively in the Composer Versions and constraints documentation article:

The ~ operator is best explained by example: ~1.2 is equivalent to >=1.2 <2.0.0, while ~1.2.3 is equivalent to >=1.2.3 <1.3.0.


text:
Q: Show that the collection of all subsets of a finite sample space satisfies the 3 conditions to be called a collection of events. As title.
Suppose that the sample space $S$ of some experiment is finite. Show that the collection of all subsets of $S$ satisfies the three conditions required to be called the collection of events.
So sample space $S$ is finite, with $N$ possible outcomes, where $N$ is a positive integer. Thus $S$ has the form $S = \{w_1, ..., w_N\}$, where $w_i$ represents the $i$-th possible outcome, for $i \in \{1, ..., N\}$.
This sample space contains $2^N$ possible events like a power set.
We can construct a probability measure by defining probabilities $p_i$ for each particular outcome $w_i \in S$.
$P[w_i] = p_i, \forall i \in \{1, ..., N\}$
I was thinking of defining the probability measure to all events $A \subseteq S$ by defining $P(\emptyset)=0$, and $P(A)$ for each non-empty subset $A \subseteq S$ as follows:
$P(A) = \sum_{w_i \in A} P(w_i)$
where the summation on the right-hand side represents a sum over each of the elements $w_i$ in the set $A$.
My question is, am I on the right track, if so, how do I show that this definition satisfies the three axioms of probability?
That is,

*

*$S$ must be an event.

*If $a \in S$ is an event, then so is $a^c$.

*If $a_1, ..., a_n$ is a countable collection of events, then $\bigcup_{i=1}^{\infty} a_i$ is also an event.

A: Much of the post is not on the right track. The part that is on the right track is the list of three conditions. You need to show that the collection of all subsets of a (finite) set satisfies these conditions. The verifications will be in each case very short.
For example, is $S$ in our collection? Sure, every subset of $S$ is in our collection, and $S$ is a subset of itself.


text:
Q: ASP Net Core MVC Refresh Partial View following Add/Edit via Jquery PopUp Modal I've been trying to work this out for the past few days and I wondered if anyone might be able to get me over the line with it.
The problem I have is that I want to add a new value to the database and then update the partial view without updating the main view which is just a dropdown list and button.
The code I have will currently create the new entry but then it shows the Index/List as its own view, rather than just an updated partial view.
Below is a Main View which a Partial View is rendered to following a button click which renders a partial view based on a dropdown value

@{
    ViewData["Title"] = "Manage DropDown Lists";
    //Layout = "~/Views/Shared/_Layout.cshtml";
}

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css" integrity="sha384-rbsA2VBKQhggwzxH7pPCaAqO46MgnOM80zW1RWuH61DGLwZJEdK2Kadq2F9CUG65" crossorigin="anonymous">

Manage Lists

    Select List:
    @Html.DropDownList("ddl", ViewData["selected"] as List<SelectListItem>)
    <button id="btn-ddl" data-url='@Url.Action("Index", "param")' class="js-load-partial; btn btn-primary btn-sm">Get List</button>

@section Scripts {

}

This is the Jquery for the Button Click (btn-ddl)
//Render PartialView from Button click - input Id from DropDownList - Manage Lists
$(document).ready(function () {
    $("body").on("click", '#btn-ddl', function (evt) {
        var $detailDiv = $('#detailsDiv'),
            url = $(this).data('url');

        url = url.replace("param", $("#ddl").val());

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

This is one of the Partial Views which is rendered.  This partialview is an Index of the selected model.  It also contains a button to Add a new item to the list, and edit buttons to edit the items in the list.
@model IEnumerable<PoCStaffDatabase.Models.AccessLevel>

Access Levels

<button type="button" class="btn btn-primary" data-toggle="ajax-modal" data-target="#addAccessLevel" data-url="@Url.Action("Create")" id="showModalPopup">
    Create
</button>

                @Html.DisplayNameFor(model => model.AccessLevelName)

                @Html.DisplayNameFor(model => model.Live)

        @foreach (var item in Model)
        {

                    @Html.DisplayFor(modelItem => item.AccessLevelName)

                    @Html.DisplayFor(modelItem => item.Live)

                    Edit

        }

The 'Create' button (id="showModalPopup") is clicked to create a new item, and this is done via a Partial View (below) which appears as a Modal Popup.
@model PoCStaffDatabase.Models.AccessLevel

Add Access Level

                <button type="button" class="close" data-dismiss="modal" id="btnClose" aria-label="Close">
                    ×
                </button>

                <form asp-action="Create">

                        <input asp-for="AccessLevelName" class="form-control" />

                            <input class="form-check-input" asp-for="Live" /> @Html.DisplayNameFor(model => model.Live)

                        <button type="button" class="btn btn-danger" data-dismiss="modal" id="btnClose" >Cancel</button>

                        <button type="submit" class="btn btn-primary" data-save="modal" data-url='@Url.Action("Index", "AccessLevels")'id="btnSave">Create New</button>

                </form>

This is the Jquery code which runs from the 'Create New' button (id="btnSave").   I have left in the last thing I tried in order to update the partial view but it's commented out.
Again even with that part in the code the partial view renders as a full view (without formatting as the _Layout view isn't shown either.
$(document).ready(function () {
    $('body').on("click", '#showModalPopup', function (event) {

        var PlaceHolderElement = $('#PlaceHolderHere'),
            url = $(this).data('url');

        PlaceHolderElement.empty();

        $.get(url, function (data) {
            PlaceHolderElement.html(data);
            PlaceHolderElement.find('.modal').modal('show');
        });
    });

    PlaceHolderElement.on("click", '#btnSave', function (event) {
        form = $(this).parents('.modal').find('form'),
            actionUrl = form.attr('action'),
            sendData = form.serialize();

        $.post(actionUrl, sendData).done(function (data) {
            PlaceHolderElement.find('.modal').modal('hide');
        });

       // var $detailDiv = ('#detailsDiv'),
       //         url = $(this).data('url');
       //
       //     $.get(url, function (data) {
       //         $detailDiv.html(data);
       //     });

    });
});

Finally this is the Controller for the Create and Index actions.
namespace PoCStaffDatabase.Controllers
{
    public class AccessLevelsController : Controller
    {
        private readonly AppDbContext _context;

        public AccessLevelsController(AppDbContext context)
        {
            _context = context;
        }

        // GET: AccessLevels
        public async Task<IActionResult> Index()
        {
            var accesslevel = await _context.AccessLevel.ToListAsync();

            return PartialView("_partialIndex", accesslevel);
            //return View(await _context.AccessLevel.ToListAsync());
        }

        // GET: AccessLevels/Details/5
        public async Task<IActionResult> Details(int? id)
        {
            if (id == null)
            {
                return NotFound();
            }

            var accessLevel = await _context.AccessLevel
                .FirstOrDefaultAsync(m => m.AccessLevelId == id);
            if (accessLevel == null)
            {
                return NotFound();
            }

            return View(accessLevel);
        }

        // GET: AccessLevels/Create
        public IActionResult Create()
        {
            AccessLevel accesslevel = new AccessLevel();

            return PartialView("_partialCreate", accesslevel);
        }

        // POST: AccessLevels/Create
        // To protect from overposting attacks, enable the specific properties you want to bind to, for
        // more details, see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Create([Bind("AccessLevelId,AccessLevelName,Live")] AccessLevel accessLevel)
        {
            if (ModelState.IsValid)
            {
                _context.Add(accessLevel);
                await _context.SaveChangesAsync();
                //return NoContent();
                return RedirectToAction("Index");

                //return PartialView("_partialIndex", await _context.AccessLevel.ToListAsync() );
            }
            return View(accessLevel);
        }

Any help that anyone can give would be greatly appreciated.
Thanks.

A: You need change the js like below:
$(document).ready(function () {
    $('body').on("click", '#showModalPopup', function (event) {
        var PlaceHolderElement = $('#PlaceHolderHere'),
            url = $(this).data('url');

        PlaceHolderElement.empty();

        $.get(url, function (data) {
            PlaceHolderElement.html(data);
            var data = PlaceHolderElement.find('.modal');
            //modify here......
            $(PlaceHolderElement.find('.modal')).modal('show')
        });
        //});     remove here

        PlaceHolderElement.on("click", '#btnSave', function (event) {
            form = $(this).parents('.modal').find('form'),
                actionUrl = form.attr('action'),
                sendData = form.serialize();

            $.post(actionUrl, sendData).done(function (data) {
                //modify here......
                $(PlaceHolderElement.find('.modal')).modal('hide');
                $('#detailsDiv').html(data);  //add this...
            });
        });
    });
}) //add this...

Modify your _partialCreate here:
@model AccessLevel
       @*remove fade*@

Add Access Level

                <button type="button" class="close" data-dismiss="modal" id="btnClose" aria-label="Close">
                    ×
                </button>

                <form asp-action="Create">

                        <input asp-for="AccessLevelName" class="form-control" />

                            <input class="form-check-input" asp-for="Live" /> @Html.DisplayNameFor(model => model.Live)

                        <button type="button" class="btn btn-danger" data-dismiss="modal" id="btnClose">Cancel</button>
                          @*change here.........*@
                        <button type="button" class="btn btn-primary" data-save="modal" data-url='@Url.Action("Index", "AccessLevels")' id="btnSave">Create New</button>

                </form>

Backend code:
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create([Bind("AccessLevelId,AccessLevelName,Live")] AccessLevel accessLevel)
{
    if (ModelState.IsValid)
    {
        _context.Add(accessLevel);
        await _context.SaveChangesAsync();
        return PartialView("_partialIndex", await _context.AccessLevel.ToListAsync() );
    }
    throw new Exception("xxxxx");  //ajax cannot judge the modelstate error
}


text:
Q: How to disable browser features and shortcut keys to conduct fullscreen online Exam? I am new to OES (Online Exam System). I want to conduct an Online Examination with Secure environment that user will not be able to cheat
please help do this.
I am using PHP with Codeigniter framework for back end and bootstrap, JS and JQuery for user side or front end.
I have already created a the exam module which is working fine with straight way. but I want to restrict users doing wrong ways tell me the best way to do this or suggest any link where I can get the details about.
Here is My assessment.php view file
    <?php
    $temp = "";
    $sr_no = 0;
    $assessment = $response['assessment'];
    $test_time = $this->session->userdata('test_time') * 60;
    $questions = $response['questions'];
    $total_que = count($questions);
    $i = $que_no - 1;
    $question = $questions[$i];
    $sr_no++;
    $temp.="
<input  type='hidden' name='que_id' value='" . $question['que_id'] . "'>";
    if ($total_que == $que_no) {
        $i = $que_no - 1;
        $temp.="<input  type='hidden' name='que_no' value='$i'>";
    } else {
        $temp.="<input  type='hidden' name='que_no' value='$que_no'>";
    }
    $temp.="Que. $que_no)
                        " . $question['que_dscp'] . "";
    if ($question['que_type'] == "d") {
        $temp.="
";
        if (isset($question['selected_options'])) {
            $temp.="<textarea style='height: 100px;' disabled name='ans_" . $question['que_id'] . "[]'  class='form-control'>" . $question['selected_options'][0] . "</textarea>";
        } else {
            $temp.="<textarea style='height: 100px;' name='ans_" . $question['que_id'] . "[]'  class='form-control'></textarea>";
        }
        $temp.="
";
    } else {
        foreach ($question['options'] as $option) {
            $temp.="

";
            if ($question['que_type'] == "ma") {
                if (isset($question['selected_options'])) {
                    if (in_array($option['option_id'], $question['selected_options'])) {
                        $temp.="<input type='checkbox' checked disabled >";
                    } else {
                        $temp.="<input type='checkbox' disabled >";
                    }
                } else {
                    $temp.="<input type='checkbox' name='ans_" . $question['que_id'] . "[]' value='" . $option['option_id'] . "'>";
                }
            } else if ($question['que_type'] == "sa") {
                if (isset($question['selected_options'])) {
                    if (in_array($option['option_id'], $question['selected_options'])) {
                        $temp.="<input type='radio' checked disabled >";
                    } else {
                        $temp.="<input type='radio' disabled >";
                    }
                } else {
                    $temp.="<input type='radio' name='ans_" . $question['que_id'] . "[]' value='" . $option['option_id'] . "'>";
                }
            }
            $temp.="

                            <input type='text' readonly value='" . $option['option_dscp'] . "' class='form-control'>

";
        }
    }
    $temp.="
";
    $temp1 = "";
    $sr_no = 0;
    foreach ($questions as $question1) {
        $sr_no++;
        $temp1.="$sr_no ";
    }
    ?>

    <link href="<?php echo base_url(); ?>resource/css/TimeCircles.css" rel="stylesheet">

<?php echo $assessment['test_name']; ?> <?php echo $title; ?>

        <?php $this->load->view('alert'); ?>

Questions Navigation

                <?php echo "$temp1"; ?>

            <div id="test_time" data-timer="<?php echo "$test_time"; ?>">

Assessment Questions

                <?php echo validation_errors(); ?>
                <form id="signupform" action="<?php echo base_url(); ?>user/assessment/submit" class="form-horizontal" method="POST">
                    <input type="hidden" name='test_id' value='<?php echo $assessment['test_id']; ?>'>
                    <input type="hidden" name='user_id' value='<?php echo $this->session->userdata('user_id'); ?>'>
                    <?php echo "$temp"; ?>

                            <?php
                            if ($que_no == 1) {
                                ?>
                                Previous
                                <?php
                            } else {
                                ?>
                                <a href="<?php echo base_url(); ?>user/assessment/index/<?php echo $assessment['test_id']; ?>/<?php echo ($que_no - 1); ?>" class='btn btn-info'>Previous
                                <?php
                            }
                            if (isset($question['selected_options'])) {
                                ?>
                                <button id="btn-signup" disabled type="submit" class="btn btn-danger"> &nbsp Save</button>
                                <?php
                            } else {
                                ?>
                                <button id="btn-signup" type="submit" class="btn btn-info"> &nbsp Save</button>
                                <?php
                            }
                            if ($total_que == $que_no) {
                                ?>
                                Next
                                <?php
                            } else {
                                ?>
                                <a href="<?php echo base_url(); ?>user/assessment/index/<?php echo $assessment['test_id']; ?>/<?php echo ($que_no + 1); ?>" class='btn btn-info'>Next
                                <?php
                            }
                            ?>

                    <input type="hidden" id="time_taken" name="time_taken" >

                </form>
                <a href="<?php echo base_url(); ?>user/assessment/solved/<?php echo $assessment['test_id']; ?>/<?php echo $this->session->userdata('user_id'); ?>" class='btn btn-info'>Finish Test

Here is My home.php view file from where I redirect user to assessment.php
<?php
$temp = "";
$sr_no = 0;
foreach ($assessments as $assessment) {
    $solved = $assessment['solved'];
    $test_id = $assessment['test_id'];
    $test_name = $assessment['test_name'];
    $status = $assessment['status'];
    if ($status == "1") {
        $status = "Active";
    } else {
        $status = "InActive";
    }
    $sr_no++;
    $temp.="

                $sr_no
                $test_name
                $status	";
                 if($solved=="0"){
                    $temp.="Take Test	";
                 }else if($solved=="1"){
                    $temp.="
                    	";
                 }
        $temp.="
";
}
?>
<link rel="stylesheet" href="<?php echo base_url(); ?>resource/css/bootstrap-table.css">

User Assessment System! User Dashboard <?php echo $title; ?>

    <?php $this->load->view('alert'); ?>

Manage Assessment

                        #
                        Assessment Name
                        Status
                        Start/View Test

                    <?php echo "$temp"; ?>

A: There is absolutely no way for you to restrict someone in a location not controlled by you.
No matter what you do to my browser or even my operating system, I can always just use a second computer, or my phone, or have a book lying around, or a sheet of paper, or a friend who knows stuff.
The only way to detect such a thing would be a camera filming the user the entire time.
In addition to that, you'd have to film the screen - with a camera too, not via a screen recorder, because otherwise I might just use a virtual machine for the exam, in which the browser is in full screen all the time, but I can just alt-Tab out of the VM and do whatever I want, while a screen recorder will just see the inside of the VM.
So you cannot actually restrict the user - the only thing you can try is to surveil them.
That would require at the very least one microphone and two cameras, probably more - one to film the screen (so that you can actually recognise something afterwards) and the rest to film the user and his entire possible field of view (don't forget the ceiling, there could be writing or something). The microphone, of course, is to make sure the user has no audible input during the exam - this also implies that they must not wear headphones, otherwise they might make use of some sound-based interface.
For example, I imagine a service which, upon activation by hotkey, opens an invisible browser window, captures your keyboard input, conducts a Google search upon hitting Return, lets you navigate via the arrow keys/Return/Tab/Backspace/Esc and reads to you any text that you "select".
I believe on OS X, one would only need to find a way to make windows invisible - then they could activate Voice over, set their start page to Google and create a service with Automator that opens a new browser window (invisibly), to which they can then assign a hotkey.
Also, all recordings should be transmitted in real time, otherwise the user has a chance to tamper with them.
Now that I wrote this I realise that this is probably more of a question for Information Security.

A: This might help you partially,
You can suppress few keydown events which might help you partially, You won't be able to disable all the events though,
window.addEventListener('keydown', function (event) {
    // if the keyCode is 16 ( shift key was pressed )
    // Here you can specify which key events you want to disable
    if ((event.which || event.keyCode) === 16) {
        // prevent default behaviour
        event.preventDefault();
        // Few Browser also need return false, to disable keydown events
        return false;
    }
});

A: For limited browser capabilities,
You can use Javascript's window.open function, it takes certain parameters. For example look below
If you look at the third parameters, it does the tricks that you are looking for, it disables the toolbar and all those stuffs.
window.open('exampage.html','some_name_for_this_window','titlebar=no,toolbar=no,menubar=no,width=400,height=350');

Take a look at the Mozilla Docs for what other features you can disable or enable. It might help you out
And on the backend for what the user is clicking and interacting, you have codeigniter's SESSION library to take care of that

A: I had a similar question which was closed. After some online search, found out this amazing software called safeexambrowser which currently works for windows and mac os.  Built on Firefox/ gecko engine, it will help you to disable keyboard shortcuts and refrains user from using any other application.
This is suitable for standallone web applications. Please check if this suits your requirement.


text:
Q: Why may I have no "Cloud Functions Admin" role option to grant at Google Cloud? I'm trying to connect Firebase with Flutterflow.
For this, I need to grant permissions, using a provided Flutterflow login.
One of the steps is to dry Cloud Functions Admin role, associated with this login.
Problem is, there's no such option on the page where you suppose to do it!

Fun fact, with my previous project it works fine, I can see the Cloud Functions tab with this role inside.
I've checked the list of all roles, found this specific one – it's here, enabled.
I've duplicated this role and granted the duplicate instead of "Cloud Functions Admin", but still Flutterflow says there's no permission.

A: The Cloud Functions API had to be enabled first (as confirmed in comments). It's off by default for new projects; generally each project must enable the APIs it wishes to use.


text:
Q: Where clause throws error Why does this code throw an error?
using (MySqlConnection cn = new MySqlConnection(VarribleKeeper.MySQLConnectionString))
{
    {
        MySqlCommand Command = new MySqlCommand();
        Command.Connection = cn;

        Command.CommandText = "UPDATE TeleworksStats SET Ja= ('" + JaTak +
            "') WHERE Brugernavn = " + VarribleKeeper.Brugernavn + "' AND Dato = " +
            DateTime.Today.ToString("yyyy-MM-dd") + "";
        cn.Open();
        Command.ExecuteNonQuery();
        //Ryd op
        Command.Dispose();
        cn.Close();
    }
}

A: You missed one quote ' after Brugernavn = and Dato:
Brugernavn = "... '" + VarribleKeeper.Brugernavn + "' AND Dato = '" +
             DateTime.Today.ToString("yyyy-MM-dd") + "'";

Also I strongly recommend that you always use parameterized queries to avoid SQL Injection like this:
Command.CommandText =
     "UPDATE TeleworksStats SET Ja = @Ja WHERE Brugernavn = @Brugernavn and ...";
Command.Parameters.AddWithValue("@Ja", JaTak);
Command.Parameters.AddWithValue("@Brugernavn",  VarribleKeeper.Brugernavn);

Although specify the type directly and use the Value property is more better than AddWithValue. Check this: Can we stop using AddWithValue() already?

A: Rather than just forgetting ' for the value of Brugernavn column and both single quotes for Dato column, I think you have more things to keep in mind.

*

*Use using statement to dispose your Command object as you did for your connection instead of calling Close or Dispose methods manually.

*Use paramterized queries instead of string concatenation. This kind of codes are open for SQL Injection attacks.

*Looks like you try to save your DateTime values with their string representations. Do not do that! If you wanna keep your DateTime values to your database, you need to pass them directly. Change your Dato column to DateTime type. Read: Bad habits to kick : choosing the wrong data type

using(var cn = new MySqlConnection(VarribleKeeper.MySQLConnectionString))
using(var Command = cn.CreateCommand())
{
   Command.CommandText = @"UPDATE TeleworksStats SET Ja = @Ja
                           WHERE Brugernavn = @Brugernavn  AND Dato = @Dato";
   Command.Parameters.Add("@Ja", MySqlDbType.VarChar).Value = JaTak;
   Command.Parameters.Add("@Ja", MySqlDbType.VarChar).Value = VarribleKeeper.Brugernavn;
   Command.Parameters.Add("@Ja", MySqlDbType.DateTime).Value = DateTime.Today;
   // I assumed your column types. You should write proper column types instead.

   cn.Open();
   Command.ExecuteNonQuery();
}


text:
Q: unable to make Elastic Load Balancer work on port 8080 My EC2 instance has a site hosted using tomcat and that can be accessed using
http://public-Ip:8080/index.html

But when i put this instance behind a elastic load balancer, set the health check to
HTTP:8080/index.html

though the ELB passes the health check, when i try to access the using site using
 http://ELB:8080/index.html

i am unable to access the site.
Is there something that is missing? or i need to do additionally.
This is how my LB listner tab looks like
LB listner tab

A: There was issue with the communication between the Security Group  (SG) of my EC2 instances and the Elactic Load balancer(ELB) SG. I allowed my EC2 SG in the ELB SG and that helped.


text:
Q: Weird behavior of custom item renderer in Flex 4 I have a class defined like this:
public class Photo
    {
        public function Photo()
        {
        }
        public var PhotoId:int;
        public var Title :String;
        public var Subtitle :String;
        public var PhotoByteArray:ByteArray ;
        public var ThumbnailByteArray:ByteArray;
        public var ShowOnlyInFrontpageTop:Boolean;
        public var ShowInFrontpageGroup:Boolean;
        public var BackgroundColorGradientFrom:String;
        public var BackgroundColorGradientTo:String;
        public var IsActive :Boolean;
    }

I 'm getting diverse objects of this type (Photo) from a WCF service (works fine!). These objects are stored in an ArrayCollection  defined like this:
public static var GroupPhotos:ArrayCollection = new ArrayCollection();

I want to show up these photos using a s:List component, like this:
<s:List height="110" id="GroupPhotos" itemRenderer="MyGroupPhotoRenderer">
                <s:layout >
                    <s:HorizontalLayout requestedColumnCount="3"  />
                </s:layout>
            </s:List>

The item renderer is defined this way:
<?xml version="1.0" encoding="utf-8"?>
<s:ItemRenderer xmlns:fx="http://ns.adobe.com/mxml/2009"
                xmlns:s="library://ns.adobe.com/flex/spark"
                xmlns:mx="library://ns.adobe.com/flex/mx"
                autoDrawBackground="true"
                creationComplete="onItemrenderer_creationCompleteHandler(event)">
    <fx:Script>
        <![CDATA[
            import mx.controls.Alert;
            import mx.events.FlexEvent;

            //when the item has been rendered and is ready to be shown the following method will be called
            protected function onItemrenderer_creationCompleteHandler(event:FlexEvent):void
            {
                img.source =  data.ThumbnailByteArray;
            }

        ]]>
    </fx:Script>

    <s:Group id="PhotoGroup" width="297" height="110" >
        <!--<s:Rect id="imgRectangle" alpha="0" width="95" height="65">
            <s:stroke>
                <s:LinearGradientStroke weight="{GroupBoxBorderWeight}" scaleMode="none"/>
            </s:stroke>
        </s:Rect>-->
        <mx:Image id="img"
                  width="{PhotoGroup.width}" height="{PhotoGroup.height}"
                  />
        <s:Label id="title"
                 fontSize="20"
                 text="{data.Title}"/>
    </s:Group>
</s:ItemRenderer>

The s:Label component shows up correctly whereas the mx:Image component shows up always the same image (don't know if this is the first Image or the last in the array).
What am i missing?
Thanks in advance

A: Ahhm!!Turns out that this my error! Above i stated that the service is running fine: guess what...it didn't! Fixing the service made the images show up correctly!

A: Creation complete is only called the first time your renderer is created. Since Flex reuses renderers that means it will only get called the first time. Instead of using creationComplete, override the set data method of your renderer. Unfortunately, s:ItemRenderer doesn't have a set data method, so I'd use a mx:HBox component instead.
Here's a quick example to get you started:
<?xml version="1.0" encoding="utf-8"?>
<mx:HBox xmlns:fx="http://ns.adobe.com/mxml/2009"
             xmlns:s="library://ns.adobe.com/flex/spark"
             xmlns:mx="library://ns.adobe.com/flex/mx">
    <fx:Script>
        <![CDATA[

            override public function set data(value:Object):void
            {
                super.data = value;

                theLabel.text = value["Title"].toString();
                theImage.source = data.ThumbnailByteArray;

                validateDisplayList();
            }

        ]]>
    </fx:Script>
    <mx:Label id="theLabel" />
    <mx:Image id="theImage" />
</mx:HBox>


text:
Q: Expected Value of First k Draws From a Weighted Distribution Without Replacement You have weighted distribution, D and draw from it without replacement - meaning that when a value is chosen it and all its associated weight is removed from the distribution. In probabilistic terms, the distribution would now be altered to D' where p(k)' = 0 and p(i)'= p(i|~k).
Now consider the first m draws from this distribution. Is there a non-computationally intensive way to compute the expected value? Obviously, to compute the expected value of the ith draw you can sum across all permutations, $\Gamma$, of previous choices, multiplied by $p(\gamma)$,and then multiply by $p(j|\gamma)$ and then multiply by the value:
$$\sum_{\gamma=0}^\Gamma \sum_{j=0}^N p(\gamma)p(v_j|\gamma)v_j$$
and then you sum the above formula from 1 to m (with m as a subscript of gamma) to get the expected value of the first m draws. However, this is clearly not ideal from an algorithmic standpoint. I believe it is $O(m*N^{m+1})$ (but the exact big O is not the focus here. It is clearly intractable as m and N get large).
My question is: is there a (computationally) better formula to use for this problem?


text:
Q: Problem with heteroscedastic residuals using lme with varIdent I´m having problems when I try to fix heteroscedasticity in mixed models with lme.
My experimental design consists of 12 independent enclosures (Encl) with populations of lizards (Subject_ID). We applied 2 crossed treatments (Lag: 3 levels and Var: 2 levels). And we repeated the experiment two years (Year), so individuals that survived the first year, were measured again the next year. We analyse the snout vent length (SVL) in mm. Sex (males and females). This was my model:
    ctrl <- lmeControl(maxIter=200, msMaxIter=200, msVervose=TRUE, opt="optim")

    options (contrast=c(factor="contr.sum", ordered="contr.poly"))

    model.SVL <- lme(SVL~Lag*Var*Sex*Year, random=list(~1|Subject_ID, ~1|Encl), control=ctrl, data=data)

enter image description here
enter image description here
enter image description here
The model showed heteroscedasticity in several triple interactions using bartlett.test, so I corrected it with varIdent. However, heteroscedasticity was not fixed, and now, qqplot indicates leptokurtic distribution.
model.SVL2 <- lme(SVL~Lag*Var*Sex*Year, random=list(~1|Subject_ID, ~1|Encl), control=ctrl, weights=varIdent (form=~1|Lag*Var*Sex*Year), data=data)

What could be the problem?
I think the problem is using varIdent when I include Subject_ID as a random factor. If I remove it, this doesn't happen. Maybe it is because many individuals do not survive two years, and it is a random factor with many levels but few replications


text:
Q: Unable to resolve the error caused by PCL cylinder detection I used PointCloudLibrary (PCL) to perform the column detection. The program to perform the cylinder detection is as follows (almost the same as the PCL tutorial).
#include <pcl/ModelCoefficients.h>
#include <pcl/io/pcd_io.h>
#include <pcl/point_types.h>
#include <pcl/filters/extract_indices.h>
#include <pcl/filters/passthrough.h>
#include <pcl/features/normal_3d.h>
#include <pcl/sample_consensus/method_types.h>
#include <pcl/sample_consensus/model_types.h>
#include <pcl/segmentation/sac_segmentation.h>

typedef pcl::PointXYZ PointT;

int
main (int argc, char** argv)
{
  std::string filename = "inputfile.pcd";

  // All the objects needed
  pcl::PCDReader reader;
  pcl::PassThrough<PointT> pass;
  pcl::NormalEstimation<PointT, pcl::Normal> ne;
  pcl::SACSegmentationFromNormals<PointT, pcl::Normal> seg;
  pcl::PCDWriter writer;
  pcl::ExtractIndices<PointT> extract;
  pcl::ExtractIndices<pcl::Normal> extract_normals;
  pcl::search::KdTree<PointT>::Ptr tree (new pcl::search::KdTree<PointT> ());

  // Datasets
  pcl::PointCloud<PointT>::Ptr cloud (new pcl::PointCloud<PointT>);
  pcl::PointCloud<PointT>::Ptr cloud_filtered (new pcl::PointCloud<PointT>);
  pcl::PointCloud<pcl::Normal>::Ptr cloud_normals (new pcl::PointCloud<pcl::Normal>);
  pcl::PointCloud<PointT>::Ptr cloud_filtered2 (new pcl::PointCloud<PointT>);
  pcl::PointCloud<pcl::Normal>::Ptr cloud_normals2 (new pcl::PointCloud<pcl::Normal>);
  pcl::ModelCoefficients::Ptr coefficients_plane (new pcl::ModelCoefficients),
coefficients_cylinder (new pcl::ModelCoefficients);
  pcl::PointIndices::Ptr inliers_plane (new pcl::PointIndices), inliers_cylinder (new
pcl::PointIndices);

  // Read in the cloud data
  reader.read (filename, *cloud);
  std::cerr << "PointCloud has: " << cloud->points.size () << " data points." << std::endl;

  // Build a passthrough filter to remove spurious NaNs
  pass.setInputCloud (cloud);
  pass.setFilterFieldName ("z");
  pass.setFilterLimits (0, 1.5);
  pass.filter (*cloud_filtered);
  std::cerr << "PointCloud after filtering has: " << cloud_filtered->points.size () << "
data points." << std::endl;

  // Estimate point normals
  ne.setSearchMethod (tree);
  ne.setInputCloud (cloud_filtered);
  ne.setKSearch (50);
  ne.compute (*cloud_normals);

  // Create the segmentation object for the planar model and set all the parameters
  seg.setOptimizeCoefficients (true);
  seg.setModelType (pcl::SACMODEL_NORMAL_PLANE);
  seg.setNormalDistanceWeight (0.1);
  seg.setMethodType (pcl::SAC_RANSAC);
  seg.setMaxIterations (100);
  seg.setDistanceThreshold (0.03);
  seg.setInputCloud (cloud_filtered);
  seg.setInputNormals (cloud_normals);
  // Obtain the plane inliers and coefficients
  seg.segment (*inliers_plane, *coefficients_plane);
  std::cerr << "Plane coefficients: " << *coefficients_plane << std::endl;

  // Extract the planar inliers from the input cloud
  extract.setInputCloud (cloud_filtered);
  extract.setIndices (inliers_plane);
  extract.setNegative (false);

  // Write the planar inliers to disk
  pcl::PointCloud<PointT>::Ptr cloud_plane (new pcl::PointCloud<PointT> ());
  extract.filter (*cloud_plane);
  std::cerr << "PointCloud representing the planar component: " << cloud_plane->points.size
() << " data points." << std::endl;
  writer.write (filename, *cloud_plane, false);

  // Remove the planar inliers, extract the rest
  extract.setNegative (true);
  extract.filter (*cloud_filtered2);
  extract_normals.setNegative (true);
  extract_normals.setInputCloud (cloud_normals);
  extract_normals.setIndices (inliers_plane);
  extract_normals.filter (*cloud_normals2);

  // Create the segmentation object for cylinder segmentation and set all the parameters
  seg.setOptimizeCoefficients (true);
  seg.setModelType (pcl::SACMODEL_CYLINDER);
  seg.setMethodType (pcl::SAC_RANSAC);
  seg.setNormalDistanceWeight (0.1);
  seg.setMaxIterations (10000);
  seg.setDistanceThreshold (0.05);
  seg.setRadiusLimits (0, 0.1);
  seg.setInputCloud (cloud_filtered2);
  seg.setInputNormals (cloud_normals2);

  // Obtain the cylinder inliers and coefficients
  seg.segment (*inliers_cylinder, *coefficients_cylinder);
  std::cerr << "Cylinder coefficients: " << *coefficients_cylinder << std::endl;

  // Write the cylinder inliers to disk
  extract.setInputCloud (cloud_filtered2);
  extract.setIndices (inliers_cylinder);
  extract.setNegative (false);
  pcl::PointCloud<PointT>::Ptr cloud_cylinder (new pcl::PointCloud<PointT> ());
  extract.filter (*cloud_cylinder);
  if (cloud_cylinder->points.empty ())
    std::cerr << "Can't find the cylindrical component." << std::endl;
  else
  {
      std::cerr << "PointCloud representing the cylindrical component: " << cloud_cylinder-
 >points.size () << " data points." << std::endl;
      writer.write (filename, *cloud_cylinder, false);
  }
  return (0);
}

Then I get the following error for some point cloud files. Of course, there are possible point clouds in the input file, but I can't find them. The number of point clouds in the input file is shown, so I think I can input the data, but for some reason I cannot get the cylinder parameter.
However, for some reason I cannot get the cylinder parameters.
PointCloud has: 1042 data points.
PointCloud after filtering has: 0 data points.
[pcl::NormalEstimation::compute] input_ is empty!
[pcl::SampleConsensusModel::getSamples] Can not select 0 unique points out of 0!
[pcl::RandomSampleConsensus::computeModel] No samples could be selected!
[pcl::SACSegmentationFromNormals::segment] Error segmenting the model! No solution found.
Plane coefficients: header:
seq: 0 stamp: 0 frame_id:
values[]

PointCloud representing the planar component: 0 data points.
terminate called after throwing an instance of 'pcl::IOException'
  what():  : [pcl::PCDWriter::writeASCII] Input point cloud has no data!
Aborted (core dumped)

A: After a number of revisions to the thresholds in the code, we were able to solve the problem.


text:
Q: SciPy module names and functions fail to be defined I just installed ANACONDA and have set up my virtual environment and profile. When I enter a command like
from pandas import *

or
from numpy import random

the system pauses for a second before moving on to the next line, as expected. However, when I try to enter a command like
x = randn(100,100)

I get a message saying

name 'randn' is not defined

Also, when I run
imp.find_module("pandas")

I get
(None, 'C:\\Anaconda\\lib\\site-packages\\numpy', ('', '', 5))

Any ideas?

A: Your message title refers to scipy, but you didn't import anything from it, so I'm not sure why that's relevant.  You did two imports:
from pandas import *

which I wouldn't actually recommend; I know it's done in some tutorials, but I prefer
import pandas as pd

to keep the namespace clean.  In any case, randn isn't defined in the pandas namespace.  Then you run
from numpy import random

which only adds one new name to the namespace: random.  After you've done this, you can access randn via random.randn:
>>> from numpy import random
>>> random.randn(3)
array([-1.19504793, -0.54873061, -1.46225504])

If you really want to use simply randn, you could do
from numpy.random import randn


text:
Q: Should it be obvious that independent quantum states are composed by taking the tensor product? My text introduces multi-quibt quantum states with the example of a state that can be "factored" into two (non-entangled) substates. It then goes on to suggest that it should be obvious1 that the joint state of two (non-entangled) substates should be the tensor product of the substates: that is, for example, that given a first qubit
$$\left|a\right\rangle = \alpha_1\left|0\right\rangle+\alpha_2\left|1\right\rangle$$
and a second qubit
$$\left|b\right\rangle = \beta_1\left|0\right\rangle+\beta_2\left|1\right\rangle$$
any non-entangled joint two-qubit state of $\left|a\right\rangle$ and $\left|b\right\rangle$ will be
$$\left|a\right\rangle\otimes\left|b\right\rangle = \alpha_1 \beta_1\left|00\right\rangle+\alpha_1\beta_2\left|01\right\rangle+\alpha_2\beta_1\left|10\right\rangle+\alpha_2\beta_2\left|11\right\rangle$$
but it isn't clear to me why this should be the case.
It seems to me there is some implicit understanding or interpretation of the coefficients $\alpha_i$ and $\beta_i$ that is used to arrive at this conclusion. It's clear enough why this should be true in a classical case, where the coefficients represent (where normalized, relative) abundance, so that the result follows from simple combinatorics. But what accounts for the assertion that this is true for a quantum system, in which (at least in my text, up to this point) coefficients only have this correspondence by analogy (and a perplexing analogy at that, since they can be complex and negative)?
Should it be obvious that independent quantum states are composed by taking the tensor product, or is some additional observation or definition (e.g. of the nature of the coefficients of quantum states) required?

1: See (bottom of p. 18) "so the state of the two qubits must be the product" (emphasis added).

A: I would like to add here some further theoretical content the the excellent answer by @joshphysics, since in my view this subject is not treated as it should deserve and there are several theoretical results on the subject which should be known.
Let us consider a quantum system $S$ described in the Hilbert space $\cal H$ and suppose that it is made of two independent parts $S_1$ and $S_2$. We want to discuss when this system can be represented in a suitable tensor product $\cal H_1 \otimes \cal H_2$, for some Hilbert spaces $\cal H_i$ associated with $S_i$, $i=1,2$.
In the rest of my answer I do not use the notion of tensor product as a priori description of independent subsystems, because I want to discuss when this description is feasible.
First of all the systems $S$, $S_1$, $S_2$ are pictured in terms of their observables. With a very great generality we can assume that these observables are bounded (the unbounded ones cam be obtained as limit in the strong operator topology from the bounded ones) and the sets of observables (including complex linear combinations of operators) are closed with respect to the product and the sum and the strong operator topology (this is necessary for implementing the standard spectral machinery).
This way we get a well-known structure called von Neumann algebra of observables. So there are three von Neumann algebras here: $R$ associated to $S$ and $R_i$ respectively associated to $S_i$, for $i=1,2$.
The selfadjoint operators $A\in R$ represent all of (bounded) observables of the system $S$. Similarly, The selfadjoint operators $A_i\in R_i$ represent all of (bounded) observables of the system $S_i$, $i=1,2$.
A typical situation is $R = B(\cal H)$, where $B(\cal H)$ denotes the full algebra of bounded operators $A: \cal H \to \cal H$ (if $\cal H$ is finite dimensional boundedness is automatic). However in case of presence of superselection rules or when there is a gauge group, not all selfadjoint operators over $\cal H$ represent observables, so the assumption $R = B(\cal H)$ is generally untenable.
Let us discuss how the notion of independent subsystems is presented in this picture. There are three requirements

*

*$R_i$ are substructures of $R$: $R_i \subset R$, for $i=1,2$,

*$R_1$ and $R_2$ are compatible: $[A_1,A_2]=0$ if $A_1\in R_1$ and $A_2\in R_2$,

*we can independently assign states on $R_1$ and $R_2$ according to the requirement below called $W^*$-independence
[$W^*$-independence]. If $T_1$ and $T_2$ are statistical operators acting on the observables of $R_1$ and $R_2$ respectively ($<A_i>_{T_i} = tr(T_iA_i)$), then there exists a statistical operator $T$ for the overall system (acting on $R$) such that $$tr(TA_i) = tr(T_iA_i) \quad \mbox{ for every $A_i\in R_i$, $i=1,2$.}$$
There are many implementations of the notion of independence in fixing states on subsystems and this is proper of the Hilbert space description of quantum theory.
Under the hypotheses (1)-(3) (also weakening them) it arises that the algebra generated by $R_1$ and $R_2$ (the finite sum of finite product so elements in the union of the algebras) is isomorphic to $R_1\otimes R_2$ in pure algebraic sense (without topological implications). This is however still quite far from the standard picture where also the Hilbert space is factorized $\cal H = \cal H_1 \otimes \cal H_2$ and the algebras $R_1$ and $R_2$ are interpreted as algebras of operators in the factors $\cal H_1$ and $\cal H_2$.
The converse is however true as I go to illustrate.
Suppose that $\cal H = \cal H_1 \otimes \cal H_2$
so that $B(\cal H) = B(\cal H_1) \otimes B(\cal H_2)$.
Next we fix

*

*$R=B(\cal H)$,

*$R_1= B(\cal H_1)\otimes I_2$

*$R_2= I_1 \otimes B(\cal H_1)$
Above $I_k$ indicates the identity operator over $\cal H_k$.
In particular $A_1 \in R_1$ takes the form $A'_1\otimes I_2$ for some
$A'_1 \in B(\cal H_1)$ and an analogous fact is true for $S_2$.
In this case (1), (2) are satisfied trivially and (3) is true in an even stronger sense. If $T_1$ acts as a statistical operator over $R_1$ it can always be written as $T'_1\otimes I_2$, for some statistical operators in the space $\cal H_1$, the analogue is true for $S_2$. A state $T$ satisfying (3) is always $T= T_1'\otimes T'_2$. This state has a further property (immediately arising from the basic properties of the tensor product)
$$tr(TA_1A_2)= tr(T_1A_1)tr(T_2A_2) \quad \mbox{ for every $A_i\in R_i$, $i=1,2$.}$$
This property, which is stronger than $W^*$-independence, is called statistical independence.
We have so far seen that the standard representation of independent subsystems based on the notion of tensor product is in agreement with the general requirements (1),(2),(3) valid in whole generality for independent subsystems.
The natural question is the converse one, whether or not the structure of independent subsystems (requirements (1)-(3)) is always implementable by means of the notion of tensor product.
The answer is negative since there physically fundamental systems where the notion of tensor product is inappropriate to describe independent subsystems. Perhaps the most important case is that  of observables of a quantum field localized in two causally separated regions of the Minkowski spacetime. The associated von Neumann algebras satisfy (1), (2) and (3), but in general it is false that the algebra of observables generated by both regions (the overall system) is representable as a tensor product of von Neumann algebras over a corresponding tensor product of Hilbert spaces. (The tensor product can be used when a certain technical condition called split property is valid.)
Are there sufficient conditions assuring that (1),(2),(3) are implementable by the standard use of tensor product over a tensor product of Hilbert spaces?
There is an important result due to von Neumann which actually is valid in almost all situations of standard quantum mechanics (not QFT and thermodynamics of extended systems).
Suppose that

*

*(a) $R= B(\cal H)$,

*(b) $R_1$ is a type-I factor

*(c)  $R_2$ is made of all operators in $R$ which commute with all operators in $R_1$.

(b) deserves some explanation. $R_1$ is a factor if it does not includes non-trivial  operators which commute with all operators of $R_1$ (in other words there are no superselection rules). The requirement type-I is technical and means that $R_1$ is algebraically (not necessarily unitarily) isomorphic to some $B(\cal K)$ for some Hilbert space $\cal K$. This condition is always true if $\cal H$ is finite dimensional, and it is false in QFT where factors of type-III take place (and this is the reason for the above mentioned failure of the tensor product representation in QFT).
Under the hypotheses (a),(b), and (c), then (1),(2),(3) are valid and there exist a couple of Hilbert spaces $\cal H_1$, $\cal H_2$, a unitary operator $U: \cal H \to \cal H_1 \otimes \cal H_2$ such that $UR_1U^{-1} = B({\cal H_1})\otimes I_2$ and
$UR_2U^{-1} = I_1 \otimes B(\cal H_1)$.
This is the most common situation where the notion of tensor product is the fundamental building block to describe independent subsystems.

A: No, it's not obvious at all. The (essentially identical) answers here and here provide some nice justification. The key idea is that if we only do measurements on a single subsystem, then the probabilities that come out of the Born rule do not change if we multiply the subsystem's state vector by a complex number. The tensor product is the only way to combine subsystems together into new state vectors which preserves this property once we consider the joint system.

A: Great question!  I don't think there is anything obvious at play here.
In quantum mechanics, we assume that that state of any system is a normalized element of a Hilbert space $\mathcal H$.  I'm going to limit the discussion to systems characterized by finite-dimensional Hilbert spaces for conceptual and mathematical simplicity.
Each observable quantity of the system is represented by a self-adjoint operator $\Omega$ whose eigenvalues $\omega_i$ are the values that one can obtain after performing a measurement of that observable.  If a system is in the state $|\psi\rangle$, then when one performs a measurement on the system, the state of the system collapses to one of the eigenvectors $|\omega_i\rangle$ with probability $|\langle \omega_i|\psi\rangle|^2$.
The spectral theorem guarantees that the eigenvectors of each observable form an orthonormal basis for the Hilbert space, so each state $\psi$ can be written as
$$
  |\psi\rangle = \sum_{i}\alpha_i|\omega_i\rangle
$$
for some complex numbers $\alpha_i$ such that $\sum_i|\alpha_i|^2 = 1$.  From the measurement rule above, it follows that the $|\alpha_i|^2$ represents the probability that upon measurement of the observable $\Omega$, the system will collapse to the state $|\omega_i\rangle$ after the measurement.  Therefore, the numbers $\alpha_i$, although complex, do in this sense represent "relative abundance" as you put it.  To make this interpretation sharp, you could think of a state $|\psi\rangle$ as an ensemble of $N$ identically prepared systems with the number of $N_i$ elements in the ensemble corresponding to the state $|\omega_i\rangle$ equaling $|\alpha_i|^2 N$.
Now suppose that we have two quantum systems on Hilbert spaces $\mathcal H_1$ and $\mathcal H_2$ with observables $\Omega_1$ and $\Omega_2$ respectively.  Then if we make a measurement on the combined system of both observables, then system 1 will collapse to some $|\omega_{1i}\rangle$ and system 2 will collapse to some state $|\omega_{2 j}\rangle$.  It seems reasonable then to expect that the state of the combined system after the measurement could be any such pair.  Moreover, the quantum superposition principle tells us that any complex linear combination of such pair states should also be a physically allowed state of the system.  These considerations naturally lead us to use the tensor product $\mathcal H_1\otimes\mathcal H_2$ to describe composite system because it is the formalization of the idea that the combined Hilbert space should consists of all linear combinations of pairs of states in the constituent subsystems.
Is that the sort of motivation for using tensor products that you were looking for?

A: Actually the story of the tensor product, which is typically told as an axiom in the world of quantum information, comes from the relativistic electron theory of Dirac.
In relativistic quantum mechanics one wavefunction is replaced by 4 wavefunctions, and a suitable contraction leads to a two-element array (1,0) or (0,1) which we call the spin.
In the case of 2 electrons the same theory leads to a 16-component wavefunction, and after some trimming we can get down to a 4 component object (called Pauli spinor for 2 electrons). This object and the various operations with the Hamiltonian are best described (in terms of algebra) by using tensor product of the states (1,0) and (0,1).
Obviously these tensor product correspond to spins, and since the idea of qubit comes from that of spin, the idea of tensor composition is now taken axiomatically in QIP.

A: I think it is pretty obvious. Correct me if my argument is wrong somewhere.
In the classical case, if you want to describe e.g. the x-positions of two particles, you have a two-dimensional phase space to show the possible states -- and two is the sum of one and one. But a quantum state space is very different -- every point in the $x_1$ "axis" is a basis vector of its own, and likewise for $x_2$ -- the state vectors we speak of are vectors in the Hilbert space, and can be shown as distributions mapped on this $(x_1,x_2)$ plane, representing them as superpositions of these basis vectors.
So it makes perfect sense that the dimension of the product space is the product of the dimensions and not the sum. The total number of points in the $(x_1,x_2)$ plane -- which is the dimension of this new Hilbert space -- is the product of the number of points on the $x_1$ axis and the $x_2$ axis.
It's clear that the probabilities are multiplicative. Given states $|\phi\rangle=\sum p(x)|x\rangle$ and $|\psi\rangle=\sum q(y)|y\rangle$ in bases $|x\rangle$ and $|y\rangle$, it is clear that the magnitudes of the components of the state $$|\phi\rangle\otimes|\psi\rangle=\sum r(x,y)|x\rangle\otimes|y\rangle$$ where $\otimes$ (is the desired product representing composition) of the combined system are $|r(x,y)|^2=|p(x)q(y)|^2$. But -- as you ask in your question -- how do we know that $r(x,y)=p(x)q(y)$?
The idea is quite simple, though -- suppose we have a state like
$$\left( {\frac{1}{{\sqrt 2 }}\left| x \right\rangle  + \frac{1}{{\sqrt 2 }}\left| y \right\rangle } \right) \otimes \left| z \right\rangle  = \frac{u}{{\sqrt 2 }}\left| x \right\rangle  \otimes \left| z \right\rangle  + \frac{v}{{\sqrt 2 }}\left| y \right\rangle  \otimes \left| z \right\rangle $$
Because we're representing two independent systems, we can just observe the first system, collapsing it to $|x\rangle$: then the combined state based on the left-hand-side is collapsed to $|x\rangle\otimes|z\rangle$. But based on the right-hand-side, this is $u|x\rangle\otimes|z\rangle$, and thus $u=1$ and similarly for $v$.


text:
Q: HPA on AZURE AKS but pod are immediately going in terminating state because it showing not able to find out default volume to mount enter image description hereI'm trying to implement HPA in my project, such that whenever CPU utilization is above 15% it should auto scale pods, but HPA is working, it is creating pods but pods are going from container creating state to terminate state within a second, as pods are terminating so not able to see any pod related logs also, but  kubectl get events is showing:
"**Error: cannot find volume "default-token-chcXX" to mount into container, Unable to attach or mount volumes: unmounted volumes=[default-token-chcXX[\][1], unattached volumes=[default-token-chcXX]: timed out waiting for the condition** "

error sample

apiVersion: apps/v1
kind: Deployment
metadata:
  name: XXX
  namespace: XXX
spec:
  selector:
    matchLabels:
      app: XXX
  replicas: 2
  template:
    metadata:
      labels:
        app: XXX
      annotations:
        timestamp: "{{ .Values.metadata.annotations.timestamp }}"
    spec:
      containers:
      - name: gui
        image: ""1.0"
        volumeMounts:
        - mountPath: /var/run/secrets/kubernetes.io/serviceaccount
          name: default-token-chcXX
          readOnly: true
imagePullPolicy: Always
        resources:
          limits:
            memory: 300m
            cpu: 512Mi
         requests:
            memory: 300m
            cpu: 512Mi
     nodeSelector:
        agentpool: XXX
      tolerations:
      - key: pool-name
        operator: Equal
        value: XXX
        effect: NoSchedule
      volumes:
      - name: default-token-chcXX
        secret:
          defaultMode: 420
          secretName: default-token-chcXX

A: i think your pod is crashing due to the as your secrets and config maps will be mounted as read-only volumes.
Kubernetes add its own secret at /run/secrets/kubernetes.io/serviceaccount/ it is unable to place them as /run/secrets is read-only.
Due to that maybe your pod crashes.
maybe readOnly: false won't work.
Before everything else first check your secret and volume exist as error is showing : cannot find volume "default-token-chcXX" to mount into container
what may be you can try out is to use subpath
apiVersion: v1
kind: Secret
metadata:
  name: test-secret
data:
  test: <YOUR DATA>
type: Opaque
---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: test
spec:
  selector:
    matchLabels:
      app: test-nginx
  replicas: 1
  template:
    metadata:
      labels:
        app: test-nginx
    spec:
      containers:
      - name: nginx
        image: nginx
        imagePullPolicy: Always
        volumeMounts:
        - name: secret-volume
          mountPath: "/run/secrets/test"
          subPath: test
      volumes:
      - name: secret-volume
        secret:
          secretName: test-secret
          items:
          - key: test
            path: "test"

Issue : https://github.com/kubernetes/kubernetes/issues/60814


text:
Q: why magento rest api returning more order items than ordered? I placed order using magento graphQL api, order placed successfully and listed in my orders section in website. I placed order of 1 product. In website's order detail page it displaying 1 item ordered. But when I fetch order items data using rest api rest/default/V1/orders/000000004, it gives me 2 item ordered.
I think there may be something naming issue, because I ordered,
product name : Portia Capri
size : 29
color : Green

Now, when I fetch ordered items data using rest api it returning 2 items which includes Portia Capri and Portia Capri-29-Green.
Please anyone can help me how to get only ordered item ?

A: When place order configurable product then magento create 2 entry sales_order_item
Check this Query
SELECT * FROM `sales_order_item` WHERE `order_id` = 'your_order_id'


text:
Q: Node JS callbacks executing in sychronously I have this code in node js
var PrintFirstName = function(first_name , cb) {
    cb("First name  is "+first_name) ;
}
PrintFirstName("Tushar" , function(res){
    for(var i = 0 ; i < 100000; i++) {
        console.log(i);
    }
    console.log("processing callback");
});
console.log("Code continue....") ;

As callbacks are asynchronous in nature , my expected order of execution should be Code continue , numbers 1-10000 and then processing  callbacks
But if i run the above i am getting output as numbers 1-10000 , processing  callbacks and then Code continue . Code continue should be executed first.Why it is waiting for callbacks to complete.

A: The code you wrote  is not asynchronous, usually async functions in javascript requires constructing the expression argument to setTimeout or setInterval manually.
In your case:
var PrintFirstName = function(first_name , cb) {
    cb("First name  is "+first_name) ;
}

PrintFirstName("Tushar" , function(res){
        for(var i = 0 ; i < 100000; i++) {
            console.log(i);
        }
 setTimeout(function() {        console.log("processing callback");}, 0);
});

console.log("Code continue....") ;

But keep in mind that this will not work when making calls on Object methods
Take a look here http://devedge.primedirective.net/toolbox/examples/2003/CCallWrapper/index.html


text:
Q: How get data in the exist clause I am trying to get data from table rem2 but I am unsuccessful. How am I to do this?
SELECT *, rem2.id FROM remuneracao_performance_competencia AS competencia
JOIN remuneracao_performance AS rem1 ON competencia.remuneracao_performance_id = rem1.id
WHERE EXISTS (
    SELECT 1 FROM remuneracao_performance AS rem2 WHERE
        rem1.id <> rem2.id and rem1.cargo_id = rem2.cargo_id AND rem1.frequencia_campanha = rem2.frequencia_campanha AND rem1.modelo_remuneracao = rem2.modelo_remuneracao AND competencia.remuneracao_performance_id <> rem2.id AND rem2.inicio_vigencia_campanha <= competencia.inicio_vigencia and rem2.inicio_vigencia_campanha > rem1.inicio_vigencia_campanha
        ORDER BY rem2.inicio_vigencia_campanha DESC)
ORDER BY cargo_id ASC

The error message is

Error Code: 1051. Unknown column 'rem2.id' in 'field list

A: I changed my query to:
select distinct competencia.*, rem2.id from remuneracao_performance_competencia as competencia
join remuneracao_performance as rem1 on competencia.remuneracao_performance_id = rem1.id,
     remuneracao_performance as rem2
where
rem1.id <> rem2.id and
rem1.cargo_id = rem2.cargo_id and rem1.frequencia_campanha = rem2.frequencia_campanha and
rem1.modelo_remuneracao = rem2.modelo_remuneracao and competencia.remuneracao_performance_id <> rem2.id and
rem2.inicio_vigencia_campanha <= competencia.inicio_vigencia and
rem2.inicio_vigencia_campanha > rem1.inicio_vigencia_campanha
group by competencia.id, rem1.cargo_id


text:
Q: How to add a multi line text to a JButton with the line unknown? (dynamically) How do you make the text on a JButton multiline?  I have read that most use HTML, but what happens when it is dynamic and you don't know the size of the lines, or what the lines are?
Right now the text on my button just ends with ...  as opposed to making a new line.
Most other methods assume you know the string and are hard coded, so you can't do this on the fly.
Edited: I created a method that will do this dynamically for a button

A: You'll need to at least know how each line is delimited. For example if lines are delimited with newline characters, you could do:
String twoLines = "Two\nLines";
JButton b =
    new JButton("" + twoLines.replaceAll("\\n", "
") + "");


text:
Q: MySql Insert Into Select Sum TABLE ONE DATA - po_header

PO_ID   PROJ_ID SUP_ID  TOT_SUM         SUBM_DATE
32      5555    AccAYOU 99.00           2016-11-29
33      5555    AccAYOU 990.00          2016-11-29
34      25412   AccAYOU 248778595.08    2016-11-30

TABLE TWO DATA - po_details

PO_ID   amount
32      110.00
33      1500000.00
34      565079266.00
34      1.00

How can I Run the following SQL ?
    INSERT INTO po_header (TOT_SUM) VALUES (SELECT SUM(amount)
    FROM po_details WHERE PO_ID = '34') WHERE PO_ID ='34';

A: Even it's un correct syntax but this is what you want:
UPDATE po_header h
 SET TOT_SUM = (Select sum(amount) From po_details d Where d.po_id = h.po_id)

A:
UPDATE po_header SET TOT_SUM = (SELECT SUM(amount) FROM po_details WHERE PO_ID='34') WHERE PO_ID='34';


text:
Q: How to place captcha on Django CreateView that uses Material Design Layout() feature I'm working in an existing codebase that uses Django Material.  There is a CreateView defined with a Django Material Layout:
class OurModelCreateView(LayoutMixin, CreateView):
    model = OurModel

    layout = Layout(
        Row('field1', 'field2', 'field3'),
        Row(...)
    )

This view is getting lots of spam signups and so needs to have a captcha.  I use Django Recaptcha, and I've set up a number of captchas in the past.  However, I've never set one up without using a ModelForm.  If I create a Django model form and define the captcha field in the form as I've always done:
from captcha.fields import ReCaptchaField
from captcha.widgets import ReCaptchaV3

class OurModelForm(ModelForm):

captcha = ReCaptchaField(widget=ReCaptchaV3)

    class Meta:
        model = OurModel
        exclude = ()

and then specify form_class = OurModelForm on the CreateView, the following error is raised by ModelFormMixin.get_form_class():  "Specifying both 'fields' and 'form_class' is not permitted".  This error is being raised because, though I've not explicitly specified fields, Django Material's LayoutMixin defines fields:  https://github.com/viewflow/django-material/blob/294129f7b01a99832a91c48f129cefd02f2fe35f/material/base.py  (bottom of the page)
I COULD drop the Material Layout() from the CreateView, but then that would mean having to create an html form to render the Django/Django Material form - less than desirable as there are actually several of these CreateViews that need to have a captcha applied.
So I think that the only way to accomplish what I'm after is to somehow dynamically insert the captcha field into the form.
I've dynamicaly inserted fields into Django forms in the past by placing the field definition in the __init__() of the Django form definition, but I can't figure out what to override in either CreateView (or the various mixins that comprise CreateView) or Django Material's LayoutMixin in order to dynamically insert the captcha field into the form.  The following several attempts to override get_form and fields in order to dynamically insert the captcha field do not work:
   On the CreateView:
       def get_form(self, form_class=None):
           form = super(OurModelCreate, self).get_form(form_class)
           form.fields['captcha'] = ReCaptchaField(widget=ReCaptchaV3)
           return form

       def fields(self):
           fields = super().fields(*args, **kwargs)
           fields['captcha'] = ReCaptchaField(widget=ReCaptchaV3)
           return [field.field_name for field in fields

       # fields is actually a list, so trying the following too, but it doesn't include the ReCaptchaField(widget=ReCaptchaV3) anywhere at this point
       def fields(self):
           fields = super().fields(*args, **kwargs)
           fields.append('captcha')
           return fields

Any help would be greatly appreciated.

A: Following up on the comment from @Alasdair above which pointed me to the answer, I solved this problem by removing Django Material's LayoutMixin from CreateView, creating a Django form with the captcha field defined, and then adding to CreateView the form_class for the Django form.  Also see my last comment above.  It was counterintuitive to me until I looked again at the code after @Alasdair's second comment:  the use of LayoutMixin on the CreateView isn't necessary for the layout = Layout(...) on the CreateView to work.


text:
Q: Python 3.4 : How to do xml validation I'm trying to do XML validation against some XSD in python. I was successful using lxml package. But the problem starts when I tried to port my code into python 3.4.
I tried to install lxml for 3.4 version. Looks like my enterprise linux doesn't play very well with lxml.
pip installation:
pip install lxml
Collecting lxml
  Downloading lxml-3.4.4.tar.gz (3.5MB)
    100% |################################| 3.5MB 92kB/s
Installing collected packages: lxml
  Running setup.py install for lxml
Successfully installed lxml-3.4.4

After pip Installation :
> python
Python 3.4.1 (default, Nov 12 2014, 13:34:29)
[GCC 4.1.2 20080704 (Red Hat 4.1.2-48)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> from lxml import etree
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: /ws/satjonna-sjc/pyats/lib/python3.4/site-packages/lxml/etree.cpython-34m.so: undefined symbol: xmlMemDisplayLast
>>>

git installation:
git clone git://github.com/lxml/lxml.git lxml
Cloning into 'lxml'...
remote: Counting objects: 25078, done.
remote: Total 25078 (delta 0), reused 0 (delta 0), pack-reused 25078
Receiving objects: 100% (25078/25078), 21.38 MiB | 2.66 MiB/s, done.
Resolving deltas: 100% (9854/9854), done.
Checking connectivity... done.

After git Installation :
> python
Python 3.4.1 (default, Nov 12 2014, 13:34:29)
[GCC 4.1.2 20080704 (Red Hat 4.1.2-48)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> from lxml import etree
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: cannot import name 'etree'

I found lxml equivalent xml.etree.ElementTree. But the main problem is apart from rewriting the entire code, I need to find an xml.etree alternative  for lxml validation moethod ( etree.fromstring(xmlstring, xmlparser) ).
Any suggestions to make this work will be really helpful.

A: Just for the sake of troubleshooting, did you run pip install lxml as administrator?  And are the libxml2 and libxslt dependencies installed?
This is from the installation page:
http://lxml.de/installation.html
On Linux (and most other well-behaved operating systems), pip will manage to build the source distribution as long as libxml2 and libxslt are properly installed, including development packages, i.e. header files, etc. See the requirements section above and use your system package management tool to look for packages like libxml2-dev or libxslt-devel. If the build fails, make sure they are installed.
Alternatively, setting STATIC_DEPS=true will download and build both libraries automatically in their latest version, e.g. STATIC_DEPS=true pip install lxml.


text:
Q: How can I provide an editable default value when prompting for user input? In a Perl script, I want to prompt the user for input and offer him an editable default value. So far I have this:
#!/usr/bin/perl

print "what's your name? [John Doe]: ";
$name = <STDIN>;
chomp $name;
if (!$name)
{
    $name = "John Doe";
}
print "hello $name.\n";

What I'm looking for is a solution where I can have "John Doe" on STDIN already before the user starts typing. So it's practically an editable default input. E.g. the user could press backspace 3x and then type "Wayne" to get "John Wayne" rather than typing the whole string "John Wayne" from beginning on. I tried to print to STDIN, but that didn't work.

A: You by definition cannot write to stdin.  You're going to have to use something like Term::ReadLine::Gnu.
The feature you are looking for is called PREPUT, it is the second argument to the readline function.

A: # Try this. It worked for me on Windows 10, Perl 5.32
use Term::ReadLine;  # Do not "use Term::ReadLine::Gnu;"
my $term ;
my $prompt = "Enter a name: " ;
my $name   = "John Doe" ;
$term = Term::ReadLine->new('Test script', \*STDIN, \*STDOUT);
$name = $term->readline($prompt,$name) ;
print "\nThe name is $name" ;


text:
Q: Error to report with median and graphical representations? I've used a wide array of tests for my thesis data, from parametric ANOVAs and t-tests to non-parametric Kruskal-Wallis tests and Mann-Whitneys, as well as rank-transformed 2-way ANOVAs, and GzLMs with binary, poisson and proportional data. Now I need to report everything as I write all of this up in my results.
I've already asked here how to report asymmetrical confidence intervals for proportion data. I know that standard deviation, standard error or confidence intervals are appropriate for means, which is what I'd report if all my tests were nicely parametric. However, for my non-parametric tests, should I be reporting medians and not means? If so, what error would I report with it?
Associated with this is how best to present non-parametric test results graphically. Since I largely have continuous or interval data within categories, I'm generally using bar graphs, with the top of the bar being the mean and error bars showing 95% CI. For NP tests, can I still use bar graphs, but have the top of the bar represent the median?
Thanks for your suggestions!

A: You can report a confidence interval for the median.  In R, you can use wilcox.test with the argument conf.int=TRUE.  There's a tiny discussion of this in John Verzani's simpleR notes: see here.
Regarding plots: I don't really like using bar plots even for representing a set of means.  I'd prefer to just plot little line segments for the CI:

The plot on the right was made with errbar() from the Hmisc package [CRAN page].
You could make the same sort of plot for the medians and the related confidence intervals, or you could use box plots (which, in the same amount of space, describe the entire distribution).