Getting 500 Error on Home page when publishing ASP.Net Core Web App with class library to Azure

Question: I've been trying to deploy my web application to Azure but I get a 500 Error on the first page. I am assuming this is because of an issue with the model that I am referencing on the first page, which is being referenced to a class library in my solution.
Here's how the project looks

I've had some issues with referencing the class library before but I have been able to remedy those issues and build both projects successfully so far. And the project runs just fine in IISExpress. But when I try to deploy it to Azure, I get a 500 Error on my Home page. Here's the code for it:
@using LNCLibrary.Models.HomeViewModel
@model HomeViewModel
@{
    ViewData["Title"] = "Home Page";
}
@inject SignInManager<ApplicationUser> SignInManager
@inject UserManager<ApplicationUser> UserManager

<!DOCTYPE HTML>

    <title>New Shop a E-Commerce Online Shopping Category Flat Bootstrap Responsive Website Template | Home :: w3layouts</title>

    <link href="css/bootstrap.css" rel="stylesheet" type="text/css" media="all" />
    <link href="css/style.css" rel="stylesheet" type="text/css" media="all" />
    <link href="css/font-awesome.css" rel="stylesheet">

    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <meta name="keywords" content="New Shop Responsive web template, Bootstrap Web Templates, Flat Web Templates, Android Compatible web template,
Smartphone Compatible web template, free webdesigns for Nokia, Samsung, LG, SonyEricsson, Motorola web design" />

    <link href='//fonts.googleapis.com/css?family=Cagliostro' rel='stylesheet' type='text/css'>
    <link href='//fonts.googleapis.com/css?family=Open+Sans:400,800italic,800,700italic,700,600italic,600,400italic,300italic,300' rel='stylesheet' type='text/css'>

    <link rel="stylesheet" href="css/jstarbox.css" type="text/css" media="screen" charset="utf-8" />

                     Help   +0123-456-789
                    Administration

                        @await Html.PartialAsync("_LoginPartial")

New Shop Shop anywhere

                                <button type="button" class="navbar-toggle collapsed navbar-toggle1" data-toggle="collapse" data-target="#bs-megadropdown-tabs">
                                    Toggle navigation

                                </button>

Home

                                        Women

Clothing

Wallets

Shoes

Watches

 Underwear

Accessories

Submenu2

Sunglasses

Wallets,Bags

Footwear

Watches

Accessories

Jewellery

                                        Men

Clothing

Wallets

Shoes

Watches

 Underwear

Accessories

Sunglasses

Wallets,Bags

Footwear

Watches

Accessories

Jewellery

Short Codes

Mail Us

                    @*

  cd-header-buttons

                                <form action="#" method="post">
                                    <input name="Search" type="search" placeholder="Search...">
                                </form>

*@
                    @*

                                             ( items)

Empty Cart

*@

        <link href="css/coreSlider.css" rel="stylesheet" type="text/css">

Men's Clothing

50% Off/-

Women's Clothing

T - Shirt

Hand Bag

New Arrivals

                    @foreach (var item in Model.ShopProducts)
                    {

                                @*

NEW

SALE

*@

@item.ProductName

                                    XL / XXL / S

@*$100.00*@$@item.Price

                                    Add To Cart

                    }

I'm sure that it must be an issue with the model i'm using for the page because it resides in the Web app project but references a model in the class library, and so I'm thinking it's another issue with the library or reference. But the problem is I can't figure out how to debug in Azure to see what the actual issue is due to the 500 error. Here's the ViewModel, Model and Controller:
ViewModel:
using System;
using System.Collections.Generic;
using System.Text;

namespace LNCLibrary.Models.HomeViewModel
{
    public class HomeViewModel
    {
        public ICollection<Product> ShopProducts { get; set; }
    }
}

Model:
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Text;

namespace LNCLibrary.Models
{
    public enum Category
    {
        Shirts,
        Accesories,

    }
    public enum Gender
    {
        Men,
        Women,
        Both

    }

    public class Product
    {
        public int ID { get; set; }
        [Display(Name ="Name")]
        public string ProductName { get; set; }
        public int Price { get; set; }
        [Display(Name = "Gender")]
        public Gender GenderOption { get; set; }
        public int Quantity { get; set; }
        public Category Category { get; set; }
        [Display(Name ="Created")]
        public DateTime DateCreated { get; set; }
        [Display(Name = "Description")]
        public string ProductDescription { get; set; }
        public ICollection<Size> AvailableSizes { get; set; }
        [Display(Name = "Profile Picture")]
        public string ProfilePicture { get; set; }
    }
}

Controller:
 private readonly ApplicationDbContext _context;

    public HomeController(ApplicationDbContext context)
    {
        _context = context;
    }
    public async Task<IActionResult> Index()
    {
        HomeViewModel HVM = new HomeViewModel();
        HVM.ShopProducts = await _context.Products.ToListAsync();
        return View(HVM);
    }

Any ideas? I'm stumped.
Comment: In ASP.NET Core there's some configuration for error handling in _startup.cs_. There should be a line where you add `app.UseDeveloperExceptionPage();` if the environment is Development. Switch it to add this line always, and see some error details coming in. That should help you debug your issue.
Comment: You were partially correct. My environment settings were already set in VS and in the project; I had to set the environment settings in Azure and that took care of it.
Answer: After you pusblished Azure App Service with the Publish dialog box in VS, open Server Explorer (View > Server Explorer), right-click on the App Service instance and choose Attach Debugger.
In the running ASP.NET application, reproduce the error or set a breakpoint before.
The breakpoint should be hit in Visual Studio.
Like locally!
Answer: In starup.cs there is a method Configure. Enable   app.UseDeveloperExceptionPage() and  app.UseDatabaseErrorPage() to see errors in detail.
 public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseDatabaseErrorPage();
            }
            else
            {
                //app.UseExceptionHandler("/Home/Error");

                app.UseDeveloperExceptionPage(); // add this to see error
                app.UseDatabaseErrorPage();    // add this to see  error

            }

        }


What is the meaning of 'Analytic Isomorphism'?

Question: I am reading the book "Problems in the Theory of Modular Forms: M. Ram Murty" Chapter-3, Exercise 3.1.4. In this, I need to show that the map $$ z \mapsto \frac{z-i}{z+i} $$
is an analytic isomorphism from the upper half-plane $\mathbb{H}$ to the unit disk $$\mathbb{D}=\{w \in \mathbb{C}: |w|<1\}.$$ Since the map is defined on the upper half-plane which is not a group with respect to addition or multiplication, in what sense, we call the above map to be an 'Isomorphism'? Is it just a set bijection? Any clarification in this regard would be appreciated!
Comment: It means an [bi-holomorphic map](https://en.wikipedia.org/wiki/Biholomorphism) : $f(z) : A \to B$ is holomorphic and $f^{-1}(z) : B \to A$ too. The idea is that it is easy to construct a real analytic isomorphic map $A \to B$, but it is much harder to make it complex analytic. Indeed, the only bi-holomorphisms $H \to D$ or $D \to D$ (or $H \to H$ or $D \to H$) are Möbius transformations.
Comment: A bijection that is analytic in both directions ... This is an isomorphims in a suitable category, and not all categories are the category of groups.
Comment: And something natural (in particular in the context of modular forms) is to consider the ring of analytic (= holomorphic) functions on $A$ and (its field of fraction) the field of meromorphic functions on $A$, and to say that a bi-holomorphic map $A \to B$ induces a field isomorphism with the field of meromorphic functions on $B$.
Answer: It means that the map is bi-holomorphic. The map is the well-known "Cayley-transform". There is a generalization $\Phi\colon G\rightarrow {\rm Lie}(G)$ defined on groups, if you want groups, namely on certain algebraic groups and Lie groups. For this see the interesting article by Kostant and Michor.


Fingernail and hand care for pianists

Question: I've never given much thought to nail/hand care. I keep my nails short and generally don't use lotion, because it transfers to the keytops.
I'm also prone to hangnails, and every once in a rare while my fingertips feel bruised if I practice vigorously for an extended time after trimming my nails.
I'm so used to all of this, it's never until now occurred to me to question it. But then I read this, regarding guitar playing:

Shorten your nails as much by possible, but not by cutting. The problem with cutting them very short is that the tool compresses the fingernail and pulls it away from the skin. That causes the separation and pain. You should cut your nails only to a comfortable point, and then from there continue to shorten them by filing with a diamond file. (SOURCE: SE MP&T)

I cut my nails will a clipper. Are manicure scissors better? Should I file them? With a certain type of file? Should I go all out and get manicures? Should I be treating (or preventing) hangnails is some way? Is there some advantage or disadvantage to more or less dry skin?
What should pianists consider in caring for our hands and nails? What kind of impact, if any, do the care techniques chosen have on our hands, nails, and piano playing?
Comment: Aaron, are you suffering from covic-blues? ;)
Comment: I'm fairly sure you are more knowledgeable than I am, but still going to give my point of view. I oftenly let my fingernails grow kinda long before I start cutting them with regular nail clipper. And whenever I cut them, I usually try to not cut them too deep. Because of which the pink part of the nails seem to grow over the years (meanwhile relatives have finger part above nails because they cut them deeper). I guess it makes playing with the finger tip harder, but I never had much "health trouble" because of that.
Answer: Healthy hand skin is better than dry skin since you can grip the keys better and avoid painful skin cracks.  I put Aquaphor on my hands right before bed (once or twice a week during winter) so it can soak in all night and not get on my keyboard or anything else.
As for nail care, the concern is that nails that are too long or have jagged edges produce a clicking sound while playing that is audible to listeners and on recordings.  I trim my nails frequently (probably about every 4 or 5 days) making shallow cuts and avoiding trimming too close (which can lead to a skin crack right under the nail and is most annoying to have while playing).  Finger- sized clippers should be used, not toe-sized clippers.  Toe-sized clippers make it more likely that you'll trim too close and get that painful skin crack right under the edge of the nail.  Finally, I file the nails with a large emery board so there are no edges or points.
Hangnails can be simply cut off with the nail scissors. Biting or tearing them should obviously be avoided.  A simple inexpensive nail-care kit should have everything you need.
Answer: I believe that the same rule is applied everywhere in piano practice: while you feel comfortable it is OK: if you feel fatigue in the right hand - it is good to switch to the practice the left one; if you are bored with a piece it would be beneficial to switch to something else for some time.
When you are doing properly your nails, it reduces the chance of skin injury which can lead to the development of infection at that place and as a result pain and loss of comfort during practice.
So, if skin injuries are a problem for you - then it could be a sign to reconsider your nail-care habits.
Considering tools, you usually can purchase a manicure set that will contain all you need (scissors for nails, scissors for cuticle, diamond file, etc.).

Fingernail and hand care for pianists


Improving the speed and efficiency of this PHP spellchecker

Question: I built a simple PHP spellchecker and suggestions application that uses PHP's similar_text() and levenshtein() functions to compare words from a dictionary that is loaded into an array.

How it works: First I load the contents of the dictionary into an
array.
I split the user's input into words and spell check each of the
words.
I spell check by checking if the word is in the array that is the
dictionary.
If it is, then I echo a congratulations message and move on.
If not, I iterate through the dictionary-array comparing each word, in the dictionary-array, with the assumed misspelling.
If the inputted word, in lower-case and without punctuation, is 90%
or more similar to a word in the dictionary array, then I copy that
word from the dictionary array into an array of suggestions.
If no suggestions were found using the 90% or higher similarity
comparison, then I use levenshtein() to do a more liberal comparison
and add suggestions to the suggestions array.
Then I iterate through the suggestions array and echo each
suggestion.

I noticed that this is running slowly. Slow enough to notice. And I was wondering how I could improve the speed and efficiency of this spell checker.
Any and all changes, improvements, suggestions, and code are welcome and appreciated.
Here is the code (for syntax highlighted code, please visit here):
<?php
    function addTo($line) {
        return strtolower(trim($line));
    }

    $words = array_map('addTo', file('dictionary.txt'));
    $words = array_unique($words);

    function checkSpelling($input, $words) {
        $suggestions = array();
        if (in_array($input, $words)) {
            echo "you spelled the word right!";
        }
        else {
            foreach($words as $word) {
                $percentageSimilarity = 0.0;
                $input = preg_replace('/[^a-z0-9 ]+/i', '', $input);
                similar_text(strtolower(trim($input)), strtolower(trim($word)), $percentageSimilarity);
                if ($percentageSimilarity >= 90 && $percentageSimilarity<100) {
                    if(!in_array($suggestions)){
                        array_push($suggestions, $word);
                    }
                }
            }
            if (empty($suggestions)) {
                foreach($words as $word) {
                    $input = preg_replace('/[^a-z0-9 ]+/i', '', $input);
                    $levenshtein = levenshtein(strtolower(trim($input)), strtolower(trim($word)));
                    if ($levenshtein <= 2 && $levenshtein>0) {
                        if(!in_array($suggestions)) {
                            array_push($suggestions, $word);
                        }
                    }
                }
            }
            echo "Looks like you spelled that wrong. Here are some suggestions:
";
            foreach($suggestions as $suggestion) {
                echo "
".$suggestion."
";
            }
        }
    }

    if (isset($_GET['check'])) {
        $input = trim($_GET['check']);
        $sentence = '';
        if (stripos($input, ' ') !== false) {
            $sentence = explode(' ', $input);
            foreach($sentence as $item){
                checkSpelling($item, $words);
            }
        }
        else {
            checkSpelling($input, $words);
        }
    }

?>

<!Doctype HTMl>

        <meta charset="utf-8" />
        <title>Spell Check</title>

        <form method="get">
             <input type="text" name="check" autocomplete="off" autofocus />
        </form>

Comment: Have you thought about using an extension like [Enchant](http://php.net/enchant) or [Pspell](http://php.net/pspell)? They have `suggest` functions that basically do what you are trying to do.
Comment: This question might be better suited for http://codereview.stackexchange.com/
Comment: @SverriM.Olsen PSell is not supported in 5.3
Comment: @JayGatz I know, but Enchant is supported.
Comment: @SverriM.Olsen It is? In the documentation it says it requires plugins.
Comment: @JayGatz It is an extension, so yes, it needs to be installed and enabled.
Comment: Will that result in valid HTML? Shouldn't (most of) the PHP code be within the `body` tag?
Answer: Levenshtein over a large list will be pretty processor intensive. Right now if you mistyped refridgerator it would calculate the edit distance to cat dog and pimple.
Too pare the list down before going into the levenstein loop you could match against a precalculated metaphone or soundex key for each of your dictionary entries. This would give you a much shorter list of likely suggestions then you could use levenshtein and similar_text as a means of rank the short list of matches.
Another thing that may help you out is to cache your results. I would venture to guess that most of the misspellings are going to be common.
The following implementation doesn't deal with the paring of the data effectively but it should give you some guidelines on how to dodge the levenshtein distance against the entire dictionary for each word.
First thing you are going to want to do is append the metaphone results to each of your word entries.
This would be a servicable way to do that
<?php
$dict = fopen("dictionary-orig.txt", "r");
$keyedDict = fopen("dictionary.txt", "w");
while ($line = fgets($dict)){
    $line = trim(strtolower($line));
    fputcsv($keyedDict, array($line,metaphone($line)));
}
fclose($dict);
fclose($keyedDict);
?>

Along with this you are going to need something that can read the dictionary into an array
<?php
function readDictionary($file){
        $dict = fopen($file, "r");
        $words = array();
        while($line = fgetcsv($dict)){
                $words[$line[0]] = $line[1];
        }
        return $words;
}
function checkSpelling($input, $words){
    if(array_key_exists($input, $words)){

        return;
    }
        else {
        // sanatize the input
        $input = preg_replace('/[^a-z0-9 ]+/i', '', $input);
        // get the metaphone key for the input
        $inputkey = metaphone($input);
        echo $inputkey."
";
        $suggestions = array();
        foreach($words as $word => $key){
            // get the similarity between the keys
            $percentageSimilarity = 0;
            similar_text($key, $inputkey, $percentageSimilarity);
            if($percentageSimilarity > 90){
                $suggestions[] = array($word, levenshtein($input, $word));
            }
        }
        // rank the suggestions
        usort($suggestions, "rankSuggestions");
        return $suggestions;
    }
}
if(isset($_GET['check'])){
    $words = readDictionary("dictionary.txt");
    $input = trim($_GET['check']);
    $sentence='';
    $sentence = explode(' ', $input);
    print "Searching Words ".implode(",", $sentence);
    foreach($sentence as $item){
        $suggestionsArray = checkSpelling($item, $words);
        if (is_array($suggestionsArray)){
                echo $item, " not found, maybe you meant";
                var_dump($suggestionsArray);
        } else {
                echo "found $item";
        }
    }
}
function rankSuggestions($a, $b){
        return $a[1]-$b[1];
}
?>
<!doctype html>

        <meta charset="utf-8" />
        <title>Spell Check</title>

        <form method="get">
             <input type="text" name="check" autocomplete="off" autofocus />
        </form>

The simplest way to do actual paring of the data would be to split your dictionary into multiple files partitioned by something like the first character in the string. Something along the lines for dict.a.txt, dict.b.txt, dict.c.txt etc.
Comment: Yes, it would do a comparison between cat, dog, and pimple. Ah, okay. Good idea.
Comment: Could you update your answer with how to use `metaphone()` or `soundex()` to create a smaller array and then do the levenshtein comparison between what is in the samller array and the $input ? I have some trouble understanding the output of the metaphone and soundex functions and how I can know what type of output means the words are close in comparison. For similar_text it is a simple percentage.
Comment: If you are willing to help me out with an implementation using soundex() or metaphone could you let me know? Could you please also let me know if you are not willing to give anymore help in your answer?
Comment: sorry afk for the day. will form an example in a few hours
Comment: @jayGatz Updated the answer, code is untested but should steer you in the right direction
Comment: I seemed to understand where you were going with it. But I slightly further developed your code to test it and now not even the HTML is rendering? Also how do I load the new dictionary that is made by the first part of your code. Right now, on line 11, I am loading the only dictionary. Here is the code if you don't mind taking a look at it: http://pastebin.com/g61A1cww
Comment: updated the code this has been tested. One thing I don't think you got was that the first code snippet should be run once to build a new dictionary off of your first. You should not do this for every request, only once and every time you update the dictionary. change the name of your dictionary.txt file to dictionary-orig.txt create a new php file named build-dictionary.php then hit it with the browser. Make sure that the web server can create the new dictionary.txt
Comment: Thank you. And Thank you for testing it. Ah, okay. So only update the dictionary once and on update. Not on each request. That makes sense. Thank you for the help!
Comment: I am getting an error in buildDicitonary.php, the first part of your code, on the line with `fputcsv()` that says expects parameter 1 to be resource, boolean given. [Here is the dictionary-orig.txt](http://the-irf.com/dictionary-orig.txt) that I am trying it with.
Comment: That probably means the web server does not have permission to create the dictionary.txt file. Change the permissions of the directory and try again.
Comment: 773 turned out to be the proper permissions, but now I am getting an HTTP 500 error in the second part of your code. Here is what the server log says: `PHP Parse error:  syntax error, unexpected T_FUNCTION in spellCheck/check.php on line 31` and line 31 is `usort($suggestions, function ($a, $b){`
Comment: what version of php are you using?
Comment: let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/31489/discussion-between-orangepill-and-jaygatz)


Criar uma função javascript para todos os botões da aplicação

Question: Galera, gostaria de criar uma função javascript para todos os botões da aplicação, ou seja, todo botão quando for clicado ele chamará essa função.
Obs: Sem a necessidade de colocar em cada botão o onclick.
Obrigado!!
Comment: @EliseuB. Uma das respostas ([esta aqui](https://pt.stackoverflow.com/a/143220/8063)) não usa jQuery.
Answer:

var buttons = document.getElementsByTagName("button");
var buttonsCount = buttons.length;
for (var i = 0; i < buttonsCount; i += 1) {
    buttons[i].onclick = function(e) {
        alert(this.id);
        // O que quer que ele faça
    };
}
button {
padding: 10px;
font-size: 13px;
}
<button id='1'>Clique</button>
<button id='2'>Clique</button>
<button id='3'>Clique</button>
<button id='4'>Clique</button>
Comment: Resolveu meu problema, obrigado!!!


SQL Agrupar consulta com mais de um atributo distinto

Question: Tenho uma aplicação que gera aproximadamente 25000 registros por dia no BD. Isso irá gerar uma grande quantidade de id's por dia no BD do usuário.
Segundo a regra de negócio do usuário, apenas as inspeções reprovadas (is_ok = 0), devem ser registradas, as que foram aprovadas (is_ok = 1) poderão ser descartadas.
Porém o usuário necessita de um relatório com alguns dados da produção diária feita, como o total de inspeções por modelo feito em cada dia, quantas foram  aprovadas ou reprovadas,
que horas foi feita a primeira inspeção e que horas foi feita a última inspeção.
Pensando em eliminar o fato da geração do grande volume de id's gerados por dia,
ao final de cada dia eu poderia ler essa tabela de INSPECOES,
gravar as que foram reprovadas em uma tabela (INSPECOES_REPROVADAS),
gravar os dados da produção diária em outra tabela (PRODUCAO_DIARIA), apagar a todos os registros da tabela INSPECOES,  e por fim, reiniciar o contador de ID'S preparando assim a tabela para começar um novo registro de inspeções com o id começando novamente em 1.
Preciso fazer um job em um servidor MySql para executar essa tarefa.
Vale lembrar que tenho que gravar as inspeções agrupadas por data e modelo, ou seja, numa mesma data tenho inspeções de mais de um modelo. Não posso somar inspeções de modelos diferentes para uma mesma dada.
Veja o exemplo:
INSPECOES
=========
id      is_ok   serial_number       date_inspection         path            mode    models_id   shift_id    line_id
1       1       BR11S140325004685   2014-08-27 09:50:36                     1       7           1           1
2       1       BR11S140325004663   2014-08-27 09:51:01                     1       7           1           1
3       1       BR11S140325004685   2014-08-27 10:16:39                     1       7           1           1
4       1       BR11S140325004663   2014-08-27 10:17:28                     1       7           1           1
5       0       BR11S140325004685   2014-08-27 10:41:35     c:/bla.abc      1       7           1           1
6       0       BR11S140325004685   2014-08-27 10:42:19     c:/bla.abc      1       7           1           1
7       0       BR11S140325004663   2014-08-27 10:42:34     c:/bla.abc      1       7           1           1
8       1       BR11S140325004685   2014-08-27 11:05:19                     1       7           1           1
9       1       BR11S140325004599   2014-08-27 11:07:33                     1       6           1           1
10      1       BR11S140325004599   2014-08-27 11:30:16                     1       6           1           1
11      1       BR11S140325004685   2014-08-27 11:36:42                     1       6           1           1
12      0       BR11S140325004666   2014-08-27 12:40:14     c:/bla.abc      1       6           1           1
13      0       BR11S140325004663   2014-08-27 12:42:34     c:/bla.abc      1       6           1           1
14      1       BR11S140325004685   2014-08-28 08:55:12                     1       7           1           1
15      1       BR11S140325004685   2014-08-28 08:56:22                     1       7           1           1
16      1       BR11S140325004663   2014-08-28 08:57:44                     1       7           1           1
17      0       BR11S140325004685   2014-08-28 08:59:12     c:/bla.abc      1       7           1           1
18      0       BR11S140325004685   2014-08-28 08:59:40     c:/bla.abc      1       7           1           1
19      1       BR11S140325004685   2014-08-28 10:00:00     c:/bla.abc      1       8           1           1
20      0       BR11S140325004685   2014-08-28 10:00:12     c:/bla.abc      1       8           1           1
21      1       BR11S140325004685   2014-08-28 10:01:30     c:/bla.abc      1       8           1           1
22      0       BR11S140325004685   2014-08-28 10:01:40     c:/bla.abc      1       8           1           1
23      1       BR11S140325004685   2014-08-28 10:08:40     c:/bla.abc      1       8           1           1
24      0       BR11S140325004685   2014-08-28 10:09:40     c:/bla.abc      1       8           1           1

PRODUCAO_DIARIA
===============
id  date        total_inspections   models_id   start_time  end_time
1   2014-08-27  8                   7           09:50:36    11:05:19
2   2014-08-27  5                   6           11:07:33    12:42:34
3   2014-08-28  5                   7           08:55:12    08:59:40
4   2014-08-28  6                   8           10:00:00    10:09:40

O máximo que consegui foi fazer uma query que me mostra as inspeções, mas ela não contabiliza todos os modelos separados. Veja:
select date_inspection, models_id, count(models_id)
from
(
    select *
    from
    (
        select*from Inspecoes where is_ok = 0
    ) as t
    group by date_inspection
)as t
group by models_id;

Porém o retorno dessa query é :
date_inspection     models_id   count(models_id)
2014-08-27 12:40:14 6           2
2014-08-27 10:41:35 7           5
2014-08-28 10:00:12 8           3

Ela volta as contagens erradas e ainda faltam modelos.
Onde estou errando?
Comment: Para o start_time e end_time use o MIN e o MAX respectivamente.
Comment: Ok @Motta, mas ele pega os Min e o Max dá seleção de inspeções que estão com problema pois eu passei o filtro `where is_ok = 0` . Na verdade eu preciso dos horários de início e término da tabela INSPECOES antes de passar o filtro. Como posso fazer isso nessa consulta?
Comment: select date_inspection, models_id, min(date_inspection) start_time , max(date_inspection) end_time , count(models_id)
from ( select *
       from ( select *
              from Inspecoes
              where is_ok = 0 ) as t
group by date_inspection )as t group by models_id; sem levar em conta a questão do filtro que não entendi , o que indica o is_ok !?
Comment: @Motta, obrigado pelas dicas. Eu editei a questão para melhorar o entendimento para você e para outros usuários também.
Answer: Pelo o que entendi, seu problema está em separar os registros por modelo e pela data.
Sua consulta está agrupando apenas pelo modelo. Para que as datas sejam levadas em conta ao agrupar, você precisa adicioná-las ao group by antes de agrupar por modelo.
Ficaria assim
SELECT
    `date_inspection` AS 'date',
    count( `models_id` ) AS 'total_inspections'
    `models_id`,
    DATE_FORMAT( min( `date_inspection` ) ,'%H:%i:%s' ) AS 'start_time',
    DATE_FORMAT( max( `date_inspection` ) ,'%H:%i:%s' ) AS 'end_time'
FROM `Inspecoes`
GROUP BY
    YEAR(`date`),
    MONTH(`date`),
    DAY(`date`),
    `model_id`;

O retorno dever ser como desejado.
Caso seja importante saber o número de inspeções que ocorreram bem ou não, vc pode adicionar um contador condicional, ficando da seguinte forma:
SELECT
    `date_inspection` AS 'date',
    COUNT( `models_id` ) AS 'total_inspections'
    `models_id`,
    DATE_FORMAT( MIN( `date_inspection` ), '%H:%i:%s' ) AS 'start_time',
    DATE_FORMAT( MAX( `date_inspection` ), '%H:%i:%s' ) AS 'end_time',
    COUNT( IF( `is_ok` = "1", 1, null ) ) AS 'success',
    COUNT( IF( `is_ok` = "0", 1, null) ) AS 'error'
FROM `Inspecoes`
GROUP BY
    YEAR( `date` ),
    MONTH( `date` ),
    DAY( `date` ),
    `model_id`;

Obs.: Observe que deixo claro na consulta o que é tabela, campo, valor ou palavra-chave usando aspas, apóstrofo ou letra maiúscula. Isso não só ajuda na leitura como evita erros de execução da query. Recomendo começar a fazer o mesmo.
Comment: Perfeito @marcusagm. Exatamente o que eu precisava. Obrigado.
Comment: Que bom! As ordens =]


Drush restore to proper folder level

Question: Before working on a site, I take a quick dump of a site via drush arb --destination=/var/backup/latest.tgz --overwrite from the root level /var/www/html.
However, on the rare occasion that I need to restore via drush arr ../backup/latest.rgz --overwrite, I end up with a restored database but the file structure is written to /var/www/html/html.
Would drush arr ../backup/latest.rgz --overwrite --destination=/var/www/ solve this issue? Do I just continue to muddle through withmv /var/www/html/html* /var/www/html?
How can I get drush to write to the actual root level for the default drupal site?
Answer: the --destination flag surely works to say where. I'm not quite sure if the outcome would be a mix of the former and the latter system though. Probably the writing does not delete the old files. It would be safer to delete them manually prior to archive recover.

Drush restore to proper folder level


Como definir uma propriedade privada no Python? E existe propriedade protegida?

Question: Eu venho do PHP. Nele, quando queremos definir uma propriedade de uma classe como privada adicionarmos a palavra chave private na sua declaração.
Exemplo:
class StackOverflow extends StackExchange
{
    private $language = 'en'; // privado, só pode ser acessado via Accessor!

    public function __construct($language === null){

            if ($language !== null) {
                $this->language = $language;
            }

    }

    public function getLanguage()
    {
        return $this->language;
    }
}

Agora gostaria de saber como fazer isso no Python. Como definir a propriedade privada nesse exemplo abaixo.
class StackExchange(object):
    def __init__(self):
        pass

class StackOverflow(StackExchange):

    language = 'en' // quero que seja privado ou protegido!

    def __init__(self, language = None):
        if language is not None:
            self.language = language

sopt = StackOverflow('pt')
sopt.language // retorna o valor, mas quero utilizar um Accessor ao invés disso

Outra coisa: No PHP, utilizamos protected para definir que a propriedade não pode ser acessada na instanciação da classe, porém pode ser acessada por ela mesma e por quem a herda.
Tem como fazer isso no Python também?
Answer: Em Python não existe esse conceito de propriedade privada.
Seguindo o PEP 8 - Style Guide for Python Code, você pode utilizar o __ na frente de um método como uma convenção. Lembrando que seu método não será "privado", mas seria uma espécie de convenção para quem vê seu código saber que esse método (ou variável) só deve ser utilizado na classe pai.
Segue um trecho do PEP 0008:

If your class is intended to be subclassed, and you have attributes
  that you do not want subclasses to use, consider naming them with
  double leading underscores and no trailing underscores. This invokes
  Python's name mangling algorithm, where the name of the class is
  mangled into the attribute name. This helps avoid attribute name
  collisions should subclasses inadvertently contain attributes with the
  same name.
Comment: E sempre dará. Como dito acima, não existe o conceito de variável privada.
Comment: Ainda assim, dá pra acessar a variável através de `_StackOverflow__language`, como no exemplo que ele pediu.
Comment: Nem um enclausuramentozinho básico?
Comment: O mais perto que chega disso é utilizando __ em métodos ou variáveis. Nesse caso eles não poderão ser chamados publicamente...
Answer: Conforme a resposta do @JoãoPedroAlves, não existe propriedade privada.
Para propriedades protegidas, seria um esquema usando os modificadores @property e @nomedaproperty.setter:
class StackExchange(object):
    def __init__(self):
        pass

class StackOverflow(StackExchange):
    # Coloque sua variável dentro de __init__, o que "evita" que ela vire pública.
    # Ela ainda é acessível através de _StackOverflow__language.
    def __init__(self, language = None):
        self.__language = 'en'
        if language is not None:
            self.__language = language

    @property # Objeto.language cai aqui
    def language(self):
        return self.__language

    @language.setter # Objeto.language = 'pt' cai aqui
    def name(self, language):
        self.__language = language

Aqui você pode testar.
Comment: Só para refrescar meu cérebro? São dois underlines? tipo len('__') `2`?
Comment: Sim. Exatamente.


Can Adjusted R squared be equal to 1?

Question: I have a dataset with around 15 independent variables. I am using a multi-regression model to fit the dataset. For model selection, I am using a backward elimination procedure based on the p-values. The adjusted R^2 for the model with all predictors is exactly 1. At this point, I concluded that maybe the model is also picking up noise. But, based on the model selection I removed 5 predictor variables and still the adjusted R^2 is 1. I am not sure if this correct or I am just modeling noise. Can someone comment on this?
Comment: That shouldn't happen. You should be able to find out if all the residuals are 0. That is the only way the unadjusted R$^2$ can be 1.
Answer: Dan and Michael point out the relevant issues. Just for completeness, the relationship between adjusted $R^2$ and $R^2$ is given by (see, e.g., here)
$$
R^2_{adjusted}=1-(1-R^2)\frac{n-1}{n-K},
$$
(with $K$ the number of regressors, including the constant). This shows that $R^2_{adjusted}=1$ if $R^2=1$, unless (see below) $K=n$.
$R^2=1$ occurs when all residuals $\hat u_i=y_i-\hat y_i$ are zero, as
$$
R^2=1-\frac{\hat{u}'\hat{u}/n}{\tilde{y}'\tilde{y}/n}.
$$
Here, $\hat u$ denotes the vector of residuals and $\tilde y$ the vector of demeaned observations on the dependent variable.
Dan discusses one reason to get an $R^2$ of 1. Another is to have as many regressors as observations, i.e., $K=n$.
Technically, this is because the $n\times K$ regressor matrix $X$ then is square. The OLS estimator $\hat\beta=(X'X)^{-1}X'y$ can then be written as (assuming no exact multicollinearity)
$$
\hat\beta=(X'X)^{-1}X'y=X^{-1}{X'}^{-1}X'y=X^{-1}y
$$
so that the fitted values $\hat y=X\hat\beta$ are just $\hat y=XX^{-1}y=y$, so that all residuals are zero.
Here is an illustration using artificial data (code below), in which regressors are generated totally independently of $y$, and yet we achieve an $R^2$ of 1 once we have as many of them as we have observations.

Code:
n <- 15
regressors <- n-1 # enough, as we'll also fit a constant
y <- rnorm(n)
X <- matrix(rnorm(regressors*n),ncol=regressors)

collectionR2s <- rep(NA,regressors)
for (i in 1:regressors){
  collectionR2s[i] <- summary(lm(y~X[,1:i]))$r.squared
}
plot(1:regressors,collectionR2s,col="purple",pch=19,type="b",lwd=2)
abline(h=1, lty=2)

When $K=n$, R however, correctly, does not report an adjusted $R^2$:
> summary(lm(y~X))

Call:
lm(formula = y ~ X)

Residuals:
ALL 15 residuals are 0: no residual degrees of freedom!

Coefficients:
            Estimate Std. Error t value Pr(>|t|)
(Intercept)  2.36296         NA      NA       NA
X1          -1.09003         NA      NA       NA
X2           0.39177         NA      NA       NA
X3           0.19273         NA      NA       NA
X4           0.51528         NA      NA       NA
X5          -0.04530         NA      NA       NA
X6          -1.28539         NA      NA       NA
X7          -0.72770         NA      NA       NA
X8          -0.14604         NA      NA       NA
X9           0.34385         NA      NA       NA
X10         -0.93811         NA      NA       NA
X11          2.23064         NA      NA       NA
X12          0.06744         NA      NA       NA
X13          0.21220         NA      NA       NA
X14         -2.29134         NA      NA       NA

Residual standard error: NaN on 0 degrees of freedom
Multiple R-squared:      1, Adjusted R-squared:    NaN
F-statistic:   NaN on 14 and 0 DF,  p-value: NA

Comment: Ouch, I should have seen that this was not the right expression to connect the adjusted and standard $R^2$. I hope that my edit fixes this.
Comment: Do you want to expand on what u hat and y tilde are? I wonder how many cases the OP has as too few cases can easily lead to perfect prediction.
Comment: Right, I should have spelled out all my notation in the first place. I agree it would be helpful information to know the sample size OP has access to.
Comment: By quoting an unnecessarily limited formula for the adjusted $R^2$ (which applies only to the ordinary regression situation but not to multiple regression) you arrive at an incorrect conclusion: the adjusted $R^2$ isn't even defined when there are as many regressors as observations.  It's certainly not equal to unity in that case!
Answer: An adjusted R squared equal to one implies perfect prediction and is an indication of a problem in your model. Adjusted R squared is a penalised version of R square, which is a way of describing the ratio of the residual sum of squares to the total sum of squares - as you approach 1 the implication is that there is no variation/deviation away from your model.
I would suggest you begin by looking at a correlation matrix, or put each predictor into your model individually to see which predictor is causing the issue.
In R, you will get a warning from lm: "essentially perfect fit..."
In the (single predictor) example below you will see that adjusted R square is less than 1 even when the correlation between y and x is greater than 0.99.
# create a data frame with some strongly correlated variables
myData<- data.frame(y = rnorm(n = 1000, mean = 0, sd = 1))
myData$x1<- myData$y
myData$x2<- jitter(myData$x1, factor = 10)
myData$x3<- jitter(myData$x1, factor = 1000)

# fit models
myModel1<- lm(y ~ x1, data = myData)
myModel2<- lm(y ~ x2, data = myData)
myModel3<- lm(y ~ x3, data = myData)

# output
summary(myModel1)
#> Warning in summary.lm(myModel1): essentially perfect fit: summary may be
#> unreliable
#>
#> Call:
#> lm(formula = y ~ x1, data = myData)
#>
#> Residuals:
#>        Min         1Q     Median         3Q        Max
#> -4.551e-15 -1.200e-17  6.000e-18  2.090e-17  3.455e-16
#>
#> Coefficients:
#>              Estimate Std. Error   t value Pr(>|t|)
#> (Intercept) 1.404e-17  4.924e-18 2.852e+00  0.00444 **
#> x1          1.000e+00  5.085e-18 1.966e+17  < 2e-16 ***
#> ---
#> Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
#>
#> Residual standard error: 1.553e-16 on 998 degrees of freedom
#> Multiple R-squared:      1,  Adjusted R-squared:      1
#> F-statistic: 3.867e+34 on 1 and 998 DF,  p-value: < 2.2e-16
summary(myModel2)
#>
#> Call:
#> lm(formula = y ~ x2, data = myData)
#>
#> Residuals:
#>        Min         1Q     Median         3Q        Max
#> -1.996e-03 -9.643e-04 -1.996e-05  1.009e-03  2.034e-03
#>
#> Coefficients:
#>              Estimate Std. Error  t value Pr(>|t|)
#> (Intercept) 3.278e-06  3.647e-05     0.09    0.928
#> x2          1.000e+00  3.766e-05 26550.25   <2e-16 ***
#> ---
#> Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
#>
#> Residual standard error: 0.00115 on 998 degrees of freedom
#> Multiple R-squared:      1,  Adjusted R-squared:      1
#> F-statistic: 7.049e+08 on 1 and 998 DF,  p-value: < 2.2e-16
summary(myModel3)
#>
#> Call:
#> lm(formula = y ~ x3, data = myData)
#>
#> Residuals:
#>       Min        1Q    Median        3Q       Max
#> -0.214135 -0.097828 -0.003721  0.099000  0.226453
#>
#> Coefficients:
#>              Estimate Std. Error t value Pr(>|t|)
#> (Intercept) -0.001598   0.003602  -0.444    0.657
#> x3           0.983900   0.003685 266.982   <2e-16 ***
#> ---
#> Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
#>
#> Residual standard error: 0.1136 on 998 degrees of freedom
#> Multiple R-squared:  0.9862, Adjusted R-squared:  0.9862
#> F-statistic: 7.128e+04 on 1 and 998 DF,  p-value: < 2.2e-16

cor(myData$x1, myData$x2)
#> [1] 0.9999993
cor(myData$x1, myData$x3)
#> [1] 0.9930721

Can Adjusted R squared be equal to 1?


React webpackage webpack-obfuscator: Cannot find module 'object-assign'

Question: I'am tryng to use a webpack-obfuscator inside a React project. I added the configuration in order to obfucate the source code, but not the imported librariers, but I get this error message while luncing the command to create the webpack:
npm run dev

webpack Cannot find module 'object-assign'
Below the configuration I have for this project:
package.json
{
  "name": "xyz",
  "version": "1.0.0",
  "private": true,
  "homepage": "/apps/",
  "dependencies": {
    "@date-io/date-fns": "^1.3.13",
    "@date-io/moment": "^2.6.0",
    "@fortawesome/fontawesome-svg-core": "^1.2.28",
    "@fortawesome/free-solid-svg-icons": "^5.13.0",
    "@fortawesome/react-fontawesome": "^0.1.9",
    "@material-ui/core": "^4.8.2",
    "@material-ui/icons": "^4.5.1",
    "@material-ui/lab": "^4.0.0-alpha.39",
    "@material-ui/pickers": "^3.2.10",
    "apexcharts": "^3.28.1",
    "babel-preset-es2015": "^6.24.1",
    "crypto-browserify": "^3.12.0",
    "crypto-random-string": "^4.0.0",
    "cypress": "^9.1.1",
    "date-fns": "^2.14.0",
    "dayjs": "^1.8.28",
    "fetch-retry": "^3.1.0",
    "i18next": "^21.5.4",
    "i18next-browser-languagedetector": "^6.1.2",
    "i18next-http-backend": "^1.3.1",
    "isomorphic-fetch": "^3.0.0",
    "jwt-decode": "^3.1.2",
    "moment": "^2.26.0",
    "mui-datatables": "^2.15.0",
    "multimatch": "^6.0.0",
    "npm": "^7.16.0",
    "process": "^0.11.10",
    "prop-types": "^15.8.1",
    "react": "^16.14.0",
    "react-alert": "^7.0.3",
    "react-apexcharts": "^1.3.9",
    "react-async": "^10.0.0",
    "react-avatar": "^3.9.0",
    "react-custom-scrollbars": "^4.2.1",
    "react-dom": "^16.14.0",
    "react-filter-box": "^3.4.2",
    "react-grid-layout": "^0.17.1",
    "react-helmet": "^6.1.0",
    "react-i18next": "^11.14.3",
    "react-image-mapper": "0.0.15",
    "react-lineto": "^3.2.1",
    "react-native-svg": "^12.1.1",
    "react-number-format": "^4.4.1",
    "react-responsive-carousel": "^3.2.18",
    "react-router-dom": "^5.1.2",
    "react-scripts": "^4.0.3",
    "react-split-pane": "^0.1.89",
    "react-svg-pathline": "^0.5.0",
    "react-youtube": "^7.11.2",
    "recharts": "^1.8.5",
    "stream": "^0.0.2",
    "typescript": "^3.7.0-dev"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject",
    "dev": "webpack serve",
    "production": "webpack --mode production"
  },
  "eslintConfig": {
    "extends": "react-app"
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  },
  "devDependencies": {
    "@babel/core": "^7.19.0",
    "@babel/preset-env": "^7.19.0",
    "@babel/preset-react": "^7.18.6",
    "babel-loader": "^8.2.5",
    "clean-webpack-plugin": "^4.0.0",
    "css-loader": "^6.7.1",
    "csv-loader": "^3.0.5",
    "file-loader": "^6.2.0",
    "html-loader": "^4.1.0",
    "html-webpack-plugin": "^5.5.0",
    "interpolate-html-plugin": "^4.0.0",
    "javascript-obfuscator": "^4.0.0",
    "mini-css-extract-plugin": "^2.6.1",
    "node-sass": "^7.0.1",
    "object-assign": "^4.1.1",
    "papaparse": "^5.3.2",
    "sass-loader": "^13.0.2",
    "webpack": "^5.74.0",
    "webpack-cli": "^4.10.0",
    "webpack-dev-server": "^4.10.1",
    "webpack-obfuscator": "^3.5.1",
    "xml-loader": "^1.2.1"
  }
}

.babelrc
{
 "presets": ["@babel/preset-env", "@babel/preset-react"]
}

webpack.config.js
'use strict';

const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const InterpolateHtmlPlugin = require("interpolate-html-plugin");
const WebpackObfuscator = require('webpack-obfuscator');

const webpack = require('webpack');
//const multimatch = require('multimatch');

const publicUrl = process.env.PUBLIC_URL;

module.exports = {
 mode: "development",
 entry: {
    app: "./src/index.js"
 },
 devtool: 'source-map', //'eval',
 devServer: {

    static: {
        directory: path.join(__dirname, 'public'),
        staticOptions: {
          index: false
        }
      },
      liveReload: false,
      compress: true,
      port: 80,
      open: true,
      hot: false,
      client: false,
      historyApiFallback: false

 },
 output: {
    filename: '[name].js',
    path: path.resolve(__dirname, 'dist'),
    publicPath: "/"
  },
 resolve: {
   extensions: [".wasm", ".mjs", ".js", ".jsx", ".ts", ".tsx", ".json"], // ['*', '.js', '.jsx'],
   alias: {
     '@': path.resolve(__dirname, 'src') // shortcut to reference src folder from anywhere

   },
    fallback: {
        crypto: require.resolve('crypto-browserify'),
        assert: require.resolve('assert'),
        console: require.resolve('console-browserify'),
        constants: require.resolve('constants-browserify'),
        domain: require.resolve('domain-browser'),
        events: require.resolve('events'),
        http: require.resolve('stream-http'),
        https: require.resolve('https-browserify'),
        os: require.resolve('os-browserify/browser'),
        path: require.resolve('path-browserify'),
        punycode: require.resolve('punycode'),
        process: require.resolve('process/browser'),
        querystring: require.resolve('querystring-es3'),
        stream: require.resolve('stream-browserify'),
        string_decoder: require.resolve('string_decoder'),
        sys: require.resolve('util'),
        timers: require.resolve('timers-browserify'),
        tty: require.resolve('tty-browserify'),
        url: require.resolve('url'),
        vm: require.resolve('vm-browserify'),
        zlib: require.resolve('browserify-zlib'),
        isomorphic: require.resolve('isomorphic-fetch'),
        log: false,
        object_assign: require.resolve('object-assign'),
        scheduler: require.resolve('scheduler')
    }

 },
 module: {
   rules: [

     { // config for es6 jsx
       test: /\.(js|jsx)$/,
       exclude: /node_modules/,
       use: {
         loader: "babel-loader"
       }
     },
     { // config for sass compilation
       test: /\.scss$/,
       use: [
         {
           loader: MiniCssExtractPlugin.loader
         },
         'css-loader',
         {
           loader: "sass-loader"
         }
       ]
     },
     {
        test: /\.css$/,
        use: [
          // [style-loader](/loaders/style-loader)
          { loader: 'style-loader' },
          // [css-loader](/loaders/css-loader)
          {
            loader: 'css-loader',
            options: {
              modules: true
            }
          },
          // [sass-loader](/loaders/sass-loader)
          { loader: 'sass-loader' }
        ]
      },
     { // config for images
       test: /\.(png|svg|jpg|jpeg|gif)$/,
       type: 'asset/resource',
       exclude: /node_modules/,
       use: ['file-loader?name=[name].[ext]']
     },
     { // config for fonts
       test: /\.(woff|woff2|eot|ttf|otf)$/,
       use: [
         {
           loader: 'file-loader',
           options: {
             outputPath: 'fonts',
           }
         }
       ],
     },
     {
        test: /\.html$/i,
        loader: "html-loader",
      },

      {
        test: /\.js$/,

        exclude: [
            //path.resolve(__dirname, 'content.js')
            path.resolve(__dirname, 'node_modules/react/index.js')
        ],

        enforce: 'post',
        //exclude: /node_modules/,
        use: {
            loader: WebpackObfuscator.loader,
            options: {
                rotateStringArray: true
            }
        }
      }
   ],
   noParse: [require.resolve('typescript/lib/typescript.js')]
 },
 plugins: [

  new WebpackObfuscator ({
    rotateStringArray: true
  }),
  new webpack.ProvidePlugin({
    process: 'process/browser',
  }),
   new HtmlWebpackPlugin({ // plugin for inserting scripts into html
    template: path.resolve(__dirname, "public/index.html"),
    inject: true,
    PUBLIC_URL: publicUrl
   }),
   new MiniCssExtractPlugin({ // plugin for controlling how compiled css will be outputted and named
     filename: "css/[name].css",
     chunkFilename: "css/[id].css"
   }),
   new InterpolateHtmlPlugin({
    PUBLIC_URL: ''
  })

 ]
};

Can anybody help on this?
Thanks in advance
Answer: Try in your terminal
npm install object-assign


Touch button on DWIN DGUS Software for switching pages and incrementing value both

Question: On my DGUS software, I need a touch button which sends a message to the microcontroller (to perform a task) and also switches between pages. Which functionality under "Touch Control" should I use?
I tried Basic Touch control (to switch page) and Increment Adjustment (to send message) but they overlap and only one happens which is on the top.
Answer: You must use "-Return key code", check Data auto-uploading and in page switching choose destination page. VP will be your variable address, key value will be value which will be store in this address after pressing the area. If VP = 2000, key value = 2001 display return through RS232 when you press area-  5A A5 06 83 20 00 01 20 01
if VP = 2222 KeyValue = 000A ---->  5A A5 06 83 22 22 01 00 0A


How do I reference the value of a constructed environment variable in a loop?

Question: What I'm trying to do is loop over environment variables.  I have a number of installs that change and each install has 3 IPs to push files to and run scripts on, and I want to automate this as much as possible (so that I only have to modify a file that I'll source with the environment variables).  The following is a simplified version that once I figure out I can solve my problem.
So given in my.props:
COUNT=2
A_0=foo
B_0=bar
A_1=fizz
B_1=buzz

I want to fill in the for loop in the following script
#!/bin/bash
. <path>/my.props

for ((i=0; i < COUNT; i++))
do


Push key always null

Question: I want to use push notification in android but the push key is always null. what might be the reason? I have a professional account which supports push notification. When I debug the app in devices, the pushkey value is always null.
Code:
String pushKey = Push.getPushKey();
System.out.println("push " + pushKey );

Answer: Push key will only return a valid value after registeredForPush is invoked. You need to register then when registration succeeds the key will be valid.
If it doesn't you will get an error.
Notice this works on the device. You can simulate this process in the push console in the simulator.

Push key always null


Getting State of Toggle Button in Android

Question: I am trying to make a list view in which every item has two things, a description in textview and a toggle button. The details in the textview are dynamically loaded by the AsyncTask. At the end of the listview, I have inserted a button programatically. When that button is clicked, I need to get the data in all the textviews and the states of all the ToggleButtons. This is the Code that I have used:
XML FILE
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#dfdede"
android:focusable="true"
android:focusableInTouchMode="false">

<TextView
    android:id="@+id/textView1"
    android:layout_width="wrap_content"
    android:layout_height="30dp"
    android:layout_alignParentLeft="true"
    android:layout_centerVertical="true"
    android:layout_marginLeft="10dp"
    android:layout_marginTop="15dp"
    android:textColor="#000000"
    android:textSize="20dp" />

<ToggleButton
    android:id="@+id/toggle1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentRight="true"
    android:layout_centerVertical="true"
    android:checked="true"
    android:text="ToggleButton" />

<View
    android:layout_width="fill_parent"
    android:layout_height="2dp"
    android:layout_alignBottom="@id/textView1"
    android:background="#49656565" />

public class MarkAttendance extends ListActivity {

String url = "http://192.168.173.1:8080/WebApplication1/androidrollsheet.jsp";
String pid = "";
ArrayList<String> array = new ArrayList<String>();

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    pid = getIntent().getStringExtra("pid");
    new LoadRollSheet().execute();

    final ListView lv = getListView();
    Button submitButton = new Button(this);
    submitButton.setText("Submit");
    lv.addFooterView(submitButton);

    submitButton.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            ListAdapter adapter = lv.getAdapter();
            int total = adapter.getCount() - 1;
            for (int i = 0; i < total; i++) {
                View rowview = adapter.getView(i, null, lv);
                TextView textView = (TextView) rowview.findViewById(R.id.textView1);
                ToggleButton toggle1 = (ToggleButton) rowview.findViewById(R.id.toggle1);
                String studentDetails = textView.getText().toString();
                String value = String.valueOf(toggle1.getText());
                Log.i("VALUE ???? ", value);
            }
        }
    });
}

@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
    String item = (String) getListAdapter().getItem(position);
    Toast.makeText(this, item + " selected", Toast.LENGTH_LONG).show();
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.activity_mark_attendance, menu);
    return true;
}

private ProgressDialog pDialog;

class LoadRollSheet extends AsyncTask<String, String, String> {
    /**
     * Before starting background thread Show Progress Dialog
     */
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pDialog = new ProgressDialog(MarkAttendance.this);
        pDialog.setMessage("Loading products. Please wait...");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(false);
        pDialog.show();
    }

    protected String doInBackground(String... args) {
        // Building Parameters
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("pid", pid));
        // getting JSON string from URL
        JSONParser jParser = new JSONParser();
        JSONObject json = jParser.makeHttpRequest(url, "GET", params);
        // Check your log cat for JSON reponse
        Log.d("All Entries: ", json.toString());
        //getting Sections array from JSON object
        JSONArray rollSheet = null;
        try {
            rollSheet = json.getJSONArray("RollSheet");
            //looping through all sections
            for (int i = 0; i < rollSheet.length(); i++) {
                JSONObject entry = rollSheet.getJSONObject(i);
                int rollNo = entry.getInt("rollNo");
                int userId = entry.getInt("userId");
                String studentName = entry.getString("studentName");

                String value = rollNo + "  " + studentName;
                array.add(value);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * After completing background task Dismiss the progress dialog
     **/
    protected void onPostExecute(String file_url) {
        // dismiss the dialog after getting all products
        pDialog.dismiss();
        // updating UI from Background Thread
        runOnUiThread(new Runnable() {
            public void run() {
                ArrayAdapter<String> adapter = new ArrayAdapter<String>(getApplicationContext(), R.layout.activity_mark_attendance, R.id.textView1, array);
                setListAdapter(adapter);
                ((BaseAdapter) getListAdapter()).notifyDataSetChanged();
            }
        });
    }
}

}
But, the problem is that I am able to correctly get the String in the text views but not the state of the toggle button. It always comes out to be the default state that is ON in this case. Any help with this will be very nice :(
Comment: Why don't you set a separate flag that changes whenever the button state changes?
Comment: Actually I dont know How many toggle buttons will appear as it totally depends on the number of entries I get from the JSON object
Comment: @durbnpoisn any pointers?
Answer: This should do the trick;
final Boolean toggleState = toggle1.isChecked();

Comment: Code should be formatted with [Markdown](https://stackoverflow.com/editing-help).
Comment: @223seneca sorry.
Comment: Nothing to be sorry about, just trying to help. :-)
Answer: I believe you can use isChecked(), can't you?
EDIT: Another try, does this work (?) :
ToggleButton toggle = (ToggleButton)findViewById(R.id.toggle);
toggle.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        Log.e(TAG, String.valueOf(isChecked));
    }
});

Comment: I tried using that but it gives the same value for all the toggle buttons same as the getText()
Comment: I'll just check and come
Comment: How do I do this for all the toggle buttons that appear ? I dont know the count
Comment: I suggest you to create your own adapter, it should be easier to set a listener on each toggle... http://stackoverflow.com/questions/6305899/custom-listview-android


Dirac Notation Confusion

Question: I am trying to  express the vectors $0\choose 1$ and  $1\choose 0$ in dirac notation wrt the basis {|$0\rangle,$|$1\rangle$}
How do I distinguish  between the above two vectors given that all vectors take the form
$\lambda_{1}$|$0\rangle$ $+$ $\lambda_{2}$|$1\rangle$?
Comment: What do you mean by distinguishing those two vectors? Also, the proper formatting would be $|0\rangle$ where you use \rangle instead of >.
Comment: Thanks. I don't understand how I would write these two vectors in dirac notation.
Answer: Hint.
You  have the answer in the linear combination that you have write ,  interpreting $\lambda _1$ as the first component and $\lambda_2$ as the second component.
$$
\lambda_1|0\rangle + \lambda_2|1\rangle=(\lambda_1,\lambda_2)^T
$$
Answer: This is more like a comment but it's too long so I'll put this as an answer instead.
Well, it depends. There's no rule on how you put things inside the $|\dots \rangle$, sometimes it's used to denote the eigenvalue of the vector, e.g.
$$
A|n\rangle=\lambda_n|n\rangle
$$
.In this case $|n\rangle$ is used to denote the $n^{th}$ eigenvector of the operator $A$. Sometimes they use it to denote the spin or other properties of the quantum state like $|s, m_s\rangle$ or $|n,l\rangle$, etc.
In your case, you'll need the explicit description of $|0\rangle,|1\rangle$ to proceed. Maybe it's defined
$$
{0\choose 1}=|0\rangle\ \ , {1\choose 0}=|1\rangle
$$
or vise versa.

Dirac Notation Confusion


Maximum area for minimum perimeter of a triangle

Question: Does the fact that a triangle has the maximum area for a given perimeter when it is an equilateral triangle (Isoperimetric Property of Equilateral Triangles) imply that the ratio of a triangle's area to its perimeter will have a maximum when all side lengths are equal? I found the derivative of Heron's formula for area divided be perimeter for an isosceles triangle and this is not the case. The ratio is at a maximum when the third side is $\sqrt5 - 1$ times the length of the two equal sides, which interestingly enough comes out to be $2(\phi - 1).$
Comment: There's a problem of units when taking a ratio of area to perimeter.  Depending on your choice of units the same triangle can have such a ratio that is arbitrarily large or arbitrarily small, and if you fix a unit of length, the ratio can be made arbitrarily large or arbitrarily small by changing the size of the triangle,
Comment: Will do, thank you.
Comment: Welcome to stackexchange. Are you sure your calculus/algebra is right? They symmetry of Heron's formula implies symmetry in the triangle for which the area is maximum. Perhaps the problem is in the units, as @hardmath comments.
Answer: Well, even for a square, your question is not very interesting. The maximum of area-perimeter ratio is $+\infty$. Just magnify your triangle or square, area increases quadratically, while perimeter only linearly increases.
Answer: You should take a ratio of area to the perimeter squared to get meaningful (independent from the scale/units) results.
And yes, then the ratio is maximum for equilateral triangle.
Answer: Area and perimeter have different unites so the ratio changes with  the size of triangle.
The ratio  of the area of an equilateral triangle of size $a$ to its perimeter is  $$R=\frac {a\sqrt 3}{12}$$
As you see, the ration grows with the size of triangle.
For $a=4\sqrt 3$  we have $R=1$ and the ratio grows to $\infty$ as the triangle enlarges.
Answer: This is a demo to show that the interpretation of Heron is wrong. I have not had good luck with him either so perhaps misreading him is just a common thing. Note: D is used for area because it is the fourth term of a cubic equation that often results in area computations and it avoids confusion with sides or vertices A,B,C of any triangles used.

Given a triangle with $P=240$ we will let  $(\sqrt{5}-1)x$ be the base.

$$\big(\sqrt5 - 1\big)x+2x=240\implies x=\frac{240}{\sqrt{5}+1}\approx 74.16\\
\implies (\sqrt{5}-1)x\approx 91.67
\implies h=\sqrt{74.16^2-\bigg(\frac{91.67}{2}\bigg)^2}\approx 58.2997...\\
\implies D=area=\bigg(\frac{91.67}{2}\bigg)\cdot 58.2997\approx 2672.17$$

In comparison, an equilateral triangle where $P=240$ has sides of $80$.
$$x=80\implies h=\sqrt{80^2-40^2}\approx 69.28\\
\implies D=area= 40\cdot 69.28\approx 2771.2$$

The equilateral triangle has the larger area for the same perimeter and the larger D/P ratio.
$$
\frac{D_1}{P}=\frac{2672.17}{240}\approx 11.134\\
\frac{D_2}{P}=\frac{2771.2}{240}\approx 11.546$$


Adicionar Class se corresponder a um padrão

Question: Eu estou a tentar fazer com que adicione uma Class à um elemento através do seu ID caso ele seja um certo gênero de padrão.

if (/^([0-9]{4}[\-]?[0-9]{3})$/.test('#codigoPost')) {
  $('#codigoPost').removeClass("is-invalid");
  $('#codigoPost').addClass("is-valid");
} else {
  $('#codigoPost').removeClass("is-valid");
  $('#codigoPost').addClass("is-invalid");
}
.is-valid(
border: 1px solid red;
)

.is-invalid(
border: 1px solid green;
)

<form>

    Código Postal
    <input type="number" class="form-control" name="codigoPost" id="codigoPost" pattern="[0-9]{4}[\-]?[0-9]{3}" placeholder="0000-000" required="true">

</form>

Basicamente, se for do gênero "1234-123", "2222-333" ou "9876-543". 4 números, seguido de um "-" e seguido de 3 números adiciona a class.
Mas não estou a ver o que estou a fazer mal aqui, ele dá sempre false entrando no else. Agradeceria ajuda.
Comment: @Lodi Assim fica melhor?
Comment: coloca o resto o html também se não fica impossível de testar seu snippet pelo fato de não existir nenhum elemento com esse #id
Answer: Coloquei a função no evento de onkeyup, troquei o tipo do input estava number para text.
Motivo: Como number toda vez que entrar um carácter que não seja numero invalida o valor no input, como você espera um - não pode ser number.
Acertei o style que estava com () ao invés de {} e coloquei a cor vermelha no invalid e a verde no valid, tirei o outline do input para ver melhor no snippet

function teste(){
    var self = $(this),
        valor = self.val(),
        result_teste = /^([0-9]{4}[\-]?[0-9]{3})$/.test(valor);
    console.log( valor, result_teste );
    if ( result_teste ) {
      self.removeClass("is-invalid").addClass("is-valid");
    } else {
      self.removeClass("is-valid").addClass("is-invalid");
    }
 }

 $('#codigoPost').on('keyup',teste);
input{ outline:none; }
.is-valid{
border: 1px solid green;
}

.is-invalid{
border: 1px solid red;
}

<form>

    Código Postal
    <input type="text" class="form-control" name="codigoPost" id="codigoPost" pattern="[0-9]{4}[\-]?[0-9]{3}" placeholder="0000-000" required="true">

</form>
Comment: Muito obrigado acho que o meu maior problema era ter o tipo como ```number``` e nao como ```text``` mas simplifico o codigo com isto muito obrigado :)


decltype() of captured variable in lambda: GCC bug and/or Clang bug?

Question: I've checked the GCC buglist and the Clang buglist and don't see anything relevant yet.
This Wandbox link shows some C++11/C++14 code exercising decltype(x) and decltype((x)) for various kinds of x captured by lambdas. GCC and Clang give different answers for this code. Which of them, if either, is correct?
Here's the offending snippet:
// inside main()
int i = 42;
int &j = i;
[j=j](){
    static_assert(std::is_same<decltype(j), GCC(const) int>::value,""); // A
    static_assert(std::is_same<decltype((j)), const int&>::value,""); // B
}();
[=](){
    static_assert(std::is_same<decltype(j), int&>::value,""); // C
    static_assert(std::is_same<decltype((j)), CLANG(const) int&>::value,""); // D
}();

where:
#ifdef __clang__
 #define CLANG(x) x
 #define GCC(x)
#else
 #define GCC(x) x
 #define CLANG(x)
#endif

I believe that in both cases, the thing that is actually captured(*) is a (non-const) int initialized to a copy of j's value (that is to say, i's value). Since the lambda isn't marked mutable, its operator() is going to be a const member function. With those prerequisites out of the way, let's proceed...
On line // A, GCC tells me that the decltype of the explicitly init-captured j is const int, when I'm almost positive that it ought to be int (per Clang).
On line // B, both compilers agree that (j) is an lvalue referring to a const int (since the lambda is not marked mutable); this makes perfect sense to me.
On line // C, both compilers agree that j is a name referring to the int& declared on line 2. This is a consequence of 5.1.2 [expr.prim.lambda]/19, or rather, a consequence of the-thing-that-happens-when-that-clause-is-not-being-invoked. Inside a [=] lambda, the name j refers to the j in the outer scope, but the expression (j) refers to the (j) that would exist if j were to have been captured. I don't fully understand how this works or why it's desirable, but there it is. I'm willing to stipulate that this is not a bug in either compiler.
On line // D, Clang tells me that (j) is an lvalue referring to a const int, whereas GCC tells me that it's an lvalue referring to a non-const int. I'm pretty sure that Clang is right and GCC is wrong; decltype((j)) should be the same whether j is captured implicitly or explicitly.
So:

Are my explanations correct (according to the Standard)?
Does the correct answer change between C++11 and C++14 (and C++1z)?
Are // A and // D both bugs in GCC?
Have these bugs been filed already?

(*) — In fact nothing is technically captured by the second lambda, because it doesn't use j in any evaluated context. That's why lines // A and // C give different answers. But I don't know any nice terminology for the-thing-that-is-being-done-to-j, so I'm just saying "captured".
Comment: GCC's misbehavior has been reported here: https://gcc.gnu.org/bugzilla/show_bug.cgi?id=66672
I'm still interested in more in-depth answers about precisely what detail GCC is getting wrong, what other ramifications that might have, etc.
Answer: I believe that both compilers are wrong for (A) and gcc is wrong for (D).
I believe that gcc is wrong for (A) and (D), while clang is correct for both.

The relevant sections of [expr.lambda.prim] are:

An init-capture behaves as if it declares and explicitly captures a variable of the form "auto init-capture ;"
  whose declarative region is the lambda-expression's compound-statement, except that:
  — if the capture is by copy (see below), the non-static data member declared for the capture and the
  variable are treated as two different ways of referring to the same object, which has the lifetime of the
  non-static data member, and no additional copy and destruction is performed,

and

Every id-expression within the compound-statement of a lambda-expression that is an odr-use (3.2) of an
  entity captured by copy is transformed into an access to the corresponding unnamed data member of the
  closure type.

decltype(j) is not an odr-use of j, therefore no such transformation should be considered. Thus, in the case of [=]{...}, decltype(j) should yield int&. However, in the case of an init-capture, the behavior is as if there was a variable of the form auto j = j;, and the variable j refers to the same unnamed non-static data member with no such transformation necessary. So in the case of [j=j]{...}, decltype(j) should yield the type of that variable - which is int. It is definitely not const int. That is a bug.
The next relevant section:

Every occurrence of decltype((x)) where x is a possibly parenthesized id-expression that names an entity of automatic storage duration is treated as if x were transformed into an access to a corresponding data member of the closure type that would have been declared if x were an odr-use of the denoted entity.
  [ Example:
void f3() {
    float x, &r = x;
    [=] {                       // x and r are not captured (appearance in a decltype operand is not an odr-use)
        decltype(x) y1;         // y1 has type float
        decltype((x)) y2 = y1;  // y2 has type float const& because this lambda
                                // is not mutable and x is an lvalue
        decltype(r) r1 = y1;    // r1 has type float& (transformation not considered)
        decltype((r)) r2 = y2;  // r2 has type float const&
    }
}

—end example ]

The example further illustrates that decltype(j) should be int& in the implicit copy case and also demonstrates that decltype((j)) is treated as if x were the corresponding data member that would have been declared: which is int const& in both cases (as the lambda is not mutable and j is an lvalue). Your (C) and (D) cases exactly mirror the r1, r2 declarations in the example. Which, while the examples are not normative, certainly suggests that gcc is in the wrong for having different behavior.
Comment: But for an *init-capture*, name lookup for `j` doesn't find the `int& j;`; it finds the `j` declared by the *init-capture*. See [expr.prim.lambda]/p11.
Comment: @T.C. Is that because the transformation into the unnamed member access doesn't need to happen?
Comment: If it happens, it refers to the unnamed member; it it doesn't happen, it refers to the thing implicitly declared by the init-capture. Either way, it's an `int`.


Search child element in ET

Question: I'm trying to search an XML file. I need to

check if the 'localteam' name matches my query (e.g 'Team A')
If a match is found check the 'awayteam' name matches my second condition (e.g 'Team B'), the elemt of which is below the 'localteam' within the same element
If 'awayteam' matches my query get the id of the parent (in 'match') and exit the search.

I can get to the localteam element but I'm not sure how to then search for the awayteam and also go 'up' a level to get the id... I've tried using child.iter() and child.find('awayteam'), but neither has worked..
Thus far I have..
for child in root.iter('localteam'):
    gs_name = child.get('name')
    if gs_name == 'Team A':
        print child.tag, child.attrib
        for step_child in child.iter():
            print step_child.tag, step_child.attrib
            gs_name = child.get('name')

XML
<scores sport="sports">
  <category name="NAME" id="1419" file_group="USA">
      <match date="21.07.2013" time="04:00" status="Finished" id="56456456">
         <localteam name="Team A" />
         <random name="yyy" />
         <awayteam name="Team B" />
         <random name="xxx" />
</match>

Answer: Search for match elements instead:
for match in root.iter("match"):
    if (match.find("localteam").get("name") == "Team A" and
        match.find("awayteam").get("name") == "Team B"):
        print match.get("id")
        break

The above will raise AttributeErrors if the find calls don't find anything, so you may want to add some additional checks or error handling; e.g.
for match in root.iter("match"):
    localteam = match.find("localteam")
    awayteam = match.find("awayteam")
    if localteam is not None and awayteam is not None and ...

Search child element in ET


Mistake with Whole/Half step intervals problem

Question: I took a beginner music theory class and there was a quiz on reading music notation.

H W H W H W W W W W
I got 8 of them right. I got the 4th and 10th bar wrong. I wrote it's a whole step (W) for both, but the answer key says it's a half-step (H) for both.
4th measure:
E# and Eb
F and Eb (there is no E#, I assume it's F)
I do 2 half steps (from F to E, and from E to Eb) which is a whole step

10th measure:
Bb and B#
Bb and C (I assume there is no B# and replaced it with C)
I do 2 half steps (from Bb to B, and from B to C) which is a whole step

Feel free to correct my terminology.
("hs" on the pictures stands for "half step")
Comment: This is an HNQ now, and I'd hate for fellow SE prowlers to get catfished into clicking for a complicated enharmonics question. (I edited the title so that it doesn't mislead anyone)
Answer: The confusion arises from the accidentals. Your answer of a whole step would absolutely be correct if those were sharps (♯), but in fact those accidentals are naturals, not sharps (♮). A note with a natural in front of it cancels any previous accidentals, meaning play the note on the white key. So, E♮ to E♭ is a half step (go down one key from E) and B♭ to B♮ is a half step as well (go up one key from B♭).
Comment: It's redundant and likely just to avoid confusion in the context of a beginner exercise.
Comment: Are we sure the 15 is the bar number and not the question number?  It's a contrived test, it's not meant to represent actual music.  Another possibility, as it's a beginner test, is that it's confirming that the (b) for the 2nd E does not apply to the first one (we know it doesn't, but it's a good way to ensure that mistake is not made, in the context of the test (perhaps it would be a better test without it?)).  It's also a good test to ensure the natural sign is not mistaken for a sharp sign, even if it's placed where it's not needed/expected (as demonstrated by this very question).
Comment: I think it's on purpose, to test if the students don't mistake the natural sign with the sharp one, as they are quite similar (too much? well a bit late for change I guess :)
Comment: @ggcg It hardly matters in this context, I suppose. The music does say the first measure is measure 15, so potentially, but with no other context, I'd have to put my money on a (mis)use of courtesy accidentals. Why anyone would mark the high E with a natural but not the low E in the measure before it is beyond me.
Comment: @user45266 It seems pretty clear that there is no intended relationship between one measure and the next.  Each exercise is independent on the previous one.  I believe the professor made good choices here, given the context and the sort of cognition required of the students.
Comment: While I agree, it seems that in measure 4 the natural is not canceling anything.  Do you think that is a courtesy?  Or is there something not shown?
Comment: Since it starts at bar 15, it would be fair to assume that in fact there would be an Eb in the key sig - thus the need to put that natural on the top E. That would then make the answer to bar 18 (q3) W... But there again, it wouldn't need the Bb in the bar before! There may be a point to the question in the question, but it's obscure!
Comment: @freedomn-m it's the bar number (or, at least, it isn't the question number). The previous question was with number 9 on it. I don't think it matters: in the class, we haven't covered it yet.
Answer: You are misreading the staff. Those aren't sharp symbols, those are natural symbols. So E-natural to E-flat and B-flat to B-natural. In measure 4, the natural symbol is redundant because a note is assumed to follow the key signature (C in this case) unless there's a preceding note in the same measure with an accidental. Therefore the first note in this measure is E-natural anyway.
In the 10th measure, the natural symbol is needed because the preceding B is B-flat -- meaning the second note would also be B-flat with nothing indicating otherwise.
Comment: @Tim I wouldn't speak about any key at all in such an exercise but… There is a clef printed on the left side and if there were any key signature, it would have to be printed on each staff after the clef (unlike time signature).
Comment: @Tim Does the mentioned music have bar numbers on each staff? I am pretty sure it does not. However, the OP's example seems to be made in modern notation software like Sibelius or Musescore which would automatically include the key signature and bar numbers on each staff or system, respectively. However, I wouldn't assume the bar 15 meaning anything here, I can even imagine it being the third staff of a "score" (or better speaking a notation software document) where each staff means a different exercise.
Comment: @Melebius yes, it was created in Musescore.
Comment: Starting at 'bar 15', can it be assumed that the key is C? It's hardly a 'good' question.
Comment: @Melebius - point taken. There's a fair bit of music I play that has clef and/or key sig. missing apart from the first line! Take a look at real or fake book transcripts.
Comment: @Melebius - so '15' is a red herring. Most likely. Irrelevant to the question, and inapproriate, at that level - or any, really. Would be better with that removed, anyway. I just dislike questions that are not clear - and at the level this one's asked, I don't think it's the best. Maybe that's what prompted OP to pose it. (apart from natral and sharp sign confusion). Probably not, but worth airing.


Migration of field_collection with migration_d2d

Question: In D7 to D7 migrations, when it comes to field_collections I know " Your field collection migration should be run after the host entity migration. ".
I have done my host entity migration via the migrate_d2d module.
For my field_collection I have written a custom module and added migrate_d2d class name (7f4f1882cNodecook_committee_vote) as a dependency.
Has this logic flowed?
I ask because my field_collection migration does not update the previously migrated cook_committee_vote nodes, rather it makes empty stubs for them!!!
Answer: The answer is: the logic is not flowed, it is correct.
when you write your own custom migration module you can establish dependencies to other migrations that you have done via code or done via UI using migrate_ui or d2d_migrate_ui modules.
here is custom migration code that depends on a class generated by d2d_migrade_ui. this code worked for me:

<code>$this->description = t('casey will migrate this field cllection even if it kills him!!!!!!');
// class of prviously imported node, this class name was generated by d2d_migrate module
// that is why the name is diffrent
$this->dependencies = array('7f4f1882cNodeorg_vote');

$query = $this->getConnection()
// start with the field that embeds the field_collection
->select('field_data_field_org_member_votes', 'nodeField')
->fields('nodeField', array('entity_id', 'field_org_member_votes_value', 'delta'))
->groupBy('nodeField.field_org_member_votes_value')
->orderBy('nodeField.entity_id')
->orderBy('nodeField.delta');

// join it to the fields that make up the field_collection, in my case there were 3 fields
$query->leftJoin('field_data_field_org_votes_member', 'member',
'nodeField.field_org_member_votes_value = member.entity_id');
$query->addField('member', 'field_org_votes_member_nid');

$query->leftJoin('field_data_field_org_votes_vote', 'vote',
'nodeField.field_org_member_votes_value = vote.entity_id');
$query->addField('vote', 'field_org_votes_vote_value');

$query->leftJoin('field_data_field_org_votes_majority', 'majority',
'nodeField.field_org_member_votes_value = majority.entity_id');
$query->addField('majority', 'field_org_votes_majority_value');

$this->source = new MigrateSourceSQL($query);

$this->destination = new MigrateDestinationFieldCollection(
    'field_org_member_votes',
    array('host_entity_type' => 'node')
);

$this->map = new MigrateSQLMap($this->machineName,
    array(
        'field_org_member_votes_value' => array(
            'type' => 'int',
            'not null' => TRUE,
            'description' => 'Unique ID for each commitee vote',
            'alias' => 'nodeField',
    )
  ),
  MigrateDestinationFieldCollection::getKeySchema()
); //map END

$this->addFieldMapping('host_entity_id', 'entity_id') ->sourceMigration('7f4f1882cNodeorg_committee_vote');

$this->addFieldMapping('field_org_votes_member', 'field_org_votes_member') ->sourceMigration('7f4f1882cNodemember');
$this->addFieldMapping('field_org_votes_member:source_type') ->defaultValue('nid');

$this->addFieldMapping('field_org_votes_vote', 'field_org_votes_vote');

$this->addFieldMapping('field_org_votes_majority', 'field_org_votes_majority');

}//construct END

 function prepareRow($row) {
   // this is a good wat to test and make sure
   // A) you have connected to the db
   // B) you are getting proper values from your query
   // drush_print_r($row);
 }//prepareRow END
 function complete($row) {
   // drush_print_r($row);
 }
 public function prependTextNotes($row) {
     return 'Imported notes: ' . $row;
 }//prependTextNotes   END

 }
</code>


Como ter mais de um valor referente a outra tabela?

Question: Bom pessoal, venho com uma duvida que anda me perseguindo a muito tempo.
Vamos ao que tenho:
Tenho a tabela X porem valores da tabela X eu pego na tabela Y. Como armazenar mais de um valor na tabela Y referente a tabela X sendo que a tabela Y pode também referenciar com os mesmos valores para outras tabelas.
Com isso eu tenho um problema que preciso muito de ajuda.
O que penso?
Criar outra tabela para auxiliar estes valores por exemplo:
Tenho a tabela X e a tabela Y. Eu crio a tabela Z onde armazenará tudo o que X precisar na tabela Y assim caso eu tenha uma tabela G que necessite também de um item da tabela Y, armazenarei na tabela Z todos os item que G necessita.
Preciso saber se está correto este pensamento ou se tem outra maneira de realizar isso.
Pessoal, agradeço desde já. Obrigado por me ajudarem.
Comment: Pedro, me desculpe mas a sua pergunta está muito confusa. Muitas referências de X Y G Z. Não teria como postar as tabelas e alguns dados para simplificar a história? Assim que você simplicar eu retiro o meu voto negativo.
Comment: Relaxa, não ligo para seu voto negativo. Isso só desanima o interesse de quem procura ajuda, se vc solicitasse primeiro alteração na pergunta antes de negativa-la. mas tudo bem, já estou acostumado com a mentira mais antiga do país. De que o poder pode ser inocente
Comment: isso não tem nada haver com poder. Apenas queria te mostrar que a sua pergunta está complexa de ser entendida. Isso é uma comunidade, que ao meu ver tem o intuito de aprimorar o conhecimento de todos e nada haver com poder.
Comment: Minha pergunta foi respondida, talvez seu entendimento nao tenha sido suficiente e seu poder pode levar ela a negativa ou positiva. Nem sempre seu ver é o correto.
Answer: Pelo meu entendimento da sua pergunta, você quer puxar os dados de duas tabelas em uma só consulta, é isso? Se for, no blog do Thiago Belem tem um artigo ótimo que foi onde eu aprendi, e aqui tem um pouco mais sobre o assunto.
Exemplo: Você tem duas tabelas no banco de dados com alguns dados inseridos
CREATE TABLE `categorias` (
    `id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY ,
    `nome` VARCHAR( 255 ) NOT NULL
) ENGINE = MYISAM;

INSERT INTO `categorias` VALUES
(1, 'Camisetas'),
(2, 'Canecas');

CREATE TABLE `produtos` (
    `id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY ,
    `categoria_id` INT NOT NULL ,
    `nome` VARCHAR( 255 ) NOT NULL ,
    `preco` DECIMAL( 10,2 ) NOT NULL
) ENGINE = MYISAM;

INSERT INTO `produtos` VALUES
(1, 1, 'Camiseta Social', 15.00),
(2, 1, 'Camiseta Regata', 11.99),
(3, 2, 'Caneca Grande', 12.00);
E quer um retorno mais ou menos assim:

| id | categoria_id | nome            | preco | categoria |
| 2  | 1            | Camiseta Regata | 11.99 | Camisetas |
| 1  | 1            | Camiseta Social | 15.00 | Camisetas |
| 3  | 2            | Caneca Grande   | 12.00 | Canecas   |

Deve montar uma QUERY assim:

SELECT p.*, c.`nome` AS categoria FROM `produtos` AS p
INNER JOIN `categorias` AS c ON p.`categoria_id` = c.`id`
ORDER BY p.`nome` ASC

Onde INNER JOIN irá fazer a junção da tabela categorias na pesquisa da tabela produtos. Que acredito eu, seja a sua dúvida.
(Fonte: Thiago Belem)
Comment: Recomenda-se respostas completas se links ou usá-los somente para complementar a pergunta.
Comment: Já resolvi meu problema. criei outra tabela para salvar a referencia onde o mesmo valor pode ser usado varias vezes. Uma tabela para auxiliar isso resolveu ! hehe .. mas muito obrigado só consegui com essa lógica que vc me passou. agradeço muito!


Finding an element whose Xpath is unique to each login

Question: I am coding a python web automation selenium script.
In the script, I use driver.find_element_by_xpath('xpath') to find elements on Binary.com. This means I would have to preload Binary.com and copy xpaths of the elements I need to find. For most elements the method works but for a few I realised that the Xpath is unique to each login.
For example, if I login in now and try to copy the xpath of a certain element it will be //*[@id="tp1602844250562"] but if the page is reloaded or I try to login on a different window the xpath would have then changed to //*[@id="tp1602844157070"]. Please note they are not the same id numbers. This means I cannot use one xpath on a separate page login
The desired element has an HTML code:

<input type="text" class="time hasTimepicker" tab-index="-1" value="00:00" readonly="" id="tp1602844157070">

Refer to the supplied image for clear html code
Answer: Why don't you use the class instead of the id? Try this xpath:
driver.find_element_by_xpath('//input[@class = "time hasTimepicker"]')

Comment: This is not the best way to filter on class names. Please have a look at this answer https://stackoverflow.com/questions/1604471/how-can-i-find-an-element-by-css-class-with-xpath/1604480#1604480.
Answer: Try changing your xpath expression to
//input[starts-with(@id,"tp")]

or, if it's not always input
//*[starts-with(@id,"tp")]

Answer: You can try below with class instead of id as the id is getting pulled from DB i guess-
//div[@class='date-time']//input[contains(@class,'time')]

Answer: To find the input element with that class use.
driver.find_element_by_css_selector("input.time.hasTimepicker")


Views: Display only first value from content field in a staff directory

Question: I'm creating a staff directory for my library in Views. In one of the display field, Departments, staff often are assigned more than one departmental affiliation when I create their Content Profile. In this tabular view I'm creating, how can I make it so only the first value of the field representing departmental affiliation is displayed? It really clutters things up to display two or more departments in this table. I'd be happy to export the view & post it if that will help solve my problem.
Thanks,
Jason
Answer: I am assuming you are using Drupal 7 and Views 3. If that is true, then you could use the below -
Quoting from the comment here - http://drupal.org/node/1024158#comment-5064416

Under fields, when you add your image field, one of the configuration options is "Multiple Field Settings". Under that make sure you check the box for "Display all values in the same row". The last line under this will ask how many items you want to display. Type "1". You can also specify which number to start with if you like. Hope this helps.
Comment: Great. If the solution worked for you 'as is', you could mark the answer as accepted, so this question does not appear in the unanswered list. Or you could edit the answer to add more steps in it that you might have had to follow. /me loves drupal.stackexchange :-)


In which situation does the log-rank test have low power?

Question: This question is complementary to question 1 asked by @Jesse here. It is about the case when we don't find a significant result when performing the log-rank test and when the proportional hazard assumption does not hold. In his/her answer to Jesse, @Aniko has started to answer my present question as follows: If it does not reject, then you have to worry about the proportionality of hazards and power. I totally understand we should worry, but I'd like to know how we should handle our anxiety then.
The log-rank test is always "valid" even if the  proportional hazard assumption does not hold, in the following sense: under the null hypothesis $H_0$ (equality of hazard rates), the probability to reject achieves (approximately or asymptotically) the nominal significance level, that is, the power is low under $H_0$. But when the proportional hazard assumption holds true, then the behavior of the power under $H_1$ is clear because it should be an increasing function of the proportionality constant $k$.
But when this proportional hazard assumption does not hold, are there some typical "$H_1$ situations" for which it is known that the power is still low ? And for a given dataset, are there some visual methods to check whether we likely are in such a situation ?
Answer: The log-rank test compares the observed and expected (under $H_0$) number of events in the two groups. It will have low power, when the observed number of events matches the expected one even though the survival functions are not the same. A typical scenario for this is when the survival curves cross: one group has more events early on, the other has more events later, and the overall number of events balances out. You might be interested in the following paper by Logan et al, 2008.
Comment: A mention of a potentially useful search term: if it can be the case that there are alternatives that can produce a lower-than-$\alpha$ rejection rate, then the test is said to be *biased*. And indeed, using that or related terms (e.g. *bias log-rank test*) in a search does seem to turn up some potentially relevant references.
Comment: Thank you. This typical scenario is what I have heard elsewhere but I didn't know *why*. Your short description of the log-rank statistic is helpful.


Cursor SQLITE pegando o ultimo valor

Question: Como fazer com que o Cursor do SQLITE, faça com que as váriaveis não parem no ultimo valor ? Fiz um SetAdapter ao qual ele me lista todos os dados da ListView, até ai tudo bem, porém quando eu coloco alguma váriavel que fica dentro do WHILE, ele printa o ultimo valor, e eu preciso que ele me mostre todos os valores no Log.i(); Abaixo o código:
//Classe do select do SQLITE

public class Testesqlite extends Tela{

    static String testenome,testesobrenome,testenascimento;

    public void gambi(){

        Cursor c = bancosqlite.rawQuery("SELECT nome,sobrenome,nascimento FROM tabelateste",null);

        while (c.moveToNext()) {

            testenome = c.getString(c.getColumnIndex("nome")).trim();
             testesobrenome = c.getString(c.getColumnIndex("sobrenome")).trim();
             testenascimento = c.getString(c.getColumnIndex("nascimento")).trim();

        }
    }
}

  //Ação ao clicar em um item do ListView
    listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int posicao, long id) {
            posi = parent.getItemAtPosition(posicao).toString();
                Testesqlite gambb = new Testesqlite();
            gambb.gambi();

                if (posi.equals(testenome)) {

                    Intent teste = new Intent(Testing.this, Tela_teste.class);
                    startActivity(teste);

                }
                 //Aqui ele me mostra corretamente a posição
                 //do item clicado, só que o da váriavel "testenome" que
                 //fica dentro do while fica só no
                 //no ultimo, fica toda hora printando o ultimo
                 //e não outros valores ; /
                Log.i("Clicado", posi + "\t" + testenome);
            }

    });

}

O primeiro nome é o da váriavel "posi" e o segundo é o do "testenome" ao qual me mostra sempre o ultimo valor, não sei por que .
OBS: Ao clicar no item da ListView contendo o nome "Testeaaa" , ele abre outra activity sem problemas, porém outros não faz nada .
Mensagem no logcat

12-08 12:18:24.680  26825-26825/br.com.kappauni.teste I/Clicado﹕ Diego Kappaun Testeaaa
  12-08 12:18:29.960  26825-26825/br.com.kappauni.teste I/Clicado﹕ Diella heckler granella    Testeaaa
  12-08 12:18:38.960  26825-26825/br.com.kappauni.teste I/Clicado﹕ Testeaaa Testeaaa
Comment: O *while* percorre todo o cursor, do primeiro registo até ao último, atribuindo os valores dos campos sempre às mesmas variáveis. Portanto as variáveis terão o valor do último registo. Para poder ajudar necessitamos de saber qual é o propósito do seu código.
Comment: Preciso que quando clique em qualquer um dos nomes, ele recupere o valor do banco do que foi clicado . Quando clico no meu nome e no da minha namorada ele não funciona, só que quando clico em "Testeaaa" ele abre a tela normalmente, preciso apenas fazer com que isso funcione para dar continuidade no projeto. Editei a postagem e coloquei 2 imagens para visualização e desculpe pela má edição.
Answer: Há várias formas de obter os valores da linha clicada de uma listView, uma delas é através da view que é passada em onItemClick:
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int posicao, long id) {

        //Substitua R.id.TextViewNome pelo id da textView que recebe o campo "nome"
        TextView tvNome = (TextView)view.findViewById(R.id.TextViewNome);
        Log.i("Clicado", posi + "\t" + tvNome.getText.toString());
    }
 }

Outra é ler diretamente do banco utilizando o id que é passada em onItemClick:
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int posicao, long id) {

        Cursor c = bancosqlite.rawQuery(
              "SELECT nome,sobrenome,nascimento
               FROM tabelateste
               WHERE id = ?",new String[] {Long.toString(id)});

        //Se o seu adapter for do tipo cursorAdapter a linha anterior pode ser
        //substituida por:
        //Cursor c = (Cursor) parent.getItemAtPosition(position);

        String testeNome = c.getString(c.getColumnIndex("nome")).trim();
        String testeSobrenome = c.getString(c.getColumnIndex("sobrenome")).trim();
        String testeNascimento = c.getString(c.getColumnIndex("nascimento")).trim();

        Log.i("Clicado", posi + "\t" + testeNome);
    }
 }

Comment: Teria como dar um exemplo utilizando listview ?
Comment: ??? O exemplo que dei é utilizando listView.
Comment: Me referia ali no lugar de "TextView tvNome = (TextView)view.findViewById(R.id.TextViewNome);". Obrigado pela resposta, assim que eu chegar em casa irei tentar implementar essa segunda opção e darei uma posição .
Comment: O primeiro método parte do principio que você tem uma *view* sua para os itens da *listView*. Se você está a usar a *view* `android.R.layout.simple_list_item_1` use `(TextView)view.findViewById(android.R.id.text1);` ou então use o segundo método.
Comment: Com a sua resposta deu para abrir um pouco mais a mente e usei comparações pra ver se determinado item era clicado para editar os campos separado . Darei como resolvido . Obrigado .

Cursor SQLITE pegando o ultimo valor