Calculos dinâmicos no Rails

Question: espero que possam me ajudar.
Eu tenho um Avaliado que possui avaliações, tenho diversos cálculos para determinar se esse passará ou não por uma etapa da avaliação.
Por exemplo um desses cálculos é  calcula_pontuacao_minima()
#Cálculo definido pela resolução 1
def calcula_pontuacao_minima(avaliado)
  calcula_porcentagem(avaliado.avaliacoes)>60 #onde esta soma todas as notas do avaliado e retorna a porcentagem de aproveitamento
end

Meu problema aqui é o aparecimento de resoluções que alteram o calculo, de modo que todos os avaliados antes dessa resolução, devem ser avaliados pelos cálculos antigos e os novos avaliados devem ser classificados utilizando-se os cálculos alterados. Por exemplo uma resolução altera o valor mínimo para 50%
#Cálculo definido pela resolução 2
def calcula_pontuacao_minima(avaliado)
  calcula_porcentagem(avaliado.avaliacoes)>50 #onde esta soma todas as notas do avaliado e retorna a porcentagem de aproveitamento
end

E se em um futuro ainda alterem para ao invés de pegar a porcentagem, o valor mínimo seja comparado ao valor total das avaliações
#Cálculo definido pela resolução 3
def calcula_pontuacao_minima(avaliado)
  calcula_total(avaliado.avaliacoes)>70 #onde esta soma todas as notas do avaliado onde o máximo é 120
end

Assim por exemplo Avaliados que tiveram suas avaliações realizadas antes da data X que definiu a resolução 2, vão ser avaliados pelo primeiro calculo, após essa data X serão avaliados pelo segundo cálculo, e depois da data Y onde entrou em vigor a resolução 3, serão avaliados pelo terceiro calculo.
Alguma ideia de como isso pode ser solucionado? Seria uma boa armazenar os cálculos a nível de banco de dados?
Comment: Todos os avaliados antes da resolução... Que foram criados antes da resolução ou existe algum outro campo de data que é relativo a criação da resolução?
Comment: Então vou adicionar como eu faria, daí você vê se a resposta se adequa ao que você quer.
Comment: Os cáculos mudarão com que constância? O usuário precisa mudá-los ou pode ser uma coisa feita pelo desenvolvedor?
Comment: Nao é utópico, com eval é facil de fazer até, desde que vc tome os cuidados de não deixar o usuário entrar com dados perigosos.
Comment: @FelipeAvelar existem campos que serão criados pós resolução =\
Comment: @AlexTakitani bom, utopicamente o usuário deveria mudar, mas julgo inviável criar algo nesse nível. Sendo assim uma boa solução onde o dev possa realizar essa alteração de uma forma Ruby Like, já seria a solução que busco.
Comment: O conceito de Strategy existe no Ruby?
Answer: A resolução que eu faria seria utilizar um campo criado (que segundo seu comentário, serão criados depois) ou o campo created_at e baseado na data de criação da resolução (considerando que você tenha uma tabela de resoluções ou as datas em que elas foram), eu utilizaria apenas as datas de criação das resoluções, considerando, por exemplo, uma data X para a resolução 1, uma data Y para resolução 2 e Z para a resolução 3. Caso você queira rodar o método para cada avaliado, seria dessa forma:
def calcula_pontuacao_minima(avaliado)
  if(avaliado.created_at < Y)
    return calcula_total(avaliado.avaliacoes) > 60
  elsif (avaliado.created_at >= Y && avaliado.created_at < Z)
    return calcula_total(avaliado.avaliacoes) > 50
  else
    return calcula_total(avaliado.avaliacoes) > 70
  end
end

Caso você queira fazer para todos de uma vez (o que eu aconselho), o ideal seria fazer da seguinte forma:
def calcula_pontuacao_minima
  resultado = []
  Avaliado.where('created_at < ?', Y).all.each do |avaliado|
    a.push(calcula_total(avaliado.avaliacoes) > 60)
  end
  Avaliado.where('created_at >= ? AND created_at < ?', Y, Z).all.each do |avaliado|
    a.push(calcula_total(avaliado.avaliacoes) > 60)
  end
  Avaliado.where('created_at >= ?', Z).all.each do |avaliado|
    a.push(calcula_total(avaliado.avaliacoes) > 60)
  end
  return a
end

Não sei se é isso o que você quer, mas foi o que eu consegui inferir da sua pergunta.
Comment: Obrigado pela resposta @Felipe, bom. Isso é um dos fatores que queria evitar, pois imagine que durante a vigência do sistema 50 resoluções sejam criadas? teria então um where para cada resolução. Minha dúvida era só se existe uma forma mais DRY de fazer isso. Não existindo sua resposta está valendo.
Comment: Nesse caso, você poderia colocar uma tabela só para resoluções e utilizá-las em um `each` ou passar uma lista de datas de resoluções e fazer dentro de um `each` para cada elemento dessa lista. Essas são as formas que eu vejo...

Calculos dinâmicos no Rails


Drupal form won't save with TinyMCE (Firefox only)

Question: I have a Drupal form with a TinyMCE (3.5.6) instance on it, this is instantiated via the Wysiwyg module. If I save the form in Firefox, it visually displays an AJAX spinner but nothing happens, the form does not save and leaves me on the form. All other browsers work. I can get it to work 2 different ways but not sure why it works and how to translate that to a permanent fix. I have been going through all the suggestions in http://www.tinymce.com/forum/viewtopic.php?id=18821 but have not been successful yet.
1.) If I unminify the code with http://jsbeautifier.org it works without throwing console errors but JSLint throws tons of lint errors in the code.
2.) If I delete the code below it works,
<textarea rows="3" cols="60" name="field_caption[und][0][value]" id="edit-field-caption-und-0-value" class="text-full form-textarea" style="display: none;" aria-hidden="true"></textarea>it works but with the below error:

but throws this error.
NS_ERROR_UNEXPECTED: Component returned failure code: 0x8000ffff (NS_ERROR_UNEXPECTED) [nsIDOMHTMLDocument.implementation]
http://loc.dbtv.nbcuni.com/sites/all/libraries/tinymce/jscripts/tiny_mce/tiny_mce.js?mhcuev
Line 1

Here is a video of the issue at hand => https://docs.google.com/file/d/0B47tip0c_KEtY2w1akUtcFZHYUU/edit
Comment: Crosslinking to issue on Drupal.org http://drupal.org/node/1907756
Answer: The main fix is linked to in comment #6 of the TinyMCE bugtracker here => http://www.tinymce.com/develop/bugtracker_view.php?id=3152
The source fix is in comment #4 but that won't help many since you need to have an environment to actually compile TinyMCE.


Set of numbers with interesting property

Question: There is an interesting property with the set $(2,2)$
$$2 + 2 = 4$$
$$2\times2 = 4$$
$$2^2 = 4$$
I am wondering is (2,2) the only set with this property.
For example, consider the set $(1,2,3)$
$$1+2+3=6$$
$$1\times2\times3=6$$
$$1^{2^3}=1$$
so this does not work.
If we restrict the number to integers, we can see the numbers have to be the power of the same number so with simple inequality this clearly wouldn't work for any other set other than $(2,2)$, but in the case of real numbers, it seems plausible that other sets might exist.
Comment: Even $xy=x+y$ would have only one solution over the positive integers. But whether we can do it with real numbers, is interesting.
Comment: If I did not make a mistake , we  have to solve $$x^{\frac{1}{x-1}}=\frac{1}{x-1}+1$$ and this seems to have only the solution $x=2$. But the case with $3$ numbers is even more exciting.
Comment: (101, 1.01) is another $xy=x+y$ solution but that sadly does not work for the exponentiation case.
Answer: The three variable case has infinite solutions in the real numbers.
Steps for the solution:
Solve for z:$$z=\frac{x+y}{x\ y-1}$$
Plot (using software) the equation $$x+y+z-x^{y^z}\ =\ 0$$
Subsituting for z.
The two variable case has only one solution using analogous logic.
Answer: If your set has only two numbers, the only possibility is $(2,2)$. Imagine there is two numbers, the first number is the number of stars and the second number is the number of squares. We can always assume that the number of squares is bigger than the number of stars.
When you add up the two numbers, the total number of shapes is at most $2$ units. Here one unit is the number of squares.
When you multiply, the number of units is the number of stars.
If there is only $1$ star, the product will be lesser than the sum by $1$. So there cannot be $1$ star.
If there are at least $2$ stars, then the product has at least $2$ units. So the product is at least equal to the sum.
For the product to be equal to the sum, there be exactly $2$ units. So there are exactly $2$ stars and exactly $2$ squares. Therefore the only possible set is $(2, 2)$.
You have already checked that $(2, 2)$ works.


Problema com o Isotope e o loadmore

Question: Eu customizei um scritp de isotope com a função de "loadmre".
Está funcionando corretamente, mas, ao clicar em qualquer um dos filtros, a classe "hidden" é removida e fica um "buraco" no rodapé.
Eu tentei mudar no Jquery a instrução para adicionar a classe, mas não consegui.
Se clicar em "banheiros", por exemplo, é possível ver o que ocorre.
Código no Codepen
Answer: Adicione à classe <code>.isotope</code> a propriedade abaixo:
<code>.isotope{
   overflow: hidden;
}
</code>
Isso irá restringir a área da div apenas aos elementos visíveis.

Problema com o Isotope e o loadmore


Path of all possible lengths $1, \ldots n - 2$ on $(n - 1)$-cycle

Question: There is cycle with $n - 1$ vertices. $\ge \frac{n}{2}$ vertices are selected. Prove that paths of all the possible lengths from $1, 2, \ldots, n - 2$ can be drawn between selected vertices.
It is easy to see that paths with lenghts $1$ and $n - 2$ can be drawn but what about possibility to draw path of arbitrary length $k$, $1 \le k \le n - 2$?
This is part of some other proof.
Comment: This is your 11th question and you've accepted none of the answers given to you. Maybe you've only been received bad or no answers, but I, for one, will not bother answering this question since I can see there is little hope of being rewarded.
Answer: It seems the following.
Enumerate the vertices along the cycle by residues $\mod n-1$. Fix the number $k$. The vertices $v_i$ and $v_j$ we call equivalent, provided $i-j\in k\Bbb Z_{n-1}$. Then the sets of the vertices of the cycle is partitioned into equivalency classes. Since the quantity of selected vertices is larger than a half of the quantity of all vertices, there is an equivalency class $C$ in which the quantity of selected vertices is larger than a half of the quantity of all vertices. Pick an arbitrary vertex $v_i\in C$. Imagine the class $C$ as a cyclic sequence $v_i-v_{i+k}-v_{i+2k}-\dots-v_{i-k}-v_i$. Since in $C$ the quantity of selected vertices is larger than a half of the quantity of all vertices, there exists a number $l$ such that both vertices $v_{i+lk}$ and $v_{i+(l+1)k}$ are selected. Then the path between these vertices has length $k$.
Comment: It would be improvement to this answer if the phrase "of all vertices" would be more specific and more clear "of all vertices in the congruence class" in some places. But otherwise - thanks!


Why isn't MongoDB using my Text index?

Question: I've got a Mongo collection with 1691721 items within it, containing essentially location information. I'm attempting to do a regex search into this, and it's pretty slow - but I don't understand why, as I thought I had appropriate indexes in place.
A typical document
{
    "_id" : ObjectId("58c08029ef4468c8157455fa"),
    "ng" : [
        394235,
        806529
    ],
    "postcode" : "AB101AB"
}

Indexes
I've created a text index on the postcode field, which you can see here in the full list of indexes:
db.locations.getIndexes()
[
        {
                "v" : 2,
                "key" : {
                        "_id" : 1
                },
                "name" : "_id_",
                "ns" : "Traders.locations"
        },
        {
                "v" : 2,
                "key" : {
                        "_fts" : "text",
                        "_ftsx" : 1
                },
                "name" : "postcode_text",
                "ns" : "Traders.locations",
                "weights" : {
                        "postcode" : 1
                },
                "default_language" : "english",
                "language_override" : "language",
                "textIndexVersion" : 3
        }
]

Query
At this point in time, all I care about is the postcode field. So I've tried writing a query to obtain the last value:
db.locations.find({ postcode: { $regex: /^ZE29XN$/ } }, { postcode: 1, _id: 0 })

Now this takes a while to run, roughly 700ms to be precise which is a lot longer than I was expecting. As far as I was concerned this is a covered query, I've got a text index on the single field I care about. However if I explain the above query it suggests it's using a COLLSCAN, but I don't understand why:
db.locations.find({ postcode: { $regex: /^ZE29XN$/ } }, { postcode: 1, _id: 0 }).explain("allPlansExecution")
{
        "queryPlanner" : {
                "plannerVersion" : 1,
                "namespace" : "Traders.locations",
                "indexFilterSet" : false,
                "parsedQuery" : {
                        "postcode" : {
                                "$regex" : "^ZE29XN$"
                        }
                },
                "winningPlan" : {
                        "stage" : "PROJECTION",
                        "transformBy" : {
                                "postcode" : 1,
                                "_id" : 0
                        },
                        "inputStage" : {
                                "stage" : "COLLSCAN",
                                "filter" : {
                                        "postcode" : {
                                                "$regex" : "^ZE29XN$"
                                        }
                                },
                                "direction" : "forward"
                        }
                },
                "rejectedPlans" : [ ]
        },
        "executionStats" : {
                "executionSuccess" : true,
                "nReturned" : 1,
                "executionTimeMillis" : 732,
                "totalKeysExamined" : 0,
                "totalDocsExamined" : 1691721,
                "executionStages" : {
                        "stage" : "PROJECTION",
                        "nReturned" : 1,
                        "executionTimeMillisEstimate" : 697,
                        "works" : 1691723,
                        "advanced" : 1,
                        "needTime" : 1691721,
                        "needYield" : 0,
                        "saveState" : 13223,
                        "restoreState" : 13223,
                        "isEOF" : 1,
                        "invalidates" : 0,
                        "transformBy" : {
                                "postcode" : 1,
                                "_id" : 0
                        },
                        "inputStage" : {
                                "stage" : "COLLSCAN",
                                "filter" : {
                                        "postcode" : {
                                                "$regex" : "^ZE29XN$"
                                        }
                                },
                                "nReturned" : 1,
                                "executionTimeMillisEstimate" : 676,
                                "works" : 1691723,
                                "advanced" : 1,
                                "needTime" : 1691721,
                                "needYield" : 0,
                                "saveState" : 13223,
                                "restoreState" : 13223,
                                "isEOF" : 1,
                                "invalidates" : 0,
                                "direction" : "forward",
                                "docsExamined" : 1691721
                        }
                },
                "allPlansExecution" : [ ]
        },
        "serverInfo" : {
                "host" : "DESKTOP",
                "port" : 27017,
                "version" : "3.4.2",
                "gitVersion" : "3f76e40c105fc223b3e5aac3e20dcd026b83b38b"
        },
        "ok" : 1
}

My Question
Why is the text index I've created not being used, and ultimately how can I make my query faster?
I should note that I'm open to alternative to using the $regex however I do need to be able to allow for a "starts with" - so ZE.* or ZE2.* or ZE29XN should all be searchable at speed.
Something potentially useful to note, I wondered if when I eventually get my index working, that marking it as unique: true might help speed things up. However running it produced a duplicate key error (despite the fact I can't find one when I run an aggregation - can dig into this if need be, but I'm not sure it's related).
Comment: Is that the regex you're using? Are you using case insensitivity?
Comment: @Shaded that was the Regex that I was using - that `explain` is an exact paste. I haven't specified case insensitivity anywhere (docs suggest case sensitve allows index use https://docs.mongodb.com/manual/reference/operator/query/regex/#index-use), I'm manually upper casing everything before getting to Mongo.
Answer: A quick summary of text search operators in MongoDB:

$regex: provides regular expression capabilities for pattern matching strings in queries. The $regex operator does support partial matches but it will only be index covered if the search string is anchored (i.e. uses a leading ^).
$text: performs a text search on the content of the fields indexed with a text index (use of the $text operator is a necessary precondition for MongoDB to use a text index). These searches are typically 'fast' (subjective term but when you have one working you'll see what that means) but they do not support partial matches so you won't be able to 'text search' for partial postcodes.

With that in mind it looks like you are attempting to use partial matching (via $regex) against a text index. This will not work because a text index is only engaged for the $text operator.
Your stated requirements are:

You want partial string matches
You want index coverage

You can meet these requirements by (1) using $regex and (2) indexing (a normal index not a text index) the postcode field. This is subject to one (important!) caveat: your search strings must be anchored. So this requirement: "need to be able to allow for a "starts with" - so ZE.* or ZE2.* or ZE29XN" should be fine. But a search such as: .*29XN will not be index covered.
Comment: Thanks, that looks like it covers exactly what I was missing. I guess I must have assumed at some point that the string field needed a text index, which seems to not be the case. I'll give it a try as soon as I can and confirm by accepting.
Comment: it says ""unknown operator: $text", is this information old?

Why isn't MongoDB using my Text index?


Trying to call an image from a custom function

Question: I am trying to display an image from a function and then while loop. Image is not getting displayed. I have made the function in functions.php and called this file in config.php. Finally config.php is called in header.php file, means functions.php file is now accessable everywhere. Every other details is coming, just image is not getting displayed
my function
function get_featured_image($p_id) {
    global $con;

    // First, get the image_id from the products table
    $featured_image_query   = mysqli_query($con, "SELECT images_id FROM products WHERE id = $p_id");
    $featured_image         = mysqli_fetch_assoc($featured_image_query);

    if ($featured_image) {
        $image_id = $featured_image['images_id'];

        // Next, fetch the image details from the images table based on the image_id
        $image_query    = mysqli_query($con, "SELECT * FROM images WHERE image_id = $image_id");
        $image_data     = mysqli_fetch_assoc($image_query);

        if ($image_data) {
            return $image_data['file_name'];
        }
    }

    return ""; // Return an empty string if no featured image is found
}

My While Loop Where i want to display the image

<?php
$productscount = 0;
while ($products = mysqli_fetch_object($product_query)) {
$product_id = $products->id;
$featured_image = get_featured_image($product_id);
?>
<a href="product_details.php?id=<?php echo $products->id; ?>">
 <img src="images/products/<?php echo $featured_image; ?>" class="img-fluid blur-up lazyload" alt="">

<?php } ?>

M
Comment: **Warning:** You are wide open to [SQL Injections](https://php.net/manual/en/security.database.sql-injection.php) and should use parameterized **prepared statements** instead of manually building your queries. They are provided by [PDO](https://php.net/manual/pdo.prepared-statements.php) or by [MySQLi](https://php.net/manual/mysqli.quickstart.prepared-statements.php). Never trust any kind of input! Even when your queries are executed only by trusted users, [you are still in risk of corrupting your data](http://bobby-tables.com/). [Escaping is not enough!](https://stackoverflow.com/q/32391315)
Comment: `SELECT file_name FROM products as p join images using(image_id) WHERE p.id = ?` will remove 1 query, and fix SQL injections if put into a prepared statement and bound.
Comment: What does the `src` attribute come out as when you load the page? Sounds like the path for image is wrong.. use developer console to see what is being requested, and what the rendered source is.
Comment: I have double checked path, images are moving into images/products and getting inserted into database also. On front end, i can see only a broken image. in console there is no info as well
Comment: by error reporting on, i have seen this error message
mysqli_fetch_assoc() expects parameter 1 to be mysqli_result, bool given in
C:\xampp7.4\htdocs\gift\include\functions.php
on line
68

this is 68 number line

$image_data  = mysqli_fetch_assoc($image_query);
Comment: Your `mysqli` query is failing. You aren't catching mysqli errors currently so your falling into PHP error reporting. Use mysqli error reporting to get errors with your queries... (which could just be the SQL injection issue already mentioned).
Comment: The console likely has a 404 error for the image resource request, unless the page isn't generating at all
Comment: yes i have made the debugging on. Any clue where i am wrong
Comment: just viewed the Ciew-source of the page. it is showing an image there, but the image name is not that what is inserted into database. For example, image moved in folder and inserted into database with name xyz123.jpg, whereas in viewsoruce of the page, it is showing hasdhdfhdj-250x250.jpg in
Comment: Please disclose the $product_query variable. Based on what I can see you are trying to print all the product images from the database. How can you expect a single result in this case?
Answer: i think this should work. You are using wrong variables. In database you have images_id, whereas you have calling $image_id in your code. Use $images_id and it will work
if ($featured_image) {
        $image_id = $featured_image['images_id'];
        $image_query = mysqli_query($con, "SELECT * FROM images WHERE images_id = $image_id");
        $image_data = mysqli_fetch_assoc($image_query);

        if ($image_data) {
            return $image_data['file_name'];
        }
    }

Comment: thank you soo much. i just seen the spelling issue. it is working


Specify more than one directory in Web.Config's Location Path element

Question: In my ASP.NET's Web Config file I have the following location elements defined:
  <location path="">
    <system.web>
      <authorization>
        <deny users="?"/>
      </authorization>
    </system.web>
  </location>

  <location path="dir1">
    <system.web>
      <authorization>
        <allow users="?"/>
      </authorization>
    </system.web>
  </location>

  <location path="dir2">
    <system.web>
      <authorization>
        <allow users="?"/>
      </authorization>
    </system.web>
  </location>

The example above is specifying that all directories will be locked down to anonymous users except the two directories dir1 and dir2.
I'm curious if there is a syntax that I can use that will allow me to define more than one directory within one location element. For example, it would be convenient if we could do something like this...
  <location path="dir1,dir2,etc">
    <system.web>
      <authorization>
        <allow users="?"/>
      </authorization>
    </system.web>
  </location>

Comment: Looks like it used to be documented as allowing a comma separated list of paths, but they fixed the documentation rather than implementing the documented feature. http://connect.microsoft.com/VisualStudio/feedback/details/104010/location-path-attribute-in-web-config-doesnt-accept-multiple-paths
Comment: @Triynko https://connect.microsoft.com/VisualStudio/feedback/details/104010/location-path-attribute-in-web-config-doesnt-accept-multiple-paths not found
Answer: You cannot specify multiple elements in the path attribute, but you can make use of the configSource attribute.
For example, the following original web.config file:
<?xml version="1.0"?>
<configuration>
  <location path="form1.aspx">
    <system.web>
      <authorization>
        <allow users="*"/>
      </authorization>
    </system.web>
  </location>
  <location path="form2.aspx">
    <system.web>
      <authorization>
        <allow users="*"/>
      </authorization>
    </system.web>
  </location>
  <location path="form3.aspx">
    <system.web>
      <authorization>
        <allow users="*"/>
      </authorization>
    </system.web>
  </location>
  <location path="form4.aspx">
    <system.web>
      <authorization>
        <deny users="*"/>
      </authorization>
    </system.web>
  </location>
  <location path="form5.aspx">
    <system.web>
      <authorization>
        <deny users="*"/>
      </authorization>
    </system.web>
  </location>
  <location path="form6.aspx">
    <system.web>
      <authorization>
        <deny users="*"/>
      </authorization>
    </system.web>
  </location>
</configuration>

Can be replaced by the following equivalent web.config, allow.config, and deny.config files:
web.config
<?xml version="1.0"?>
<configuration>
  <location path="form1.aspx">
    <system.web>
      <authorization configSource="allow.config" />
    </system.web>
  </location>
  <location path="form2.aspx">
    <system.web>
      <authorization configSource="allow.config" />
    </system.web>
  </location>
  <location path="form3.aspx">
    <system.web>
      <authorization configSource="allow.config" />
    </system.web>
  </location>
  <location path="form4.aspx">
    <system.web>
      <authorization configSource="deny.config" />
    </system.web>
  </location>
  <location path="form5.aspx">
    <system.web>
      <authorization configSource="deny.config" />
    </system.web>
  </location>
  <location path="form6.aspx">
    <system.web>
      <authorization configSource="deny.config" />
    </system.web>
  </location>
</configuration>

allow.config
<?xml version="1.0"?>
<authorization>
  <allow users="*"/>
</authorization>

deny.config
<?xml version="1.0"?>
<authorization>
  <deny users="*"/>
</authorization>

The usefulness of this approach increases as the number of allow/deny rules in each section increases.
Comment: Would I be able to simplify even further and only have lines for location with the configSource set there? So it would basically be just a list of locations?
Comment: @Ray: When I tried that, I got `Unrecognized attribute 'configSource'`.
Answer: sorry, but path property doesn't allow to use ","
so you must write  tag for all path,
Or you can create web.config in each directory.
Answer: it is possible to set path to a specific folder.
For example we have some aspx pages:

/data/pages/form1.aspx
/data/pages/form2.aspx
/data/pages/form3.aspx

By creating this rule in web.config:
<location path="data/pages">
    <system.webServer>
        <httpProtocol>
            <customHeaders>
                <remove name="X-Frame-Options" />
                <add name="X-Frame-Options" value="SAMEORIGIN" />
            </customHeaders>
        </httpProtocol>
    </system.webServer>
</location>

All resources in data/pages will be affected.
Answer: I had a similar issue. so went with the normal way of creating separate tags, no other BETTER solution.


How do I run a BrowserTestBase functional test with blocks?

Question: I have a module that defines a custom block and places it using a block.block.block_name.yml file that I generated by exporting the placement of the block on a dev site. I've unit-tested the block code, but now I want a functional test that will tell me whether the block is correctly placed and rendering to the right users;
<?php

namespace Drupal\Tests\my_module\Functional;

use Drupal\Tests\BrowserTestBase;
use Drupal\my_module\EnablerService;
use Drupal\node\Entity\Node;
use Drupal\node\NodeInterface;
use Drupal\user\Entity\User;

/**
 * Main test class for the my_module module
 *
 * @group my_module
 */

class ImplementationTests extends BrowserTestBase {

  public $defaultTheme = 'bootstrap';

  /**
   * Modules to enable.
   *
   * @var array
   */

  public static $modules = ['block', 'node', 'my_module', 'user'];

  private NodeInterface $node;
  private User $user;

  # from https://www.drupal.org/project/bootstrap/issues/2860072#comment-12287718
  protected function getConfigSchemaExclusions() {
    return array_merge(parent::getConfigSchemaExclusions(), ['bootstrap.settings']);
  }
  /**
   * {@inheritdoc}
   */
  protected function setUp(): void {
    parent::setUp();
  }

  /**
   * some test
   */
  public function test_nothing() {
    $this->assertTrue(true);
  }
}

However, when I run this, I get this error:

Drupal\Tests\my_module\Functional\ImplementationTests::test_nothing
Trying to access array offset on value of type null
/opt/drupal/web/core/lib/Drupal/Core/Block/BlockPluginTrait.php:90
/opt/drupal/web/core/lib/Drupal/Core/Block/BlockPluginTrait.php:74
/opt/drupal/web/core/lib/Drupal/Core/Plugin/DefaultSingleLazyPluginCollection.php:85
/opt/drupal/web/core/lib/Drupal/Core/Plugin/DefaultSingleLazyPluginCollection.php:99
/opt/drupal/web/core/lib/Drupal/Core/Plugin/DefaultSingleLazyPluginCollection.php:55
/opt/drupal/web/core/modules/block/src/BlockPluginCollection.php:34
/opt/drupal/web/core/modules/block/src/Entity/Block.php:156
/opt/drupal/web/core/modules/block/src/Entity/Block.php:166
/opt/drupal/web/core/lib/Drupal/Core/Config/Entity/ConfigEntityBase.php:291
/opt/drupal/web/core/modules/block/src/Entity/Block.php:344
/opt/drupal/web/core/lib/Drupal/Core/Entity/EntityStorageBase.php:494
/opt/drupal/web/core/lib/Drupal/Core/Entity/EntityStorageBase.php:449
/opt/drupal/web/core/lib/Drupal/Core/Config/Entity/ConfigEntityStorage.php:263
/opt/drupal/web/core/lib/Drupal/Core/Entity/EntityBase.php:339
/opt/drupal/web/core/lib/Drupal/Core/Config/Entity/ConfigEntityBase.php:591
/opt/drupal/web/core/lib/Drupal/Core/Config/ConfigInstaller.php:373
/opt/drupal/web/core/lib/Drupal/Core/Config/ConfigInstaller.php:248
/opt/drupal/web/core/lib/Drupal/Core/Config/ConfigInstaller.php:152
/opt/drupal/web/core/lib/Drupal/Core/ProxyClass/Config/ConfigInstaller.php:75
/opt/drupal/web/core/lib/Drupal/Core/Extension/ModuleInstaller.php:287
/opt/drupal/web/core/lib/Drupal/Core/ProxyClass/Extension/ModuleInstaller.php:83
/opt/drupal/web/core/lib/Drupal/Core/Test/FunctionalTestSetupTrait.php:464
/opt/drupal/web/core/tests/Drupal/Tests/BrowserTestBase.php:581
/opt/drupal/web/core/tests/Drupal/Tests/BrowserTestBase.php:400
/opt/drupal/web/modules/custom/implementations/tests/src/Functional/ImplementationTests.php:40
/opt/drupal/vendor/phpunit/phpunit/src/Framework/TestResult.php:685

Looking at the first file in the stack (/opt/drupal/web/core/lib/Drupal/Core/Block/BlockPluginTrait.php:90), I see this:
 80   /**
 81    * Returns generic default configuration for block plugins.
 82    *
 83    * @return array
 84    *   An associative array with the default configuration.
 85    */
 86   protected function baseConfigurationDefaults() {
 87     return [
 88       'id' => $this->getPluginId(),
 89       'label' => '',
 90       'provider' => $this->pluginDefinition['provider'],
 91       'label_display' => BlockPluginInterface::BLOCK_LABEL_VISIBLE,
 92     ];
 93   }

Here is the contents of my block.block.my_block.yml file:
langcode: en
status: true
dependencies:
  module:
    - node
  theme:
    - bootstrap
id: my_block
theme: bootstrap
region: content
weight: 10
provider: null
plugin: my_module_my_block
settings:
  id: my_module_my_block
  label: 'My Block'
  provider: null
  label_display: '0'
visibility:
  node_type:
    id: node_type
    bundles:
      idea: idea
    negate: false
    context_mapping:
      node: '@node.node_route_context:node'

My guess is that BrowserTestBase needs some additional code to properly set up the blocks module, but I'm not sure what else I need to do. Any ideas?
Answer: In setUp() you need $this->drupalPlaceBlock('block_name');
Possibly other things are wrong - you didn't show the code where the failure occurs so it's hard to say.
Comment: I've added the contents of the block's `yml` file, is that what you mean? Regarding your suggestion, the block is placed by the `yml` file, but regardless, it's crashing even without that `drupalPlaceBlock` line so I wanted to resolve that first.
Comment: I just realised I had incorrect class names in the error messages. This was because I modified the error message to produce a mve, that's fixed now.
Comment: Now you've edited your post and you changed a function name and changed the machine name of the block you're using and you don't show the code for your block plugin so it's not clear you're even doing the right things. If you used drupalPlaceBlock() like I suggested but did not modify it with your new block name, then of course it won't work. If your code works interactively, then drupalPlaceBlock() is the only "special" thing you need to add in the tests. Maybe you should start by using one of the core-provided blocks in your test (instead of your own block) and see if you can make that work.
Comment: Ok so I tried to put together an MVE in response to your comment but in doing that I realised what my mistake was - I overrode the `BlockBase` constructor and that seems to break the Functional test (but for some reason the dev environment was fine). Regardless of why it behaved the way it did, I think it's probably a bad question and your answer is more likely to help the average visitor, so I'll mark it as the correct one. Sorry about that - I'll try to do an MVE from the get-go next time around.


If a machine can be reached via two network interfaces, which one will Windows use?

Question: Consider, for example, an application server and a storage server.

Both servers run services which needs to be accessed by everyone, so
they are connected to the "public" network
The application server has high IO on the storage server, therefore a dedicated, second network connected just the two of them.

Given that

Both machines are Windows
the same machine can be reached via two network interfaces
the connection is made by machine name rather than IP address

Which connection will Windows use?

Bonus question: what if a machine is connected to two separate networks, and two servers with the same name exists on both of them respectively?
Comment: In which name service are the two hosts with the same name configured?
Comment: @Iain Windows machine name. When Network Sharing is turned on, Windows can automatically resolve other Windows machine names to IP on its network even without DNS.
Comment: The machines are in a domain? I had a "similar" setup and the domain subnet was always preferred.
Answer: If it's my network, I'm not going to let Windows decide. I'm gonna give the interfaces on the dedicated server-server network different DNS names (maybe application-dedicated and storage-dedicated) and explicitly configure services that need to talk between the servers to use the -dedicated names (or IP addresses if for some reason I can't use DNS names -- like \\dedicated.storage.ip.address\sharename)
Comment: Routing metrics. https://support.microsoft.com/en-us/kb/894564 But again, for an "important" connection, I'm not going to let Windows (or any other OS) decide that for me.
Comment: Yes, I know it can be solved by using different DNS name or IP - but my question is, what *if* they're the same name?
Comment: Yes, the routing metrics is the answer I'm looking for. Would you put that in the answer body?


Fractional Exponents and Fractions

Question: When dealing with fractional exponents like in the question below, how do  you combine them so the two "n's" in the first fraction become one? ((how do i combine $4/3$  with $1/3$))
The aim is to end up with only one 'n' in that fraction. Same goes for the 'm'.
\begin{align*}
& \frac{2^{\frac{1}{3}}mn^{\frac{4}{3}}}{5^{\frac{1}{3}}m^{\frac{1}{6}}n^{\frac{1}{3}}} \div \frac{n}{2m^{\frac{1}{6}}5^{\frac{1}{3}}}\\
& = \frac{2^{\frac{1}{3}}mn^{\frac{4}{3}}}{5^{\frac{1}{3}}m^{\frac{1}{6}}n^{\frac{1}{3}}} \cdot \frac{2m^{\frac{1}{6}}5^{\frac{1}{3}}}{n}\\
& =
\end{align*}
Comment: Exponent rules are the same for integers and fractions.  So $n^{\frac{1}{3}}\times n^{\frac{4}{3}}=n^{\frac{5}{3}}$.  And when dividing, you subtract exponents similarly.
Comment: Please see http://meta.math.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference for information about how to format mathematics on this site.
Answer: As far as I can see this is what your term looks like:
$\frac{2^{\frac{1}{3}}m n^{\frac{4}{3}}}{5^{\frac{1}{3}}m^{\frac{1}{6}}n^{\frac{1}{3}}} \cdot \frac{2m^{\frac{1}{6}}5^{\frac{1}{3}}}{n}$
$=\frac{2^{\frac{1}{3}}m n^{\frac{4}{3}}}{n^{\frac{1}{3}}}\cdot \frac{2}{n}$
$=\frac{2^{\frac{1}{3}}m n^{\frac{4}{3}}}{n^{\frac{1}{3}}} \cdot \frac{2^{\frac{3}{3}}}{n^{\frac{3}{3}}}$
$=\frac{2^{\frac{4}{3}}m n^{\frac{4}{3}}}{n^{\frac{4}{3}}}$
$=\sqrt[3]{2^4}\cdot m$

Fractional Exponents and Fractions


Socket IO scaling: is it more efficient to send messages to specific socket id's?

Question: I am developing an application using Socket IO that needs to be scaled across multiple servers. This is being achieved through socket.io-redis, which essentially interconnects all of my servers running socket IO and treats Redis as a datastore that all of my servers/nodes running Socket IO publish messages from.
For better context, here is a diagram from MSDN that outlines my setup:

Here's my issue:
If Client A sends a message only intended for Client C to receive, I feel it's a waste of bandwidth to publish a message to Client B and D. My idea is that I would, on the server-side, record user id's and their corresponding open socket id's. Then when a client sends a message, I would do do a lookup and find a user's socket id(s) and publish the messages. This seems fine and dandy as well as heavily reliant on a robust system to keep that table of user id's and socket id's up to date, but there are two questions I have about implementing this system:
1) Is it more memory efficient to emit messages to only relevant socket id's, rather than to an entire channel across every server? I realize that with 4 total clients, this problem is very small, but imagine if I had 2000 concurrent users across 2 servers. If 1 client sends a message intended for 2 clients, I imagine sending a message to 1997 other clients is more taxing than sending to just those 2 socket id's, unless "io.sockets.connected[socket_id].emit" is not efficient. Example below:
socket.on('chat message', function(msg){
    io.emit('chat message', msg);
});

vs.
for (i = 0; i < relevant_sockets.length; i++) {
    io.sockets.connected[relevant_sockets[i]].emit('chat message', msg);
}

2) Since I'm using multiple servers, are socket id's guaranteed to be unique? I'm hoping the redis module is handling this since it's entire purpose is to link processes and servers, but I just want to be sure.
Thanks ahead of time for any help.
Answer: 1) What you suggest is pretty common practice. You'll save a little bit on memory, but the biggest gain will be CPU and response times under load.
2) The id assigned to each socket looks to be a randomly generated id. Taking a look at the source code for socket.io-redis, there does not seem to be anything that ensures that each id is unique. If you are concerned about ids not being unique, you could generate your own unique id and store it along side the socket id. Then you'd just use both id's as the keys for your lookup (perhaps even create a hash out of them).
Comment: I mean, there's really no magic solution or trick to this. You can either trust the random generator and not worry about the possibility of a ID collision, or you can write a routine to verify that each id is in fact unique. This is a really broad subject in computing in general. Many large complicated systems rely on UUID's, which are randomly generated, but may theoretically have a collision. If I were you, I'd not worry about it, and trust the unique ID generator.
Comment: Thanks for the great information. My main concern about unique socket ID's is in regards to security. If two clients can potentially have the same socket ID, how can I make sure not to send the wrong client a message that is not intended for them?
Answer: You definitely do not want to broadcast messages to all clients when you need to send it to only one. Your approach #1 is like operating in "god mode", perhaps intended only for the administrator.
I have implemented a similar architecture to yours. However, I also use Redis to map my client ID's (the client names) to the socket id AND vice-versa. For example, you can join in as "omegalen" with socket id 123. Then you disconnect, for some reason, and you get a new socket id: 456. When I need to send a message to "omegalen", I need to first lookup "omegalen" in Redis and get your most recent socket id: 456, as 123 is gone and it will not work. Here's some sample code to give an idea. Notice I prefix my keys with a namespace and I also set an expiration time to them (24 hours):
var client = redis.createClient(redisPort, redisHost);

function _updateSocketId(clientName, socketId) {
    client.set("client/" + clientName, socketId);
    client.set("socket/" + socketId, clientName);

    client.expire("client/" + clientName, 1 * 24 * 60 * 60); //in seconds. 1 day
    client.expire("socket/" + socketId, 1 * 24 * 60 * 60); //in seconds. 1 day
}

function _getSocketId(clientName, callback) {
    //all clients are stored and prefixed with the namespace below
    client.get("client/" + clientName, function(err, data) {
        if(err) {
            callback("Error retrieving key for " + clientName + "Error: " + err, null);
            return;
        }
        var socketId = data;
        logger.debug("Retrieved socket for client/" + clientName + ". Socket id: " + socketId);
        callback(null, socketId);

    });
}

function _findClientBySocket(socketId) {
    var name = client.get("socket/" + socketId);
    return name;
}

function _deleteSocketId(socketId, clientName) {
    logger.debug("deleting socket: " + socketId + " - clientName: " + clientName);
    client.del("socket/" + socketId);
    client.del("client/" + clientName);
}

module.exports.getSocketId = _getSocketId;

Then, when setting up my websocket server I listen for events and update the client / socket id map accordingly:
socket.on("join", function (clientName, callback) {
    //update Redis with new client id / socket id
    redisUtil.updateSocketId(clientName, socket.client.id);
})

socket.on("rejoin", function (clientName) {
    redisUtil.updateSocketId(clientName, socket.client.id);
})

socket.on("disconnect", function (clientName) {
    redisUtil.deleteSocketId(socket.client.id, clientName);
})

The code above is just a sample code to give you an idea, as it can also be easily enhanced to handle multiple sockets per client (say you have two browser clients open). Your architectural diagram is good and it'll work, but you need to emit messages only to the intended clients.
I don't want to get off topic, but you can also use namespaces in socket.io and emit events to a group of users, say, only to a special type of clients:
 var ssClients = io.of("/ssClients");  //socket.io namespace for the some ss clients
ssClients.on("connection", function (socket) {
..

This wasn't part of your question, but I think it's valuable to mention in case you need to broadcast / filter messages by namespace.
As far as the socket.io id's being unique, I never had this problem. Google implemented a similar architecture in a MASSIVE scale and they didn't run into problems. You can read it here.
I hope this helps; overall your architecture is very good!


apply lambda function error for date issue

Question: I am trying to extract month from the below join_date. below is the structure of the emp table. and i am getting an error while performing the below code:
emp['join_mth']=emp['join_date'].apply(lambda x:x[:7])

emp_id emp_name account_id join_date
1       rob     121         2019-01-01
2       sam     122         2019-02-02
3       mike    123         2019-03-03
4       tom     124         2019-04-04

type(emp['join_date'])
<class 'pandas.core.series.Series'>

emp.dtypes
emp_id          object
emp_name        object
account_id      object
join_date       object
dtype:object

fail to excute line - 10: emp['join_mth']=emp['join_date'].apply(lambda x:x[:7])

Below is the exact error:
Traceback (most recent call last):
  File "<stdin>", line 39, in <module>
    mapped = lib.map_infer(values, f, convert=convert_dtype)
  File "pandas/_libs/lib.pyx", line 2467, in pandas._libs.lib.map_infer
  File "<stdin>", line 39, in <lambda>
TypeError: 'datetime.date' object is not subscriptable

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "<stdin>", line 70, in <module>
AttributeError: module 'sys' has no attribute 'last_value'

Comment: read your error carefully it says `'datetime.date' object is not subscriptable` so your 'join_date' is of dtype datetime.date so use `emp['join_date'].astype(str).str[:7]`
Answer: read your error carefully it says: "'datetime.date' object is not subscriptable" so your 'join_date' is of dtype datetime.date so use typecast it to string first:
emp['join_mth']=emp['join_date'].astype(str).str[:7]
#OR
emp['join_mth']=emp['join_date'].astype(str).apply(lambda x:x[:7])

OR
Since it's of type datetime.date so you can also use:
emp['join_date']=[x.strftime("%Y-%m") for x in emp['join_date']]
#OR
emp['join_mth']=emp['join_date'].map(lambda x:x.strftime("%Y-%m"))

OR
If you only want to extract month then use:
emp['join_date']=[x.strftime("%m") for x in emp['join_date']]
#emp['join_date'].apply(lambda x:x.strftime("%m"))
#OR(use above code for string format and below for int format)
emp['join_date']=[x.month for x in emp['join_date']]
#emp['join_date'].map(lambda x:x.month)

Answer: You column is not a string but a datetime object, use the relevant method pandas.Series.dt.month, which will enable you to get the month number directly:
emp['join_date'].dt.month

Take advantage of this method as you won't need to handle double digits months.


Can we customize street colours in google maps api in any way

Question: My question involves google maps api knowledge . I want to use google maps in my android app to display roads / streets in different colours. How i do that? Can i customize the street colours on google map api in any way?
Thank you.
Comment: Have you tried to customize street colors and had any problems?
Comment: No i havnt tried customizing street colours..but i need this functionality in my ptoject work. So i needed advice
Answer: yes we can.Now google actually offer this.
but before that you have to spend some time in understanding few things like:

How this works.

Follow this order to read and understand:- go through these links(advised to proceed in order to have a batter understanding)

have a look at this (https://developers.google.com/maps/documentation/javascript/styling)
here is a example for understanding how it works (https://medium.com/exploring-android/introducing-custom-map-styles-for-google-maps-be2095c38850)
finally google offical link to create customisated json map file(link is given in comment as i am not allowed to post more then 2 link(sorry)).

note: usage of this tool is also shown in second step in example.
Comment: Link to of the tool (https://mapstyle.withgoogle.com/)


Don't understand why code goes into infinite loop

Question: I am trying to learn Java and I have been having a hard time using the Scanner class. What I want to do is to accept an integer using Scanner.nextInt() method. Along with this, I want to check if the input is a number or not. If not, I want to ask the user to enter the input again.
Here is the code which I wrote to accomplish this :
  do
  {
   System.out.print("Please enter Side 1:\t");

   if(scanner.hasNextInt())
   {
     d1=(double)scanner.nextInt();
     i=0;
   }
   else
   {
     System.out.print("Side shoud be a number!\t");
     i=1;
   }

  }
  while(i!=0);

This unfortunately goes into a infinite loop, what I understand is that it doesn't wait for the 'return' in the second loop.
Comment: If you step through the code in a debugger you will be able to work it out for yourself.  Note: `scanner.hashNextInt()` will keep returning false in your case once it starts.  There is nothing to reset it.
Comment: While it is in its "infinite loop", what happens if you type a number and press enter?
Comment: Print out the content of the Scanner to see what's actually happening.
Comment: All it takes is for hasNextInt to be false.
Answer: You do not consume the incorrect input in the else branch, so if scanner.hasNextInt() returns false you will enter an infinite loop, because at the next iteration the same scanner state is seen.
Comment: Yeah I know why it goes in the infinite loop as the if condition has the same input in every loop,the problem according to me is that scanner doesn;t wait for a 'return'  i.e user to enter side in the second loop and so on
Comment: throw in a `scanner.nextLine()` at an appropriate place.
Comment: I got it I intialize the scanner object inside the loop,now it working good, thanks anyway
Answer: If scanner.hasNextInt() returns true then it should work but when it returns false it will enter infinite loop.
How about this:-
do
  {
   System.out.print("Please enter Side 1:\t");

  if(scanner.hasNextInt())
  {
   d1=(double)scanner.nextInt();
   i=0;

  }
   else
   {
   System.out.print("Side shoud be a number!\t");
   i=1;
   scanner.nextLine();
   }

  }
  while(i!=0);

or try to change your while loop like  this:-
 while(i==0);

Comment: then it won't accomplish what I want ,i want it go in the loop when the input is not number so the new input can be a number
Comment: Then probably you need to have scanner.nextLine();
Answer: You get stuck in the infinite loop becuase there isn't any method call for the scanner next line. See the bold line addition.
    do {
        System.out.print("Please enter Side 1:\t");

        if(scanner.hasNextInt()) {
            double d1=(double)scanner.nextInt();
            i=0;
        }

        else {
            System.out.print("Side shoud be a number!\t");
            i=1;
        }

        **scanner.nextLine();**
           }
    while(i!=0);

Answer: Some people seem to think it's a simple mistake of swapping the 1 or 0, or the condition should be flipped - but this isn't the case. If you made this change, then you would just get continual prompting for numbers even though you already got one.
You want to only continue prompting if the input was not an integer, and stop prompting the moment you get that integer, right?
I would recommend using a try-catch and a form of the Parse method so it is clear what you would like to do.
(Also, your integer i doesn't need to be an integer - it could just be a boolean (true or false). This also would make the intent of the variable clearer. Naming your variables well is important for good code.)
See this:
import java.io.*;
import java.util.*;

class Test {
  public static void main(String args[]) {
    Scanner scanner = new Scanner(System.in);
    boolean done = false;
    double d1 = 0;
    do {
      System.out.print("Please enter Side 1:\t");
      String next = scanner.next();
      try {
        d1 = Double.parseDouble(next);
        done = true;
      } catch (Exception e) {
        System.out.print("Side should be a number!\t");
      }
    }
    while(!done);
    System.out.println("Number obtained: " + d1);
  }
}

This only continues prompting if you didn't get a double. Once you get a double, it stops.
Comment: Also, in your problem-statement you say you want to read an integer, but you're storing it in a double, so I have it here so that you are trying to read doubles. This could easily be changed to Integer.parseInt(someStringThatCouldBeAnInteger) to suit your needs.
Answer: Hello Guys I finally got it all I needed to do was to initialize the scanner object inside the loop so it wait every time the loop execute heres the code:
do
  {
   System.out.print("Please enter Side 1:\t");
  scanner=new Scanner(System.in);

  if(scanner.hasNextInt())
  {
   d1=(double)scanner.nextInt();
   i=0;

  }
   else
   {
   System.out.print("Side shoud be a number!\t");
   i=1;
   }

  }
  while(i==1);

Thanks for responses tho.
Comment: This isn't necessarily good code though - you may want to see the alternate solution I wrote above.
Comment: Yes I tried the try catch method before I tried the hasInt method but when I used the try catch it showed a system message in scanner class into tho I had a a simple message in the catch loop ,would try ur code and see if it gives the same


How to use these ruby based CSS stylsheet frameworks languages?

Question: I read about many CSS related languages and tools which need ruby.

What is the purpose of these
languages and tool how these can save
time and improve our CSS coding.
What is the role in ruby language in
these languages and tool.
Will i have to install and learn
ruby language to use these languages and tool.
will i need ruby installed on
webserver where website will be
hosted.

I'm talking abut these languages
http://lesscss.org/
http://sass-lang.com/
http://compass-style.org/
some mentioned here:
http://www.ruby-toolbox.com/categories/css_frameworks.html
I'm on Windows XP PC , How can i use these Ruby based languages and which is preferred? I don't know ruby language.
Answer: the point
the point of these languages (i prefer, however frameworks or extensions) of css is to incorporate your workflow to your css saving you time. How?
Let's imagine, that you have div with class some-long-class-to-be-sure-what-it-does and that div has h3 child, p child, .some-other-class child and something else (span child).
Now, if you want to style all of them, you have to do something like this:
.some-long-class-to-be-sure-what-it-does { width: 120px; }
  .some-long-class-to-be-sure-what-it-does h3 { font-size: 20px; }
  .some-long-class-to-be-sure-what-it-does p { margin-bottom: 30px; }
  .some-long-class-to-be-sure-what-it-does .some-other-class { width: 120px; }

to inform browser about (i.e.) only h3 of .some-long-class-to-be-sure-what-it-does has font-size: 20px;.
with most of these parsers/frameworks, you have (still just an example) nesting at hand:
.some-long-class-to-be-sure-what-it-does {
  width: 120px;
    @ h3 { font-size: 20px; }
    @ p {
        margin-bottom: 30px;
        @ .subclass { color: red; }
      }
    @ .some-other-class { width: 120px; }
 }

which gives you smaller css, easier to edit in a long run (this is subjective, you may find it's harder for you to work with).
Also, they extend css in other ways besides nesting: constants (assign something to @col1 and use it on three places, then you decide, that you need something lighter... bam! you edit it once), flags, output formatting and many more, so I guess you will find your way of using it.
how to us it
mostly, you don't install it on your PC, but rather on your server. Instead of classic CSS, you link your site with installed CSS parser/framework/language, which on every call calculates (or will use cached version if avalaible) normal css - but when you edit it, you edit simplified/extended version of your css.
Edit: you don't install it onto your PC as a USER, but you need to install it into your developing enviroment. If it's localhost on your PC, then yes, you install it in your PC - but not as a user, but on your locally running server.
Ruby?
I think, that for ruby, these extensions to css were first. But now you can find it for other languages aswell - I, as PHP programmer, have found Anthony Short's CSScaffold:
github with little description
http://github.com/anthonyshort/csscaffold
scaffold's website, currently offline
http://scaffoldframework.com/
edit: what's it's use?
In that try example you see counting with multiple constant. that way, if you change !sidebar from 200px to 300px, every part of your css recalculates with it. every place this constant is mentioned, wheter by itself or in calculation.
another:
SASS in .NET - Better CSS in .NET?
less css in .NET - http://www.dotlesscss.com/
Comment: @Adam - +1 Thanks for explaining. It's looking more complicated thing then to write css in usual style. and need support from other languages too :ruby, php
Comment: @metal.. - yes, it may seem so. But from my POV (as a webdev. who spends 20+ hrs a week just editing css), I see few things in these frameworks I often think about - "if only css had *this feature*"
Comment: @Adam - "you don't install it on your PC" but i just found this tutorial http://net.tutsplus.com/tutorials/html-css-techniques/using-compass-and-sass-for-css-in-your-next-project/ and it's saying to install ruby on PC.
Comment: @Adam - you mean Anthony Short's CSScaffold doesn't need ruby installed. these days i mostly working with ASP.NET projects so i think no solution available for this. and what is the useful ness of this Sass tool http://sass-lang.com/try.html
Comment: Here is a PHP version of LESS - http://leafo.net/lessphp/ and Wordpress plugin http://wordpress.org/extend/plugins/wp-less/
Answer: You don't need anything on your PC, these should be installed on your webserver and you have to write css code according to frameworks' rules.
Once you do that when you deploy your webapp to server these frameworks compile your styles and convert them to traditional stylesheets.
As far as i know this is mostly what they do.
Sinan.
Comment: so if my web-server doesn't have installed ruby then i should not waste time to use and learn these languages.
Comment: nice answer @Adam Kiss, @metal-gear-solid yep, your webserver has to be able to run framework in your case it has to have ruby, there was also one which runs on Python here: http://sandbox.pocoo.org/clevercss/


Is this assembler bug? bound instruction

Question: About bytepattern 622c24, there are 2 kind of case.

The first case : objdump - as pair.

objdump disassembles 622c24 to : bound  %ebp,(%esp)
linux as assembles bound  %ebp,(%esp) to : 622c24

The second case : library Capstone- keystone pair.

Capstone disassembles 622c24 to :  bound (%esp), %ebp
Keystone assembles bound (%esp), %ebp to : 622c24

As you can see above, the position of source and destination is reversed.

objdump  : bound  %ebp,(%esp)
Capstone :   bound (%esp), %ebp

According to AT&T syntax, BOUND r32, m32 is correct.
Therefore, that means Capstone-keystone pare is the correct one.
Q. So,  objdump-as has problem on disassembling bound instruction?
Is it a bug of binutils?
Answer: Yes, this is probably a design bug in AT&T syntax.  They normally follow the pattern of reversing the operands from Intel-syntax, and renaming the sign/zero-extension mnemonics (cdq => cltq, movsx eax, byte[mem] => movsbl).  Deviations from that can be considered design bugs.
But not implementation bugs unless older versions were different.  It's valid (but unpleasant) when AT&T just does whatever it wants and makes up its own rules for different instructions.  This might be another case of compat with the original Unixware assembler. (see below).

The bound instruction doesn't write either of its input operands, so neither one is really a destination.  And unlike cmp, operand order doesn't have any meaning.  It just checks the register against both upper/lower bounds, and raises a #BR exception if it's out of bounds.
There's only one opcode for it, and it requires register + memory operands (in the ModR/M r and r/m fields.

objdump -d lists the register operand first in both AT&T and Intel syntax.
I assembled db 0x62, 0x2c, 0x24 with NASM and linked it with ld -melf_i386 into a 32-bit ELF executable (because I have a wrapper script that makes it easier to assemble+link+disassemble than to just assemble).
   objdump -drwC -Mintel
8048060:       62 2c 24                bound  ebp,QWORD PTR [esp]

   objdump -drwC -Matt
8048060:       62 2c 24                bound  %ebp,(%esp)

It does seem to be a quirk of AT&T syntax as implemented in binutils (as / objdump / gdb) that bound requires the register arg to be listed first.
bound  %eax, (%edx)  # assembles fine
bound (%edx), %eax   # foo.s:2: Error: operand size mismatch for `bound'

I assume it's the same in Intel-syntax mode that it requires the register arg to be first.  There's no ambiguity in meaning here, just an odd design choice to not reverse the operands vs. Intel syntax.

Related: AT&T syntax also has "bugs" according to the GAS manual:

9.15.16 AT&T Syntax bugs
The UnixWare assembler, and probably other AT&T derived ix86 Unix assemblers, generate floating point instructions with reversed source and destination registers in certain cases. Unfortunately, gcc and possibly many other programs use this reversed syntax, so we're stuck with it.
For example
   fsub %st,%st(3)

results in %st(3) being updated to %st - %st(3) rather than the expected %st(3) - %st. This happens with all the non-commutative arithmetic floating point operations with two register operands where the source register is %st and the destination register is %st(i).

So AT&T syntax has actual bugs where both orders are valid and mean different things.  I think we can group this operand "reversal" in with that.

ndisasm -b32 disassembles it as 622C24  bound ebp,[esp], matching the Intel manual's operand order.
Comment: If you pull out the original iapx186/188 manual Intel designated the register as the destination operand and the memory address where the two bounds are as the source. The manual also shows coding examples. The way I see it, anything that diverged from the original manuals for these processors is likely a bug. Just my opinion.
Comment: @MichaelPetch: Is it significantly different from http://felixcloutier.com/x86/BOUND.html?  The current manual definitely lists it as `BOUND r32, m32&32`  (or 16), but doesn't refer to any of the operands as source or destination, and the OPERATION section doesn't write memory or registers.  Anyway, AT&T syntax is free to make up whatever they want.  The less they stick to "intel-with-reversed-operands" the less useful / easy-to-learn it is, but Intel's manuals do not have the final say in AT&T syntax design.  But yeah, I'm fine with calling it an AT&T syntax bug.
Comment: @MichaelPetch: updated with a new section to say that we can consider this a syntax design bug.


Increments of 0.2 does not abide by the loop condition?

Question: We have Homework about loops that displays two computations and increments a variable by the inputted i. These codes run and all is well until I input a=1, b=3 i=0.2, what happens is that it won't reach to 3 even if the while condition is a<=b. The only time it works when a=1, b=2, and i=0.2
#include <iostream>
#include <iomanip>
#include <cmath>

using namespace std;

double inputI(double i){
    for(i=0;i<=0;cin>>i){
        cout<<"i must be greater than 0"<<endl;
        cout<<"Input i: ";
    }
    return i;
}

double compX(double s, double b){
    double x;
    x = s/cbrt(b)+2*pow(s,2);
    return x;
}

double compY(double s, double x){
    double y;
    y = (x+s/x)+3*s;
    return y;
}

void display(double x, double y,double a){
    cout<<fixed<<setprecision(2)<<a<<"\t";
    cout<<fixed<<setprecision(4);
    cout<<x<<"         "<<y<<endl;
}

int main(){
    double x,y,a,b,i;

    cout<<"Input a: ";
    cin>>a;
    cout<<"Input b: ";
    cin>>b;
    i = inputI(i);
    //is there something wrong???
    do{
        x = compX(a,b);
        y = compY(a,x);
        display(x,y,a);
        a+=i;
    }while(a<=b);

}

Comment: Remember that `double`s are floating point numbers and they are not exact. It might look like `a` equals `b`, but `a` could really be 0.99999999999997 and `b` could be 1.000000000003 and fail the test for equality. See [Is floating point math broken?](https://stackoverflow.com/questions/588004/is-floating-point-math-broken) for more details.
Comment: Why do you pass (the uninitialized) `i` to `inputI`?
Comment: What does it do that you don't expect?
Answer: You to correct the following warning:

warning C4700: uninitialized local variable 'i' used

For example:
double x,y,a,b,i = 0;

Comment: This is a problem, but not one likely to result in the error reported. This will most likely just screw up the user input because `i` enters `inputI` in a non-zero and possibly positive state. But it could also end the world because, you know, UB.
Comment: Yeah agree with @user4581301, the variables are set before they are used so don't think this is the cause.
Comment: I just initialize the variable to ZERO and the current code works.  Hence the output I added to my answer. No magic code change.
Answer: This is a floating-point precision issue with comparison of doubles. These seems to have worked for me:
bool double_less_than(double a, double b, double epsilon = 0.001)
{
    return a < b + epsilon;
}

int main()
{
    ...
    do{
        ...
    }while(double_less_than(a, b, 0.000001));
}


How do I cancel windows server 2003 repair install?

Question: System: Windows 2003 Server Enterprise
Scenario: NTDS db is corrupt and all attempts to fix with esentutl fail.
Ran chkdsk which seemed to repair disk error and give access to the ntds.dit file but still esentutl fails.
(Attached the drive to a different server to run the esentutl)
Error:

Access to source database '[path to copy of]/ntds.dit' failed with Jet
  error -1022.
Operation terminated with error -1022 (JET_errDiskIO, Disk IO error)
  after 0.170  seconds.

This error occurs on any disk I copy the files to including
original location in C:\WINDOWS\NTDS\
Now enter the "Stupid!" and "what was I thinking!?" part (must be the late hour...)
Stupid: No updated backup - after using a backup I get a network password error in the lsass error.
what was I thinking!?: Started the install repair from the original CD but the install fails since the AD fails to start.
Now I cant boot into any mode (safe mode, AD restore etc) nor complete the repair install.
I would really like to avoid a fresh install since I have the Exchange server on this DC and would rather migrate to a new server than have to start from scratch.
Answer: It sure sounds to me that you're completely screwed. If you can't restore from backup and can't get the system online, then you're out of luck. In the future, you should take this as a lesson to:

Take good backups
Test your backups
Not run Exchange (or other services) on a Domain Controller
Answer: Well in windows 2000 AD, ntds.dit is the actual database file.  It's the central point for your user accounts, and everything else stored in AD.  If this file is corrupt...i'm not certain on how to recover it.  Active Directory's database engine is the Extensible Storage Engine ( ESE ) which is based on the Jet database used by Exchange 5.5 and WINS. The ESE has the capability to grow to 16 terabytes which would be large enough for 10 million objects. Back to the real world. Only the Jet database can maniuplate information within the AD datastore.
Unfortunately, Kilgore2k, it seems like you're borked for the moment.
One thing to do in the future is to do regular backups (i know, i know, we've ALL heard it before).  Get some drive-imaging software (Symantec Ghost, WinImg, etc), and get a snapshot of your drive/array.  Then use backup software (start > run > ntbackup, or a 3rd party backup tool) to backup all of your files and such that change daily, weekly, etc.
I have a "vanilla" image of my domain controller and web server that i created..."vanilla" as in, after i installed everything, got the latest hot fixes in, etc, i made a snapshot of it.  Then on Saturdays and Sundays i run a Full backup, and every day in between (monday-friday) i run an incremental backup.
So to restore, i just need to plop that snapshot back on the drives/arrays, then do a restore with my last full backup + the incrementals, and voila, server up and running (you would have to go into AD restore mode though for your DC).


Access control properties from its dynamically created Event Handler

Question: I am developing a C# WinForms application. On the FormLoad event, I dynamically create and add to the form 100 buttons without text, but with names like button1, button2 etc. Also, onto these buttons, after their creation, I dynamically link a unique event handler for the ButtonClick event. How can I access the button's properties from within the event handler (more specifically the button name)?
If I use this.Name, I get the name of the form, and not the name of the button.
Later Edit: (for those who might wonder here in search of solutions)
private void function1()
{
    Button a = new Button();

    a.Name = "button" + (i * j).ToString();
    a.Click += new EventHandler(OnFieldButtonClicked);
}

private void OnFieldButtonClicked(object sender, EventArgs e)
{
    Button button = (Button)sender;
    MessageBox.Show(button.Name);
}

Answer: The sender argument is the event handler encapsulates an instance of the object that has triggered the event:
Button button = (Button) sender;
String text = button.Text;

Comment: Like a charm! Thanks a bunch!
LE: Yes, I just did not know you can convert the sender into button this way. :)
Comment: +1 With this, you don't need to add a unique button handler.  It might help the answer to include the full method definition.
Comment: I added it after your response. I mentioned that.


Práticas recomendadas para Inserção, Alteração e Exclusão com EntityFramework

Question: Para exclusão de registros talvez não tenha, mas para Inserção e Alteração eu acredito que já deve existir algo discutido.
Provavelmente, a maior prática recomendada sobre Inserção e Alteração seja a das ViewModel´s, onde você criando uma view adequada para cada caso, terá então os dados de forma simples para fazer uma Inserção, precisando apenas passar os dados da ViewModel para o Domínio.
Não quero incentivar e nem pedir conselhos sobre práticas ruins,  mas sempre é bom detalhes bem esclarecidos, e ainda assim podem existir muitos casos simples de ViewModel´s ou casos em que um Domínio é simples quanto ao nosso caso de necessidade de uma ViewModel que decidirmos por não replicar uma classe.
Bom, um exemplo:
Pessoa:
public class Pessoa
{
    public int Id { get; set; }

    [StringLength(50)]
    [Required(AllowEmptyString = false)]
    public string Nome { get; set; }

    [Required]
    [DataType(DataType.Date)]
    [Column(TypeName = "Date")]
    public DateTime DataNascimento { get; set; }

    [InverseProperty("Pessoa")]
    public virtual ICollection<Telefone> Telefones { get; set; }
}

Telefone:
public class Telefone
{
    public int Id { get; set; }

    [Required]
    public TipoTelefone TipoTelefone { get; set; }

    [StringLength(3)]
    [Required(AllowEmptyString = false)]
    public string Ddd { get; set; }

    [StringLength(10)]
    [Required(AllowEmptyString = false)]
    public string Numero { get; set; }
}

E então temos uma View para cadastro de pessoas que permite você inserir números de telefones, e com isso temos alguns casos:

Pode existir números já cadastrados (caso de edição);
Pode-se inserir novos números (caso de inserção ou edição);
Pode-se remover alguns números e até adicionar outros (casos de edição).

Obs: Acredito ter listado todas.
Em casos de edição pode até ser simples, basta deixar a propriedade Telefones de Pessoa alimentado e então adicionar o banco de dados.
Mas para inserção, uma pergunta: O Id de pessoa será passado diretamente para Telefones e então esse simples exemplo de inserção cadastra a Pessoa e os Telefones?
[HttpPost]
public ActionResult Save(Pessoa model)
{
    if (ModelState.IsValid)
    {
        dbContext.Pessoas.Add(model);
        dbContext.SaveChanges();
    }
    return View(model);
}

Para alteração: O que é recomendado fazer para então satisfazer as possiveis condições apresentadas?
[HttpPost]
public ActionResult Edit(Pessoa model)
{
    if (ModelState.IsValid)
    {
        var entry = dbContext.Pessoas.Find(model.Id);
        if (entry != null)
        {
            dbContext.Entry(Pessoa).CurrentValues.SetValues(model); // ???
            dbContext.SaveChanges();

            // E se:
            // 1. Existir números já cadastrados?
            // 2. Inserir novos números e outros já existiam?
            // 3. Alguns números e adicionar outros?
        }
        else
        {
            ModelState.AddModelError("", "Pessoa não encontrada!");
        }
    }
    return View(model);
}

Quais as práticas recomendadas nestes cenários, que acredito ser bem genérico e explicativo para diversos casos?
Detalhe: Mesmo exemplificando com ASP.NET MVC, responde à outros tipos e projetos também.
Answer: Introdução
Antes de mais nada, é preciso entender como funciona a implementação do DefaultModelBinder, que não é mencionado em nenhuma resposta sobre o assunto. Ele supõe que as variáveis em tela podem ser simples (primitivas: int, float, String, bool...) ou complexas (um objeto dentro de outro, uma coleção dentro de outra). É esta classe que realiza a associação dos Ids e nomes dos campos do seu formulário com os objetos que são recebidos pelo Controller.
O Mestre-Detalhe, para o DefaultModelBinder, é um objeto (mestre) que possui dentro de si uma Collection de objetos de outro tipo (ou, dependendo, até do mesmo tipo do mestre). Você, inclusive, pode implementar o seu próprio ModelBinder, se quiser, mas não creio que seja necessario, até porque o DefaltModelBinder é excelente para a maioria das situações.
Um exemplo na mão
Vamos fazer uma implementação manual de um mestre-detalhe. Suponha um objeto chamado Jovem e sua coleção de Brinquedos:
public class Jovem
{
    [Key]
    public int JovemId { get; set; }

    [Required]
    public String Nome { get; set; }

    pubic virtual ICollection<Brinquedo> Brinquedos { get; set; }
}

public class Brinquedo
{
    [Key]
    public int BrinquedoId { get; set; }
    public int JovemId { get; set; }

    [Required]
    public String Nome { get; set; }

    public virtual Jovem Jovem { get; set; }
}

Queremos que o mesmo formulário insira um Jovem e pelo menos um Brinquedo para o Jovem. Então o formulário fica mais ou menos assim:

Estou usando Bootstrap com Font Awesome para exemplificar.

@using SistemaDeJovens.Resources
@model SistemaDeJovens.Models.Jovem

@using (Html.BeginForm(null, null, FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    @Html.AntiForgeryToken()

Cadastro de Jovem

        @Html.ValidationSummary(true, "", new { @class = "text-danger" })

            @Html.LabelFor(model => model.Nome, htmlAttributes: new { @class = "control-label col-md-2" })

                @Html.EditorFor(model => model.Nome, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger" })

        <input type="hidden" name="Brinquedos.index" autocomplete="off" value="0">

                <input type="text" name="Brinquedos[0].Nome" id="Brinquedos_0__Nome" class="form-control ckeditor" />

                <input type="submit" value="Criar" class="btn btn-default" />

}

    @Html.FontAwesomeActionLink("Voltar para Index", "Index", "fa-list", htmlAttributes: new { @class = "btn btn-default" })

Repare que coloquei tudo fixo, mais um atributo chamado "index". Por que ele existe? O Steve Sanderson explica que o ModelBinder precisa dele pra saber o que vai ser associado ao objeto detalhe (repare que isso não é nenhuma novidade, é coisa do MVC2). Ele não precisa ser inteiro. Nos meus projetos, por exemplo, "index" é sempre um Guid.
E por que coloquei tudo fixo? Porque os Helpers Html são incapazes de gerar o Html no formato dos índices que são necessários pra que o ModelBinder faça a interpretação correta do seu formulário.
No artigo já citado, o Steve Sanderson também explica a dificuldade de fazer isso na mão, e por isso que foi criado o pacote NuGet que insisto tanto pra vocês usarem: BeginCollectionItem.
Exemplos do BeginCollectionItemHelper
Já abordei o assunto nessas respostas:

Mestre-detalhe em MVC C# com Razor
Editar lista de objetos com POST do form em MVC C#

Perguntas

O Id de pessoa será passado diretamente para Telefones e então esse simples exemplo de inserção cadastra a Pessoa e os Telefones?
No caso da inserção, se você tem um Model Pessoa ainda não salvo com uma Collection Telefones, no caso do Entity Framework 6, o objeto Pessoa será salvo antes, ganhará um Id, e logo após cada Telefone será inserido. Não é preciso fazer atribuições.
No caso do Entity Framework 5, ainda pode ser necessário atribuir mais algumas informações aos objetos de Telefone, porque o framework ainda não era muito espertinho pra ler e salvar objetos agregados como faz o Entity Framework 6.
O que é recomendado fazer para então satisfazer as possiveis condições apresentadas?

Existir números já cadastrados?
Se o número está sendo cadastrado em repetição, você pode buscar antes os telefones (utilizando AsNoTracking() para evitar o monitoramento pelo contexto) e iterar a lista que vem do formulário com a lista que veio do banco de dados.
Inserir novos números e outros já existiam?
Basta inserir os números novos. As respostas já mencionadas dão exemplos de como fazer isso.
Alguns números e adicionar outros?
Acredito que seja um dos dois casos acima.

Quais as práticas recomendadas nestes cenários, que acredito ser bem genérico e explicativo para diversos casos?
Não tem muito segredo: as verificações normalmente ficam na edição do registro pai, e nunca na inserção. O que se pode olhar na inserção são números duplicados, inválidos, etc.
Comment: Esse BeginCollectionItem não ficaria muito bom, aonde possui inúmeros campos, além de só poder deixar eles tudo lado a lado, horizontalmente, pelo menos é os exemplos que vejo... muitos dados ficaria uma view muito feia kkk, mas no caso do Tiago, só 3 propriedades, de boa
Comment: @Rod Totalmente errado isso que você falou. O BeginCollectionItem é um **facilitador** de tratamento de dados de entidades dependentes. Ter mais ou menos campos não muda nada em questão de comportamento do componente. De qualquer forma, vou melhorar essa resposta quando puder (dentro ainda do período de recompensa).


Captured group in optional part of a regular expression

Question: I want to capture a group in an optional part of a string.
For example:
In the string "firstName:Bill-lastName:Gates", I want to capture 2 groups :

Bill
Gates

I use this regex:
firstName:(.*)-lastName:(.*)

But when the lastName-part is optional, I still want to capture the first
group (firstName).
I used this regex, to make the lastName-part optional (in a non-capturing group):
firstName:(.*)(?:-lastName:(.*))?

Using this updated regex, the resulting groups are:

when the lastName part is not present, for example "firstName:Bill" the captured groups are:

Bill
/empty string/

which is correct,

when the firstName and lastName parts are present: "firstName:Bill-lastName:Gates", the groups are not correct:

Bill-lastName:Gates
/empty/

I think it has to do with greediness of the first capturing group, but how to adjust this regex to make the regex work when the lastName-part is optional?
Answer: You are right, it is about greediness. Find a delimiter for the first match group. So, if your firstname "never" contains the dash, only match everything but the dash with the first match group.
firstName:([^-]*)(?:-lastName:(.*))?

firstName:([^-]*)(?:-lastName:(.*))?

Debuggex Demo
If you cannot find such a delimiter you would need to take a different approach. Even if you try to make the first pattern "lazy", the Regex engine always prefers a bigger match over matching an additional optional match.
This is, because lazy matchgroups will match the first string that satisfies the expression (! important wording !)
There might be an option with look arrounds, but you could also use a or -statement without providing optional matches:
firstName:(.*)-lastName:(.*)|firstName:(.*)

This way, the regex engine would match either or, but prefer the pattern with 2 matches since it is listed first. Only if that does not apply, it will try the single match.
Comment: Thanks, works great! +1 for the Debuggex visualizer and the or-statement explanation.
Comment: Why are you repeating the same line twice?
Answer: Even though you accepted @dognose's answer already, I assure you there are first names with a dash in them (You don't wanna piss off Jean-Claude van Damme). I would advise you to do it like so:
    firstName:((?:(?!-lastName:).)*)(?:-lastName:(.*))?

Debuggex Demo
You can see from the visualization that the (?:(?!-lastName:).) says "if the current position is not followed by '-lastName:', capture another character"


TukeyHSD multiple comparison on binomial data using Multcomp package in R

Question: My question is how to perform TukeyHSD multiple comparison on ratio(for example, conversion rate, graduate school admit rate) using multcomp package in R. Take UCLA admission data for example:
mydata <- read.csv("http://www.ats.ucla.edu/stat/data/binary.csv")
mydata$rank <- factor(mydata$rank)

head(mydata)

admit=1 means admitted. So if I am going to multi-pair comparison of admission rate(sum(admit)/count(admit)) between "rank", can I do it as what COOLSerdash proposed in the link:
Comparing levels of factors after a GLM in R
mydata <- read.csv("http://www.ats.ucla.edu/stat/data/binary.csv")
mydata$rank <- factor(mydata$rank)
my.mod=glm(admit~rank, data=mydata,family=quasibinomial)
my.mod.mc=glht(my.mod, mcp(rank="Tukey"))
summary(my.mod.mc)
     Simultaneous Tests for General Linear Hypotheses

Multiple Comparisons of Means: Tukey Contrasts

Fit: glm(formula = admit ~ rank, family = quasibinomial, data = mydata)

Linear Hypotheses:
           Estimate Std. Error z value Pr(>|z|)
2 - 1 == 0  -0.7500     0.3095  -2.423   0.0709 .
3 - 1 == 0  -1.3647     0.3371  -4.049   <0.001 ***
4 - 1 == 0  -1.6867     0.4114  -4.100   <0.001 ***
3 - 2 == 0  -0.6147     0.2758  -2.229   0.1127
4 - 2 == 0  -0.9367     0.3628  -2.582   0.0473 *
4 - 3 == 0  -0.3220     0.3866  -0.833   0.8357

If that's the case, how to interpret "Estimate" field?
thanks,
Kyle
Answer: If I am not mistaken, you actually want a chi square test as you are comparing population proportions.  Taking the dataset you provide, you can easily make a contingency table in R.
tab <- table(mydata$admit, mydata$rank)
> tab

     1  2  3  4
  0 28 97 93 55
  1 33 54 28 12

You can then run a chi square analysis on this object with the chisq.test function.  However, you must realize that you then should do post-hoc comparisons.  In this case, running a chi square test on each pair of columns (i.e. ranks).  Keep in mind with multiple comparisons you also need a correction such as bonferroni.  Hopefully this can get you started.
Comment: Hi cdeterman,just out of curiosity, whats the difference between running a chi square test on each pair of columns and running a two proportion z-test?
Answer: I think it is OK to do what you did. You are simply comparing linear predictions from the model with an appropriate multiplicity adjustment, and if those are relevant to your study, then this does the trick.
To understand the estimate, note that it is on a scale that is the difference of two linear predictions, in this case with the default link function for quasibinomial, which is the logit (i.e., $\log[p/(1-p)]$ or the log odds ratio). A positive difference of two such values indicates that the first $p$ is greater than the second $p$. If you compute the $\exp$ function of these estimated differences, you obtain ratios of odds ratios. For instance, if the odds of one event are 2:1 and the odds of another are 4:1, then the ratio of these odds are $2/4=0.5$ and the difference of logits is $\log 0.5 \approx -0.693$.
Comment: for my own clarification, isn't what the OP asking different from what he is showing?  He states he is going to calculate percentages but shows a linear model between the 'raw' data where admit is binomial.  Are you saying he can replace 'admit' with 'admission rate' or is the linear model equivalent to evaluating 'admission rate'?
Comment: Not totally sure what cdeterman is asking, but the model predicts logit(admission rate).


File validation when the file field isn't required

Question: I have a Drupal 7 custom form where the image or file field is not required. When the form is submitted and no file/image has been uploaded, I get the following errors.

Notice: Undefined index: storage in jobform_my_form_submit() (line 136 of /var/www/html/drupaltst/sites/all/modules/jobpackage/jobform.module).
Warning: Creating default object from empty value in  jobform_my_form_submit() (line 141 of var/www/html/drupaltst/sites/all/modules/jobpackage/jobform.module).
Notice: Undefined property: stdClass::$uri in file_save() (line 601 of /var/www/html/drupaltst/includes/file.inc).

Any help is appreciated!
function jobform_permission() {
  return array(
    'add jobs module' => array(
       'title' => t('Administer permission for your module'),
       'description' => t('Some description that would appear on the permission page..'),
    ),
  );
}

function jobform_menu() {
  $items = array();
  //$items['jobform/form'] = array(
  $items['jobform'] = array(
    'title' => t('Job Form Details'),
    'page callback' => 'jobform_form',
    'page arguments' => array('jobform_form'),
    'access arguments' => array('add jobs module'),
    'description' => t('My form'),
    'type' => MENU_CALLBACK,
  );
  return $items;
}

function jobform_form() {
  return drupal_get_form('jobform_my_form');
}

function jobform_my_form($form, &$form_state) {
  $form['title'] = array(
    '#type' => 'textfield',
    '#title' => t('Title'),
    '#required' => TRUE,
    '#maxlength' => 100,
    '#prefix' => '
',
     '#suffix' => '
',
     '#attributes' => array(
       'placeholder' => t('Enter a Short Title'),
     ),
   );
   $form['descr'] = array(
     '#type' => 'textarea',
     '#title' => t('Description'),
     '#required' => TRUE,
     '#size' => 150,
     '#maxlength' => 5000,
     '#prefix' => '
',
     '#suffix' => '
',
     '#attributes' => array(
       'placeholder' => t('Enter some specific details about the service you provide!'),
     ),
   );
   $form['location'] = array(
     '#type' => 'textfield',
     '#title' => t('Enter Your Location'),
     '#required' => TRUE,
     '#size' => 75,
     '#prefix' => '
',
     '#suffix' => '
',
     '#attributes' => array(
      'placeholder' => t('Where Can the Work Be Completed? (i.e. Online, City, State, Zip)'),
     ),
   );

   //Image Field
   $form['image'] = array(
     '#type' => 'file',
     '#title' => t('Upload a Photo'),
     '#description' => t('Allowed extensions: gif png jpg jpeg'),
     '#prefix' => '

',
     '#suffix' => '
',
   );
   $form['submit'] = array(
     '#type' => 'submit',
     '#value' => 'Submit',
     '#prefix' => '

',
     '#suffix' => '
',
   );

   return $form;
 }

 function jobform_my_form_validate($form, &$form_state) {
   $file = file_save_upload('image', array(
     // Validates file is really an image.
     'file_validate_is_image' => array(),
     // Validate extensions.
     'file_validate_extensions' => array('png gif jpg jpeg'),
   ));
   // If the file passed validation:
   if ($file) {
     // Move the file into the Drupal file system.
     if ($file = file_move($file, 'public://images/')) {
       // Save the file for use in the submit handler.
       //$form_state['image'] = $file;
       $form_state['storage']['image'] = $file;
     }
     else {
       form_set_error('image', t("Failed to write the uploaded file to the site's file folder."));
     }
   }
   else {
     form_set_error('image', t('No file was uploaded.'));
     //$file = file_move($file, 'public://images/title_icon.png');
   }
 }

 function jobform_my_form_submit($form, $form_state) {
   $file = $form_state['storage']['image'];
   // We are done with the file, remove it from storage.
   //unset($form_state['image']);
   unset($form_state['storage']['image']);
   // Make the storage of the file permanent.
   $file->status = FILE_STATUS_PERMANENT;
   // Save file status.
   file_save($file);
   global $user;
   $na = 0;
   $istat = 1;
   db_insert('job_mp_catalog')
     ->fields(array(
       'user_id' => $user->uid,
       'title' => $form_state['values']['title'],
       'descr' => $form_state['values']['descr'],
       'location' => $form_state['values']['location'],
       'image' => $file->fid,))
     ->execute();
   drupal_set_message("successfully saved ");
   //Example:
   //drupal_goto("user/".$user->uid."/edit");
   drupal_goto("content/test-page");
   //drupal_set_message("successfully saved Job!");
 }

Comment: you can probably use `dpm()` on `$form_state` above `$file = $form_state['storage']['image'];` to check if storage index exist or not. And then use checks to avoid exceptions. Also there were extra curly braces.
Answer: Just try to validate on submit function as follow
function my_module_image_form_submit($form, &$form_state) {
  // Upload file to upload_directory in the public files dir.
  $file = file_save_upload('image', array(
    'file_validate_is_image' => array(),
    'file_validate_image_resolution' => array('500x500', '100x100'),
  ), 'public://uploaded_images/', FILE_EXISTS_RENAME);

  // Check if image upload was success.
  if ($file) {
    drupal_set_message(t('Image successfully uploaded.'), 'status');
  }
  else {
    form_set_error('image', t('Image was not uploaded.'));
  }
}

For more info please see this article.
Comment: That certainly helped, Thanks! I am getting this error "Notice: Trying to get property of non-object in jobform_my_form_submit()"  at 'image' => $file->fid,)) when I do not upload an image.
Answer: Figured out the 'image' => $file->fid, part in the db_insert. I used visabhishek suggestion above but for the db_insert, I did the below with removing "'image' => $file->fid," in the else section.
Thanks for the help!
if ($file) {
   db_insert('job_mp_catalog')
     ->fields(array(
       'user_id' => $user->uid,
       'title' => $form_state['values']['title'],
       'descr' => $form_state['values']['descr'],
       'location' => $form_state['values']['location'],
       'image' => $file->fid,))
     ->execute();

}
  else {
      db_insert('job_mp_catalog')
        ->fields(array(
       'user_id' => $user->uid,
       'title' => $form_state['values']['title'],
       'descr' => $form_state['values']['descr'],
       'location' => $form_state['values']['location'],
     ->execute();
}


Maven Compile cant find src/main/resources directory

Question: I am trying to setup an integration-test environment using Maven for my project but am getting the below error when I run the Compile goal.

[ERROR] Failed to execute goal
  org.apache.maven.plugins:maven-resources-plugin:3.0.2:resources
  (default-resources) on project mavenintegrationtest: Error loading
  property file
  '/Users/xxx/dev/poc/java/mavenintegrationtest/profiles/dev/config.properties'
  -> [Help 1]

The error seems to be complaining that it cant find the config.properties file in that location which is correct. For some reason it has removed the "src/main/resources" bit from the file path.
So the correct full path is,

/Users/xxx/dev/poc/java/mavenintegrationtest/src/main/resources/profiles/dev/config.properties

but for some reason its removed src/main/resources and so is looking in,

/Users/xxx/dev/poc/java/mavenintegrationtest/profiles/dev/config.properties

Does anyone know whats causing this ?
My POM is as shown below and I get this error when I uncomment the following "filter" tag,
<filter>${basedir}/profiles/${build.profile.id}/config.properties</filter>

I've tried removing the ${basedir} statement and still get the same error.
<?xml version="1.0" encoding="UTF-8"?>

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>com.stackoverflow</groupId>
  <artifactId>mavenintegrationtest</artifactId>
  <version>1.0-SNAPSHOT</version>

  <name>mavenintegrationtest</name>
  <url>http://www.example.com</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>1.7</maven.compiler.source>
    <maven.compiler.target>1.7</maven.compiler.target>
  </properties>

  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
      <scope>test</scope>
    </dependency>
  </dependencies>

  <build>
    <filters>
      <filter>${basedir}/profiles/${build.profile.id}/config.properties</filter>
    </filters>

    <resources>
      <resource>
        <filtering>true</filtering>
        <directory>${basedir}/src/main/resources</directory>
      </resource>
    </resources>

  </build>

  <profiles>

    <profile>
      <id>dev</id>

      <activation>
        <activeByDefault>true</activeByDefault>
      </activation>
      <properties>
        <build.profile.id>dev</build.profile.id>
      </properties>
    </profile>

    <profile>
      <id>integration-test</id>
      <properties>
        <build.profile.id>integration-test</build.profile.id>
      </properties>
    </profile>
  </profiles>

</project>

Comment: There is no profiles folder in your root project. And though maven is expecting one since you specified it in the filters section.
Comment: When you say you removed the ${basedir} part, I guess you also removed the leading / and left only "src/main/resources"?
Comment: don't you have more information regarding the error message?
Comment: @Sxilderik yes that's correct, i've tried running just with "src/main/resources'
Comment: @lpinto.eu I've tried switching on debug trace and then get a "FileNotFound" exception message which is clear - it cant find my config.properties file because its removed the "src/main/resources" bit from the path....I dont understand what's causing this.
Comment: [Possibly relevant.](https://stackoverflow.com/questions/9216557/referencing-resources-directory-from-project-object-model-variables)
Comment: @Sxilderik thanks - are you suggesting that I move my profiles/ directory to the project root ? I was hoping to avoid that as it didnt seem the right approach - is that correct approach ? In the resources section I specified the resources location but for some reason its not picking this up.
Comment: @robbie70, yes you should move the folder and that's the correct approach. See the update in my answer.
Answer: The filter (link) element will parse your files and apply a content filter on them.
The profiles (link) element helps you define different environments for the build.
All of this as to do with your resources. These can be configuration files, or other type of files. If you filter then you can change the content of this files with other values - e.g. pom properties. When using profiles you can have different replacement properties for each environment.
You should move the profiles up in the tree for the default path, or add a configuration in your pom for the resource location.
The base dir is the folder containing your pom. You should have your profile folder here.

Also, here is some good information about profiles and its configurations.
Comment: @Ipinto.eu thank you - I will check this. That link you posted is the one that I have been following ! :)
Comment: The same I used. Just move the profiles folder as I show in my project print. If it helped please fell free to vote my answer and or accept it.
Comment: @Ipinto.eu thank you that worked ! :) interestingly I also got my original version working by adding src/main/resources to my filter tag as follows,
 ${basedir}/src/main/resources/profiles/${build.profile.id}/config.properties

but from what you're saying the standard approach is to have "profiles" directory off the main project directory and not in the resources directory - in which case I am not clear what effect the resources tag has ?
I will accept your answer as the answer.
Comment: the resources are non source code files, that you want to add to your project - e.g. configurations, translations... the profiles you will use to "customize" the resources, and so, just to distinguish this, you store them in a different location.


Conditionaly display fields of another node on a node page

Question: I am a Drupal beginner, have some CMS and PHP knowledge. I am strugling with a case which intuitively seems like a thing that had to be been solved many times.
I have these content type:

Product with 2 fields description and company.
Company with various fields but the ones that matter here are company_intro, company_address.

When I create a product page, I fill in the description and choose a company from a list. When I present the product page to the user, I want it to start with "company_intro" from the selected company, followed by the description and ending with the address.
Is that possible?
Answer: At first you need to make a relation between Product and Company . to do that you have to install a reference module , Entity References or References .
After enabling the module (No different which one you install) you need to modify your product content type , remove your company field and add a new field of type reference to a node , then refer it to your Content type Company .
till now you have made a relation between Product and Company , now to do the rest of the job you can use Panels and Page Manager (included in CTools) .
Check this tutorial if you are not familiar with panels : Learning Panels and Page Manger