Stored Procedure with update statement not functioning

Question: I have created a very simple stored procedure and verified that the query that needs to be executed is a correct/running query. Yet, once stored in the SP, it does not do anything apart from returning '0':
USE [test]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

ALTER PROCEDURE [dbo].[GenerateVolume]

AS
BEGIN

    SET NOCOUNT ON;

    UPDATE test.dbo.[c500 CP_Simulation]
set GeneratedVolume = AvgFillRatePerDayPerCP +[dbo].[fn_InvsNorm](RAND(convert(varbinary, newid()))) * StDevFillRatePerDayPerCP
where test.dbo.[c500 CP_Simulation].OrgVPnr = test.dbo.[c500 CP_Simulation].OrgVPnr

END

No errors are given... Please give me a tip :)
Comment: Have you looked at the c500 CP_Simulation table - the stored proc should return 0 if it worked - what did you expect the proc to return?
Answer: When you use the
SET NOCOUNT ON

It will suppress the "xx rows affected" message.
If your query works fine, your rows are getting updated.
Since you have told sql server not to count how many rows were updated, you will not be told how many rows got updated.
Hope that clears some doubt.


Erro ao tentar criar uma fatura pelo Odoo 14 utilizando um modulo de terceiros

Question: Olá, eu instalei um módulo chamado "Beauty Spa Management" da cybrosys na minha instância do Odoo 14 e ao tentar criar uma fatura de um serviço o sistema gera erro (ele utiliza o módulo invoice do proprio Odoo),
Segue a mensagem de erro:
<code>Erro:
Odoo Server Error

Traceback (most recent call last):
  File "/usr/lib/python3/dist-packages/odoo/addons/base/models/ir_http.py", line 237, in _dispatch
    result = request.dispatch()
  File "/usr/lib/python3/dist-packages/odoo/http.py", line 682, in dispatch
    result = self._call_function(**self.params)
  File "/usr/lib/python3/dist-packages/odoo/http.py", line 358, in _call_function
    return checked_call(self.db, *args, **kwargs)
  File "/usr/lib/python3/dist-packages/odoo/service/model.py", line 94, in wrapper
    return f(dbname, *args, **kwargs)
  File "/usr/lib/python3/dist-packages/odoo/http.py", line 346, in checked_call
    result = self.endpoint(*a, **kw)
  File "/usr/lib/python3/dist-packages/odoo/http.py", line 911, in __call__
    return self.method(*args, **kw)
  File "/usr/lib/python3/dist-packages/odoo/http.py", line 530, in response_wrap
    response = f(*args, **kw)
  File "/usr/lib/python3/dist-packages/odoo/addons/web/controllers/main.py", line 1359, in call_kw
    return self._call_kw(model, method, args, kwargs)
  File "/usr/lib/python3/dist-packages/odoo/addons/web/controllers/main.py", line 1351, in _call_kw
    return call_kw(request.env[model], method, args, kwargs)
  File "/usr/lib/python3/dist-packages/odoo/api.py", line 396, in call_kw
    result = _call_kw_multi(method, model, args, kwargs)
  File "/usr/lib/python3/dist-packages/odoo/api.py", line 383, in _call_kw_multi
    result = method(recs, *args, **kwargs)
  File "/mnt/extra-addons/salon_management/models/salon_management.py", line 252, in write
    self.salon_invoice_create()
  File "/mnt/extra-addons/salon_management/models/salon_management.py", line 335, in salon_invoice_create
    inv = self.env['account.move'].create(invoice_line)
  File "<decorator-gen-160>", line 2, in create
  File "/usr/lib/python3/dist-packages/odoo/api.py", line 344, in _model_create_multi
    return create(self, [arg])
  File "/usr/lib/python3/dist-packages/odoo/addons/account/models/account_move.py", line 1789, in create
    vals_list = self._move_autocomplete_invoice_lines_create(vals_list)
  File "/usr/lib/python3/dist-packages/odoo/addons/account/models/account_move.py", line 1748, in _move_autocomplete_invoice_lines_create
    move = self_ctx.new(new_vals)
  File "/usr/lib/python3/dist-packages/odoo/models.py", line 5480, in new
    record._update_cache(values, validate=False)
  File "/usr/lib/python3/dist-packages/odoo/models.py", line 5122, in _update_cache
    raise ValueError("Invalid field %r on model %r" % (e.args[0], self._name))
Exception

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "/usr/lib/python3/dist-packages/odoo/http.py", line 638, in _handle_exception
    return super(JsonRequest, self)._handle_exception(exception)
  File "/usr/lib/python3/dist-packages/odoo/http.py", line 314, in _handle_exception
    raise exception.with_traceback(None) from new_cause
ValueError: Invalid field 'l10n_in_gst_treatment' on model 'account.move'
</code>
Alguem tem alguma ideia do que possa ser? tentei estudar o codigo fonte do módulo mas nao obtive sucesso em encontrar o erro, segue a função que cria o recibo no codigo fonte do modulo supracitado:
<code>    def salon_invoice_create(self):
        if self.partner_id:
            supplier = self.partner_id
        else:
            supplier = self.partner_id.search([("name", "=", "Salon Default Customer")])
        lines = []
        product_id = self.env['product.product'].search([("name", "=", "Salon Service")])
        for records in self.order_line:
            if product_id.property_account_income_id.id:
                income_account = product_id.property_account_income_id.id
            elif product_id.categ_id.property_account_income_categ_id.id:
                income_account = product_id.categ_id.property_account_income_categ_id.id
            else:
                raise UserError(_('Please define income account for this product: "%s" (id:%d).') % (product_id.name,
                                                                                product_id.id))

            value = (0, 0, {
                        'name': records.service_id.name,
                        'account_id': income_account,
                        'price_unit': records.price,
                        'quantity': 1,
                        'product_id': product_id.id,
                    })
            lines.append(value)

        invoice_line = {
            'move_type': 'out_invoice',
            'partner_id': supplier.id,
            'l10n_in_gst_treatment': 'consumer',
            'invoice_user_id': self.env.user.id,
            'invoice_origin': self.name,
            'invoice_line_ids': lines,
        }
        inv = self.env['account.move'].create(invoice_line)

        imd = self.env['ir.model.data']

        action = imd.xmlid_to_object('account.action_move_out_invoice_type')
        result = {
            'name': action.name,
            'type': 'ir.actions.act_window',
            'views': [[False, 'form']],
            'target': 'current',
            'res_id':inv.id,
            'res_model': 'account.move',
        }

        self.inv_stage_identifier = True
        self.stage_id = 3
        invoiced_records = self.env['salon.order'].search([('stage_id', 'in', [3, 4]),
                                                           ('chair_id', '=', self.chair_id.id)])
        total = 0
        for rows in invoiced_records:
            invoiced_date = str(rows.date)
            invoiced_date = invoiced_date[0:10]
            if invoiced_date == str(date.today()):
                total = total + rows.price_subtotal
        self.chair_id.collection_today = total
        self.chair_id.number_of_orders = len(self.env['salon.order'].search([("chair_id", "=", self.chair_id.id),
                                                                             ("stage_id", "in", [2, 3])]))

        return result
</code>
Answer: ValueError: Invalid field 'l10n_in_gst_treatment' on model 'account.move'
Na última linha está esse erro, o odoo encontrou um campo invalido no modelo account.move. tem que verificar pq o seu odoo não reconhece o campo l10n_in_gst_treatment. Talvez está faltando algum modulo, pelo nome é algo da localização indiana. l10n_in representa a localização indiana. Pelo que pesquisei GST é um imposto idiano, certamente seu odoo não tem isso implementado. Pesquisando mais um pouco, vi que a empresa que criou o modulo "Beauty Spa Management" é indiana, tudo indica que o modulo não foi testado fora da localização indiana, por isso o erro.
Tente remover as referencias ao campo 'l10n_in_gst_treatment' no código fonte do modulo citado. Ou instalar a localização indiana, mas acho que não deve ser de seu interesse.
Comment: Eu ja encontrei a sulução para o caso, de fato apenas remover as referencias do campo 'l10n_in_gst_treatment' resolveram o erro sem causar nenhuma falha no flow do programa, obrigado pelo apoio!


Finding the coordinates of points given the vertical length of a line and the angles between them

Question: The figure below describes a robot moving in a vertical plane $(x, y)$ with two degrees of freedom: one vertical translation of length $q_1$ and one rotation of angle $q_2$ measured with respect to the horizontal line $x$.

How can we obtain the coordinates $(x_1, y_1)$ and $(x_2, y_2)$ of the points $P_1$ and $P_2$ as functions of $q = (q_1, q_2)$, considering that the point $P_0$ is fixed at the coordinates $(0,0)$ and that the length $P_1 P_2$ is 1 meter?
Answer: Let's call $t$ the angle from the $x$-axis counterclockwise to the arrow from $P_0$ to $P_1$. It's 90 degrees, or $\pi/2$, or whatever you want to call it. But that makes the point $P_1$ be
\begin{align}
P_1
&= P_0 + q_1 (\cos t, \sin t) \\
&= (0,0) + q_1 (\cos t, \sin t) \\
&= (0 + q_1 \cos t,0 + q_1 \sin t).
\end{align}
Now you can look up the values of sine and cosine to fill in and get the actual answer.
And you can use the same approach to find the coordinates of $P_2$, starting from $P_1$>
Comment: Thank you for the time!


Jquery Slider fade automatically.

Question: I'm working with this great example of a jQuery slider: http://papermashup.com/simple-jquery-gallery/
here is the Jquery:
$(function() {
$(".image").click(function() {
var image = $(this).attr("rel");
$('#image').hide();
$('#image').fadeIn('slow');
$('#image').html('');
   return false;
   });
});

and here is the HTML

What I would like to know is, How can I get the large images to automatically be fading through the rest of them in a loop. And When I click one for it to start at that point. I plan to have around 20-ish images.
Much appreciated
Answer: There is something called setInterval(param1,param2) method in JavaScript.
param1: Function that invokes the change of image.
param2: Time interval.
I dint bother to modify your example but I made my own example, out of which you can map the function in your example. Please check see this fiddle.
Disclaimer: The images i used are only for demonstration purposes. I dont own any of those images.

Jquery Slider fade automatically.


UIAlertView On Button Click

Question: Yes, I've already Googled this question and I've used the exact code, but that's still not working.
Here is my current Objective-C code:
- (IBAction)btnTemp:(id)sender
{
    if (_deepSwitch.on == TRUE)
    {
        [self TempCleaner];
        _progress.progress += 1;
    }
    UIAlertView *cleaned = [[UIAlertView alloc] initWithTitle:@"Done!" message:@"Your device is now clean. Restarting SpringBoard." delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil, nil];

    [cleaned show];
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (buttonIndex == [alertView cancelButtonIndex]) {
        NSLog(@"clicked");
    }
}

Why isn't this working? I've tried buttonIndex 0, and cancel button!
Answer: Set the alert view's delegate to self
UIAlertView *cleaned = [[UIAlertView alloc] initWithTitle:@"Done!" message:@"Your device is now clean. Restarting SpringBoard." delegate:self cancelButtonTitle:@"Ok" otherButtonTitles:nil, nil];

Also, make sure that the class from which you are presenting the alert view declares the UIAlertViewDelegate protocol
//YourClass.h
@interface YourClass : SuperClass <UIAlertViewDelegate>

Comment: @user3818701 welcome to SO, If someone answered your question and if that answer really worked for you, there is no obligation but should accept that answer by clicking green bordered checkmark under the up/down buttons. Every accepted answers gives +2 rep to you. I am writing this because as I can see you have some questions and you got your answers but you did not accept any of them. I am just giving information, feel free to accept answers or not. thank you.
Comment: @user3818701 No problem, it's a common mistake that I make sometimes.
Comment: Sorry, I didn't know I could do that. I just upped this :)

UIAlertView On Button Click


Função para realizar divisão de duas colunas

Question: Estou iniciando no R Studio e não sei como faço para obter dados percapita (que no caso seria a divisão da coluna valor pela coluna população)
Comment: Por favor, edite a pergunta para limitá-la a um problema específico com detalhes suficientes para identificar uma resposta adequada.
Answer: #Você poderia usar a função mutate para isso. Em um exemplo hipotético vc poderia fazer:
library(tidyverse)

pop<-c(100,200,300)
PIB<-c(20000,30000,35000)
muni<-c('A','B','C')

dados<-data.frame(pop,PIB,muni)

pop
PIB muni
100 20000   A
200 30000   B
300 35000   C
Calculando o valor per capta usando a função mutate aplicada ao data.frame de exemplo
dados%>%
mutate(percapta=(PIB/pop))

dados

pop

PIB

muni

percapta

100 20000   A   200.0000
200 30000   B   150.0000
300 35000   C   116.6667


Model diagnostic in GLM

Question: If there is no duplicated observations in each level of covariates, then we cannot use Pearson or deviance residuals. An alternative is to use DARMA residuals in R (where we generate the Ys using the different covariates). Could someone intuitively explain why this procedure work?
Comment: Have a look at https://stats.stackexchange.com/questions/570727/simulated-dharma-residuals-how-are-they-created/570826#570826
Answer: Assuming the model is correct, for each value of the covariate, you simulate the response y for a certain number of times (e.g. 10 times). Then you constructive the cumulative distribution of y for this value of covariate. Then you evaluate the cumulative distribution evaluated at the observed y. For example, if all the y you generate are smaller than the observed y, then you will see an residual of 0 for the cumulative distribution. If half the y you generate are smaller than the observed y, then you will see an residual of 0.5 for the cumulative distribution.  So given a correct model, the residuals should follow a uniform distribution. These residuals can then be reflected in a QQ plot to detect a potential deviation from the uniform distribution.

Model diagnostic in GLM


How to edit the People (users admin view) to include filter by user name?

Question: I want my admins to be able to search through the admin users view by the user name. I have a site with a lot of users and periodically the admins want to be able to check on various user fields. Is there a way to do this?
Answer: You can take a look at the Administration Views Module:

Replaces administrative overview/listing pages with actual views for
  superior usability.
Features

Filter all administrative views via AJAX.
Perform any kind of bulk/mass operations on items in administrative views.
Filter content by title, node type, author, published status, and/or vocabulary.
Filter comments by title, author, node title, or published status.
Filter users by name, ban/blocked status, or user roles.

*Note: If you are upgrading from an older version of Administration views and the default views have been overridden (saved in the
  database) you could encounter issues or not see any new changes unless
  you revert these views, so the default in-code views are used. This
  can be done in the views UI listing or using drush (drush cter
  views_view --module=admin_views)

By default it has a specific users view, but since it is a view, you can modify it.
Comment: Note that in Drupal 8+ this functionality is in Core. Also, see https://www.drupal.org/project/drupal/issues/1823450
Answer: You cannot easily alter admin/people page but you can add a new tab to it using Views.
Create a custom View page that uses users as base table and expose user:name as a filter. Set its menu to a tab under admin/people and give access based on role or "administer users" permission.


Selecionando Row em um DataGrid a partir de uma pesquisa. C#

Question: Boa tarde Galera,
Alguém tem um código onde eu consiga Selecionar uma Row em um DataGrid, a partir de uma pesquisa ?
Onde eu realciono meu Button_Click a um TextBox com um determinado valor, fazendo a busca no DataGridView, assim selecionando a Row referente àquele valor do TextBox.
Comment: Acho que a resposta do @zekk ja resolveu seu problema ne?
Comment: Pelo que entendi, você tem um botão, e um textbox, onde você entra com algum valor, e ao clicar no botão vc quer que ele percorra o datagrid e se encontrar a linha, por exemplo pinte ela de vermelho e isso? seja mais especifico na sua pergunta, se possivel adicione prints, e parte do codigo
Comment: @ThomasErichPimentel exatamente isso.
Um comando que busque no DataGrid uma linha com o valor que eu determinei, e quando o comando encontrar, selecione esta linda.
Comment: Rodando perfeitamente !
Answer: Você pode percorrer os rows do DataGrid e comparar os valores com o texto do TextBox.
string pesquisar = textBox1.Text.ToLower();

dataGridView1.ClearSelection();

foreach (DataGridViewRow row in dataGridView1.Rows)
{
    if (row.Cells["NomeDaColuna"].Value != null)
    {
        if (row.Cells["NomeDaColuna"].Value.ToString().ToLower().Equals(pesquisar))
        {
            row.Selected = true;
            break;
        }
    }
}

Comment: @MaurícioSanches Você pode usar o método [`ToLower`](http://www.dotnetperls.com/tolower) em ambas as *strings* e compará-las, sobre o segundo problema, antes de fazer a pesquisa, use: `DataGridView1.ClearSelection();`.
Comment: Cara, este comando está funcionando parcialmente, quando a execução chega no 2º `if` para valorar a int rowIndex, ele não entra na chave.
Comment: @MaurícioSanches Você colocou o nome da coluna correta? outra coisa, o texto do `textbox` tem que ser **exato**.
Comment: Ok! está correto agora, o problema era eu que não estava considerando Maiusculos e Minusculos. está rodando certo agora.


ESXi 6.7 monitor hardware storage not showing usual results

Question: Yesterday 2 of our ESXi hosts were updated from 6.5 to 6.7 (build 8169922), though after doing this we noticed a few quirks when trying to access the storage hardware monitoring.
In the web UI typically we'd only see elements listed for the Avago/LSI hardware RAID here, with a clear indicator of its overall health, each logical volume's health, and each physical disk's health. Now though all sorts of hardware is showing up that isn't even storage related. (Such as the GPU, Ethernet controllers, and Thunderbolt controllers.)

I've updated the LSI SIMS provider to version 7.6 (30/May/2018), along with MegaCLI utility version 8-07-07, and the storcli utility version 007.0606.0000.0000 (20/Mar/2018). The host has been rebooted after installing each VIB. Looks like the CIM service just doesn't want to know though.
The servers work very fine indeed, VMs are operating as normal. They just lack RAID monitoring and management now, so if an issue happens we just get a buzzer and LED blink, and have to reboot to the LSI WebBIOS to see what it's for to resolve it.
I saw from the VMWare hardware compatibility that our LSI RAID controller models are supported with an official driver so I don't think there is any compatibility issue.
The MegaCLI command is also useless likely because of the same CIM issue. ./MegaCli -adpCount shows Controller Count: 0, which also means that the MegaRAID Storage Manager utility no longer detects ESXi hosts for management too.
--
Finally with the storcli only some parts of it work. This is probably a separate issue though. (Bug in the tool?) It seems if you are specifying command arguments that contain a forward slash '/' it is ignored.
For example, "storcli show" works:
[root@nexus:/opt/lsi/storcli] ./storcli show
CLI Version = 007.0606.0000.0000 Mar 20, 2018
Operating system = VMkernel 6.7.0
Status Code = 0
Status = Success
Description = None

Number of Controllers = 1
Host Name = nexus.***
Operating System  = VMkernel 6.7.0
StoreLib IT Version = 07.0603.0200.0000
StoreLib IR3 Version = 15.53-0

System Overview :
===============

------------------------------------------------------------------------------------
Ctl Model                 Ports PDs DGs DNOpt VDs VNOpt BBU  sPR DS  EHS ASOs Hlth
------------------------------------------------------------------------------------
  0 LSIMegaRAIDSAS9271-8i     8   4   1     1   1     1 Msng On  1&2 Y      4 NdAtn
------------------------------------------------------------------------------------

Ctl=Controller Index|DGs=Drive groups|VDs=Virtual drives|Fld=Failed
PDs=Physical drives|DNOpt=DG NotOptimal|VNOpt=VD NotOptimal|Opt=Optimal
Msng=Missing|Dgd=Degraded|NdAtn=Need Attention|Unkwn=Unknown
sPR=Scheduled Patrol Read|DS=DimmerSwitch|EHS=Emergency Hot Spare
Y=Yes|N=No|ASOs=Advanced Software Options|BBU=Battery backup unit
Hlth=Health|Safe=Safe-mode boot

However, using another command such as "storcli /cx show alarm" does not:
[root@nexus:/opt/lsi/storcli] ./storcli /cx show alarm

syntax error, unexpected $end

     Storage Command Line Tool  Ver 007.0606.0000.0000 Mar 20, 2018

     (c)Copyright 2018, AVAGO Technologies, All Rights Reserved.

help - lists all the commands with their usage. E.g. storcli help
<command> help - gives details about a particular command. E.g. storcli add help

List of commands:

That syntax error, unexpected $end suggests something in the command parser is not right. (I've tried from both the DCUI and SSH.) Weirdly storcli cx show help does work, only showing controller specific commands, but storcli cx show all does not.
(The fact that storcli is able to see the controller at all and query it tells me the driver is fine and compatible.)
Comment: Go to the 6.7 HCL, check EVERY SINGLE component is supported by 6.7, they stopped supporting a LOT of kit between 6.5 and 6.7, like a lot.
Comment: Silly me. "storcli" appears to work fine, I didn't realise "/cx" should actually be "/c0" to mean "use controller at index 0". I'm not bothered if MegaCLI doesn't work any more as storcli is the later product. Bit weird about the web UI and MSM utility though.
Comment: I did check the CPU and RAID in advance, they were listed on 6.5, 6.5U1, 6.5U2, and 6.7. The only component I know of that isn't supported is the Atheros Killer NIC on the motherboard.
Comment: what sort of server systemboard are you using that's got an Atheros Killer NIC on it?!?!
Comment: Heh, the server for our office actually has a workstation type motherboard. (It's a Gigabyte GA-X170-EXTREME ECC.) It has a Xeon E3-1270 v5 CPU though with ECC memory, and an LSI MegaRAID 9260-8i. --- The other server at our DC doesn't have a Killer NIC though. ;) That has a Xeon E3-1245 v2 CPU with ECC memory, and an LSI MegaRAID 9260-4i. --- Both use Intel NICs, which definitely work, as I can talk to the servers fine.
Answer: You should use
./storcli /c0 show

(0 = number of the controler, you see it in your first command ./storcli show -> Ctl 0)
If you want to see every controller you can use :
./storcli /call show

If you want to see every virtual drive you can use :
./storcli /call/eall show

If you want to see every physical drive you can use :
./storcli /call/eall/sall show

Or you can use :
./storcli /call show all

for all the information of all controllers.
In your case you have 1 controller, so you can use
./storcli /c0 show all

For alarm status/control you can use :
./storcli /c0 show alarm   (show alarm status)

./storcli /c0 set alarm=silence   (mute buzer alarm)

./storcli /c0 set alarm=off   (shutdown alarm)

Comment: Thanks, I got this working already. (Comment 21 Jun at 14:55) This won't fix the ESXi UI though.
Comment: Yes same issue here with a 9260-8i on ESXi 6.7.
I use a script for check the raid status with nagios but you can use directly on a linux machine with an ssh acces to the ESXi.
Answer: Based on the list https://www.vmware.com/resources/compatibility/pdf/vi_cim_guide.pdf last version where LSIProvider mib is support was 6.5u2
Answer: I was unable to get storcli or MegaCLI to display my H200 (crossflashed to 9211-8i in IR mode) adapter information:
[root@hostname:~] esxcli storage core adapter list | grep mpt
vmhba2    mpt2sas    link-n/a    sas.xx     (0000:02:00.0) LSI Logic / Symbios Logic Dell 6Gbps SAS HBA Adapter

[root@hostname:~]  /opt/lsi/storcli/storcli /c0 show
CLI Version = 007.0606.0000.0000 Mar 20, 2018
Operating system = VMkernel 6.7.0
Controller = 0
Status = Failure
Description = Controller 0 not found

[root@hostname:/opt/lsi/MegaCLI] ./MegaCli -adpCount

Controller Count: 0.

I found sas2ircu P20 on the Broadcom website which seems to work (as of 6.7.0 Update 1 Build 11675023):
Download location: https://docs.broadcom.com/docs-and-downloads/host-bus-adapters/host-bus-adapters-common-files/sas_sata_6g_p20/SAS2IRCU_P20.zip
Extract the vmware-esx-sas2ircu.vib from this file and upload it to your ESXi host. Install it using the following command (change path to match your datastore):
[root@hostname:~] esxcli software vib install -v /vmfs/volumes/Datastore/vmware-esx-sas2ircu.vib --no-sig-check

Installation Result
   Message: Operation finished successfully.
   Reboot Required: false
   VIBs Installed: LSI_bootbank_vmware-esx-sas2ircu_20.00.00.00-03
   VIBs Removed:
   VIBs Skipped:

I was then able to use sas2ircu to display my adapter information:
[root@hostname:~] /opt/lsi/bin/sas2ircu 0 display
LSI Corporation SAS2 IR Configuration Utility.
Version 20.00.00.00 (2014.09.18)
Copyright (c) 2008-2014 LSI Corporation. All rights reserved.

Read configuration has been initiated for controller 0
------------------------------------------------------------------------
Controller information
------------------------------------------------------------------------
  Controller type                         : SAS2008
  BIOS version                            : 7.39.02.00
  Firmware version                        : 20.00.07.00
  Channel description                     : 1 Serial Attached SCSI
  Initiator ID                            : 0
  Maximum physical devices                : 255
  Concurrent commands supported           : 1720
  Slot                                    : 4
  Segment                                 : 0
  Bus                                     : 2
  Device                                  : 0
  Function                                : 0
  RAID Support                            : Yes
------------------------------------------------------------------------
IR Volume information
------------------------------------------------------------------------
IR volume 1
  Volume ID                               : 286
  Status of volume                        : Okay (OKY)
  Volume wwid                             :
  RAID level                              : RAID1
  Size (in MB)                            : 113487
  Physical hard disks                     :
  PHY[0] Enclosure#/Slot#                 : 1:4
  PHY[1] Enclosure#/Slot#                 : 1:5
------------------------------------------------------------------------
Physical device information
------------------------------------------------------------------------
Initiator at ID #0

Device is a Hard disk
  Enclosure #                             : 1
  Slot #                                  : 4
  SAS Address                             :
  State                                   : Optimal (OPT)
  Size (in MB)/(in sectors)               : 114473/234441647
  Manufacturer                            : ATA
  Model Number                            : KINGSTON SA400S3
  Firmware Revision                       : B1D1
  Serial No                               :
  GUID                                    :
  Protocol                                : SATA
  Drive Type                              : SATA_SSD

Device is a Hard disk
  Enclosure #                             : 1
  Slot #                                  : 5
  SAS Address                             :
  State                                   : Optimal (OPT)
  Size (in MB)/(in sectors)               : 114473/234441647
  Manufacturer                            : ATA
  Model Number                            : KINGSTON SA400S3
  Firmware Revision                       : B1D1
  Serial No                               :
  GUID                                    :
  Protocol                                : SATA
  Drive Type                              : SATA_SSD
------------------------------------------------------------------------
Enclosure information
------------------------------------------------------------------------
  Enclosure#                              : 1
  Logical ID                              :
  Numslots                                : 8
  StartSlot                               : 0
------------------------------------------------------------------------
SAS2IRCU: Command DISPLAY Completed Successfully.
SAS2IRCU: Utility Completed Successfully.

I'll grab this information via SSH and monitor my array this way.


apache2 + mod_fastcgi + suexec + php5.2 = unstable on high load

Question: I am hosting several (~30) different sites on one server with apache2+fastcgi+suexec+php5. Sites have different loads and different execution times of their scripts (some of them process request for 5-7 seconds, some <1sek).
Sometimes when single site receives very high load (all php instances of this site are created and used) - whole apache server hangs. Apache (worker mpm) creates new processes up to the upper limit. It looks like it is starting to queue ALL new request for EVERY site, not only the one that has high load and quickly achieves process limits...
restart of apache solves the problem...
config:
FastCgiConfig -singleThreshold 1 -multiThreshold 10 -listen-queue-depth 30 -maxProcesses 80 -maxClassProcesses 12 -idle-timeout 30 -pass-header HTTP_AUTHORIZATION -pass-header If-Modified-Since -pass-header If-None-Match
(earlier have default -listen-queue-depth = 100, but it didn't change anything...)
Any suggestions?
Another question - how is implemented this listen queue? is it one queue for whole apache, or unique queue for every defined php apllication (suexec site)?
I would like to achieve something like this: when one site receives high load and its queue is full - server bounces next request, but only for this one site.. Other sites should work  properly...
Comment: it also produces errors for high loaded services:
FastCGI: comm with (dynamic) server "/php.fcgi" aborted: (first read) idle timeout (30 sec)
Comment: I'm interested whether you resolved this issue, since I face similar problems on a webserver.
Answer: Apache 2.4 offers a new fastcgi proxy module (mod_proxy_fcgi) that can proxy requests to php-fpm.
Using mod_proxy as an intermediary means you have access to all the mod_proxy options, including queueing and depletion parameters separate from the main server.
I would advise you to set it up on a test server with the apache 2.4 event MPM and php-fpm; you can tune each php pool for different applications, too.
Answer: Have you tried mod_fcgid instead? It's much better in handling high load at your server.
Answer: If fastcgi is spinning up the php scripts as a user process, then the /etc/security/limits.conf definitions (specifically nproc) should be enforced by the OS.
i.e: apache will try to spin up the process as that user, and the the OS will kill the process because it exceeded the process limit.
this is sort of a kludge, though; if the machine is otherwise idle, you'll still be killing connections.
why don't you just fork your larger client off to a dedicated machine? or spin up a secondary apache, listening on a high port, with a set footprint/runtime allowance?  you could use mod_proxy to pass it requests transparently.
that said, i'm not too familiar with fastcgi, so there might be some quota system available already; quick read through the docs didn't net anything, though.
Answer: You can view a series of web tutorials here:
http://blog.stuartherbert.com/php/category/the-web-platform/
I personally find those very insightful! With this tutorial possibly being just as helpful:
http://blog.stuartherbert.com/php/2008/10/07/can-you-secure-a-shared-server-with-php-fastcgi/
I'd recommend honestly moving the high traffic site to its own machine if it is using that much resources.


Erro ao executar makemigrations no meu projeto django

Question: Estou tentando executar o makemigrations no meu projeto django
, mas ele esta retornando erro dizendo que o argumento default
não é esperado ou algo do tipo, segue trecho do erro:
TypeError: __init__() got an unexpected keyword argument 'dafault'

Não sei o que está acontecendo, pois em outros projetos já executei classes com atributos praticamente idênticos sem que erro algum acontecesse.
Segue o trecho do código:
class Music(models.Model):
    id_music = models.UUIDField(
        primary_key=True,
        dafault=uuid.uuid4(),
        editable=True,
        unique=True
    )

PS.: Estou usando o Python na versão 3.8.6 e o django na versão 3.1.6
Answer: class Music(models.Model):
    id_music = models.UUIDField(
        primary_key=True,
        default=uuid.uuid4,
        editable=True,
        unique=True
    )

Não precisa chamar a função com ( )
Comment: Continua dando o mesmo erro.
Comment: Vc tem certeza que escreveu 'default', certo?


Pine Script, how to make a moving average exponential deviated in the RSI Indicator?

Question: This is the code I have made.
In this image you can see the 14 moving average exponential,
I want 2 more 14 moving average exponential but deviated.
the result would be like this result image.
<code>//@version=4
study(title="RSI deviated EMA")

//input
len = input(14, minval=1, title="Length")
src = input(close, "Source", type = input.source)
up = rma(max(change(src), 0), len)
down = rma(-min(change(src), 0), len)
rsi = down == 0 ? 100 : up == 0 ? 0 : 100 - (100 / (1 + up / down))
plot(rsi, "RSI", color=#999999)

//RSIEMA
lenema = input(14, minval=1, title="RSI EMA Length")
out = ema(rsi, lenema)
col=out >= out[1]
plot(out, title="RSI EMA", color=#999999, linewidth=2)

//deviation
</code>
How to make a moving average exponential deviated in the RSI Indicator?
Answer: If you mean standard deviation bands, like having a bollinger band of RSI
<code>mult = input(2.000, title = "stdev mult")
sd = stdev(rsi, len)
sdup = out + sd * mult
sddn = out - sd * mult

plot(sdup)
plot(sddn)
</code>


How add circular shadow in the bottom of navigation

Question: Good evening, guys,
Could you please give me an advice,
I think I was at a deadlock!
There is the main navigation menu on the top of website.
Problem is that, I don't know how we can input shadow over the our navigation, directly in the bottom of navigation and it won't stop work of our left and right borders.
So, if I will put our shadow in another block (in my case "circle_shadow"), it won't cover up our borders, it will create new space after navigation.
I am interested, how can we put this kind of shadow on our menu, over the navigation borders?
Please, take a look:

Here we have a logo_1

Here is navigation

Here is logo_2

CSS:
.border {
    border-right: 1px solid black;
    border-left: 1px solid black;
}

.circle_shadow {
    position: relative;
    overflow: hidden;
    padding:5px;
}

.box_center_shadow_m:before {
    content: "";
    height: 100px;
    position: absolute;
    right: 10px;
    top: -99px;
    left: 10px;
    border-radius: 50%/60px;
    box-shadow: 0 0 30px rgba(0,0,0,0.5);
}

Here I attached some images:
Comment: Not sure what you are asking for. Do you mean drop shadows?
Answer: It is a little hard to follow what you are asking, there might be an english barrier here. But if you are looking for a rounded drop shadow, here are some samples:
.roundedCorner {
    width:350px;
    height:200px;
    border: solid 1px #555;
    background-color: #eed;
    box-shadow: 10px -10px 5px rgba(0,0,0,0.6);
    -moz-box-shadow: 10px -10px 5px rgba(0,0,0,0.6);
    -webkit-box-shadow: 10px -10px 5px rgba(0,0,0,0.6);
    -o-box-shadow: 10px -10px 5px rgba(0,0,0,0.6);
    border-radius:25px;
}

.circle {
    width:150px;height:150px;
    border: solid 1px #555;
    background-color: #eed;
    box-shadow: 10px -10px rgba(0,0,0,0.6);
    -moz-box-shadow: 10px -10px rgba(0,0,0,0.6);
    -webkit-box-shadow: 10px -10px rgba(0,0,0,0.6);
    -o-box-shadow: 10px -10px rgba(0,0,0,0.6);
    border-radius:100px;
}

More shadow options can be seen at a CoreLangs
Answer: Sorry for not clear question.
Yes, I know how to use rounded drop shadow.
Problem is not about how create rounded drop shadow.
Problem is how can we put this rounded drop shadow into the bottom of navigation block. This is the major question.
Take a look on this code:
I)

                NEWS

                    EVENTS

                    DOWNLOADS

                    TOUR

CSS:
 .rounded_drop_shadow {
    position: relative;
    background: none repeat scroll 0% 0% transparent;
    overflow:hidden;
    padding:3px;
}

    .rounded_drop_shadow:before {
    content: "";
    height: 100px;
    position: absolute;
    right: 10px;
    top: -100px;
    left: 10px;
    border-radius: 50%/60px;
    box-shadow: 0 0 60px rgba(0,0,0,0.3);
}

Now, this image shows, that shadow was added to the navigation block, but in extra space after.
https://i.stack.imgur.com/Z1SZV.png
But, my target is not extend block of navigation, just we have to put it above of navigation menu on the bottom. As if on top of it!
It should be like here:
http://i.imgur.com/ed3zWJL.png
Now, I found a solution, but I wonder if you take a look and will be able to give advice about this option:
Maybe, we should put block div with class="rounded_drop_shadow" inside another block div with class="shadow" (Both of them will still inside common_block) and play with position:absolute?

                NEWS

                    EVENTS

                    DOWNLOADS

                    TOUR

CSS
.box_center_shadow {
   position: absolute;
   top: 64px;
   left: 0px;
   right: 0px;
}

I wonder if somebody can tell me, if it is right way....or offer another options.
Thanks.


Creating a structure from a C++ function prototype

Question: Suppose one has a C++ function foo with the following prototype:
bool foo (int a, double x, const std::vector<std::string>& v);
Is it possible via meta-programming to automagically create a struct type whose attributes are the input arguments of the function ? For this example, one would get a structure equivalent to:
struct
{
    int arg1;
    double arg2;
    std::vector<std::string> arg3;
};

I guess that it is possible to achieve this through techniques like those introduced by A.Alexandrescu in "Modern C++ Design", but I was wondering whether such a 'prototype2struct' feature already exists in some library.
To add a little more context, I get the foo function from outside and its prototype can be anything. The underlying idea is to encapsulate a call to foo in order to execute it on another computer. Which means that I need:

to serialize the arguments of the call in a buffer
to send them on the remote computer
to execute the call on the remote computer.

So my idea was to create a type from the function prototype a use some serialization library on this type.
Comment: You could use [`boost::function_traits`](https://www.boost.org/doc/libs/1_41_0/libs/type_traits/doc/html/boost_typetraits/reference/function_traits.html) and then find a way to get a `std::tuple` of the argument types out of it, which shouldn't be too hard. But this won't work for function templates or overloaded functions. Also you won't be able to generate new structs through template meta programming.
Comment: I think what I am trying to say is "don't try to outsmart yourself to safe up on a few lines of code"
Comment: What do you want to achieve?  What is wrong with your approach of expliticly writing down the struct? And then passing that struct by reference to foo? (I often do this in a dependency injection environment) since it can facilitate maintainability. But other then that just be as explicit as you can (just pass arguments explicitly or model a struct explicitly)
Comment: Are you looking for `std::bind`? It creates a callable structure with member variables that are copies of bound function arguments.
Comment: Lambda functions exactly do that.
Comment: @chrysante, yes I am actually working torwards such a solution and I guess I will manage to find one; but I was looking for a potentially existing solution, better coded than I could do in the first place.
Comment: "its prototype can be anything" doesn't looks reasonable. and you cannot really get a type that can be anything.
Comment: @apple apple, you're right, "anything" is surely excessive in my context. At least, simple types like those I put in the example could be enough for me.
Comment: @edrezen Well, the hard part is really getting the `function_traits` template right. Boost does that part for you. Copying the types into a tuple should be straight forward from there.
Comment: @chrysante No need to use `boost::function_traits`. This can be done using CTAD as shown [here](https://stackoverflow.com/a/76366825/12002570).
Comment: Typically people define a protocol, like a protobuf service (see interface definition/description language, aka IDL) to define remote procedure calls. Wanting o call "any" function looks like a red flag at least for C++.
Answer: You could use std::tuple and CTAD as shown below:
#include <vector>
#include <string>
#include <tuple>
bool foo (int a, double x, const std::vector<std::string>& v);

template<typename Ret, typename... Param> struct GetParamType
{
   using type = std::tuple<Param...>;
   public:
       GetParamType(Ret(*)(Param...));
};

struct Name
{
    decltype(GetParamType(foo))::type t;   //std::tuple of desired types
};

Demo

Do note that this won't work for overloaded functions.
Comment: @chrysante Since `std::function` already deals with all the wierd stuff [this](https://godbolt.org/z/rEThv4eKW) becomes a pretty neat solution.
Comment: You can also leverage `std::function` with CTAD to cover more then function pointers.
Comment: @super Yeah, I wanted to show the most minimal and readable version that shows what OP posted in the question. This can be modified as you said, to cover more cases.
Comment: I would like to see you implement support for functors though without all the ugliness of my solution. Because you have to create so many specializations for all the reference/const/noexcept qualifier combinations afaik.
Comment: @chrysante Yes I originally wrote/used this to circumvent exactly that. In particular, the specializations that are needed for different cases can be at least minimized through this. Though it can be somewhat tricky/difficult/ugly(not impossible though ofcousre) here to modify this for functors.
Comment: I see no reason to use CTAD here, just normal template deduction would work.
Answer: So this is not pretty, but here it goes: (Then again is TMP ever pretty?)
template <typename F>
struct argument_tuple {
private:
    using FT = function_traits<F>;
    static constexpr size_t arity = FT::arity;
    template <size_t... I>
    static auto get_tuple(std::index_sequence) -> std::tuple<typename FT::template argument...>;
public:
    using type = decltype(get_tuple(std::make_index_sequence<FT::arity>{}));
};

This of course relies on a function_traits meta function. I found that boost::function_traits is not enough here, because it doesn't let you access argument types by index.
Here is a live demo
Please test this implementation more thoroughly than I did before you use it for anything serious.
Comment: @Jason I will heavy heartedly admit that your solution is pretty smart and perhaps superior to mine.
Comment: Looks pretty ugly but at least it works. Also check out more readable [version](https://stackoverflow.com/a/76366825/12002570)
Comment: Ages ago I found a similar implementation somewhere on SO, from which this implementation is derived. Unfortunately I can't seem to find it again. Also this version is heavily edited by me and probably won't resemble the original post very much, but if you find it please let me know.
Comment: Sure, someday somewhere we will find it(hopefully), lol.
Comment: @Jason Well, it's not really the same because this also works for function objects with user defined `operator()`
Comment: I see though I'm sure if OP were to say that they also want this to work with functors then my version can be modified accordingly. But since OP didn't explicitly say that and shown an example with only ordinary function, I am going to say that they are not looking for functors solutions. But good to have solution that works with functors.
Comment: I was looking for a name to call this trick/idiom. I've been using this at many places and wrote this as an alternative to specializations that were used to solve a particular problem one time I was reviewing some code. Perhaps you could suggest some name for this trick/idiom. I think this could have a separate name as just CTAD doesn't completely describe the trick. Would be nice to have a separate name and see this trick used at more places.
Comment: Check this:https://www.boost.org/doc/libs/1_82_0/libs/callable_traits/doc/html/callable_traits/reference.html#callable_traits.reference.ref_args . You already have the arguments as a tuple with boost.calkable_traits.
Answer: A naive implementation considering only free(static or none-member) functions would be:
template<typename>
struct arguments
{ using type = void; };

template<typename R, typename ... args>
struct arguments<R(args ...)>
{using type = std::tuple<args...>; };

template<typename F>
using arguments_t = typename arguments<T>::type;

But that excludes C variadic functions & abominable functions, as well as function pointers, member function pointers, function objects and lambdas. Calling conventions - not being std - are another problem.
One attempt to tackle this problem was boost.callable_traits. But that too ommits calling conventions and is too complicated, yet better than boost.function_traits relying on MPL.
Comment: My own (free, production grade, fully documented) solution at https://github.com/HexadigmSystems/FunctionTraits handles
everything you mentioned including calling conventions (the only such solution out there that does to the best of my knowledge). The only thing it doesn't handle is abominable functions by design (few will be impacted by its absence but consult the above link for details). The solution is otherwise more complete than all others I'm aware of including Boost's  .
Comment: Did you notice the boost link? There are 3 different boost libraries, trying to implement this; and none of them omits abominable functions. How does your impedimentation stack up against them?
Comment: I omitted abominable functions by design since very few will ever require them in practice. The reasons are fully explained at the above link and their absence won't be a show stopper for most (few will ever need it). As for how it compares to Boost, it's more complete IMHO and the main issues are discussed at the link itself. Note that I've also examined the Boost code and it's needlessly complicated and bloated IMHO (so many files for a relatively small though non-trivial task). My own solution effectively does everything it does and more. It's a very worthy (humbly better) competitor.
Comment: If it works for you, then good for you. But if you want to publish it, it has a long way to go. As I mentioned in a previous comment boost provides 3 different libraries for the matter. I just linked one in my post. Now you can think why std has no such Library? The answer is simple: No satisfying generic library with simple enough implementation exists. standard doesn't miss corner cases ; implementations of standard don't miss their special extensions.
Comment: It was never intended to be published in Boost or elsewhere and wouldn't make it into the C++ standard itself. Its support for calling conventions alone would disqualify it (since they're not supported in the standard), let alone no support for abominable functions. The issues are addressed in the link itself in its "design considerations" section. As a practical function traits library however, for everyday use by most developers, I believe it has certain benefits that give it an edge over all other solutions I've seen, including its lone support for calling conventions (an important one).


C++ delete array crashes

Question: This is my code...
int* getA(int no)
{
   int *a = new int[no];
   return a;
}

void main()
{
   int* a = getA(10);
   delete []a;
}

When I delete the array a in main it crashes... what is the reason??
The error is
"Windows has triggered a breakpoint in Final.exe. This may be due to a corruption of the heap, which indicates a bug in Final.exe or any of the DLLs it has loaded..........."
But I am able to assign and access the elements of a in the main method but when I try to delete it is crashing....
Comment: It does not crash for me. Also, this main() definition is not legal in C++.
Comment: This shouldn't crash.  Is this the code you're actually using?
Comment: Could you provide some error message?
Comment: `void main()` is a compiler extension. It should be `int main()`, even if you don't return anything.
Answer: Nothing wrong with this code. Presumably either

It differs from your real code in some significant way, or
Something unrelated in your real code is corrupting the heap before this code runs.
Answer: It should just work (the delete).
Possibly, the application crashes because of undefined behaviour, if your compiler accepted that code. Try the following, and run it under a debugger to verify that it crashes in the delete:
int* getA(int no)
{
   int *a = new int[no];
   return a;
}

int main()
{
  int* a = getA(10);
  delete []a;

  return 0;
}

C++ delete array crashes


update wpf element before Thread.sleep executes

Question: I want to know how to refresh a wpf element before Thread.sleep() is executed. In the scenario below the Thread.sleep() call is executed first, then update the wpf element.
I tried this:
In the button_click event handler:
EDIT: To understand what I want, I added some variable assignations and comments.
<code> private void button_click(object sender, RoutedEventArgs e){
     //fist of all, set the static variable to_change to true, then Update GUI label
     to_change = true;
     Thread thread = new Thread(UpdateGUI);
     thread.Start();
     //Then sleep 1 second and ( With label changed)
     Thread.Sleep(1000);// one second
     //and lately reset the value of to_change to false and update the GUI again
     to_change = false;
     //UpdateGUI.
 }
</code>
And in UpdateGUI I have:
<code> private void UpdateGUI()
    {
        this.Dispatcher.BeginInvoke(DispatcherPriority.Normal,
            (ThreadStart)delegate()
            {
                this.label_success.Content = "Successful!";
            }
            );
    }
</code>
Also I've tried with DispatcherPriority.Send which is the highest priority
I guess i'm missing some important concept.
Thanks in advance !
Comment: **Never** sleep in the UI thread. What do you want to achieve?
Comment: @Clements I've edited my question to better understanding. Let me know if you doesn't understand what I am trying to do.
Comment: @jberger could be useful if you explain your point.
Comment: @Ecacavelos 1st, what @clemens said. 2nd, you're toggling a boolean value. (if you have some long-running that's supposed to run in the `Click`, then indicate it in the question via `LongRunningCode();`)
Comment: tell us in a more abstract way, what you're trying to do (e.g. `the user clicks a button and I start downloading a file in the background, then I want to show "File Downloaded" when it's complete.`)
Answer: You can force WPF to process all of the items in its queue by Invoking to the Dispatcher an item that is a lower or equal priority to the task you want to execute.  Just pass an empty delegate as the action, like this.
<code>Dispatcher.CurrentDispatcher.Invoke(DispatcherPriority.Normal, new Action(delegate { }));
</code>
This will work; however doing this should not be "normal", and I'm curious why you need to sleep your main UI thread...  The code you show above is scary, but I don't know the big picture, so maybe there is a reason for this?
Comment: Then set yourself a DispatcherTimer that ticks after that period and reset the value in the Tick event handler.
Comment: @Ecacavelos the main reason it is bad practice to sleep in the main thread is because the UI will be completely unresponsive for the entire time it is in the sleep call.
Comment: Thanks @davisoa. You say it is a bad practice to sleep the main thread?. I want to set a static variable for a period of time to some value and show a message in a label of a window. After that period I want to set to the old value again.


Adding taxonomy term list to another taxonomy term's overview

Question: Let me start by saying I'm fairly new to Drupal. I'm using Drupal 7.
I have a content type "product" which is assigned to one or more taxonomy terms in "collections" (taxonomy). Then I have another taxonomy called "brands".
The "brands" taxonomy has a field reference to a "collections" taxonomy term. For instance: brand "Google" can be assigned to collections "Shoes" or "Bags".
On the collection page for "Shoes", all the products tagged "Shoes" are being displayed. On top of the page, I want to add a list of all the brands in the "brands" taxonomy, that are assigned to this particular collection ("Shoes"). They are independent from the products themselves. How would I display this list on top of the page? Do I need to create a custom overview?
Answer: In this case you need to a create view that displays block on top of the collection page.
The view should display taxonomy terms in the "collections" vocabulary filtered by a contextual filter (taxonomy term id) so that only the desired taxonomy term is display.
Next you should add a relationship using the field reference you're using on that term.
Finally you can use the relationship to display fields or taxonomy terms to the display.
I tried to explain it briefly, let me know if you need further explanation.
Comment: I hope this article helps you out: http://atendesigngroup.com/blog/making-sense-drupal-views-relationships-and-entity-references
Comment: Thanks for your answer! So if I understand correctly, I need to create a view for displaying the brand list on top of the collection page? This is independent from the collection page itself? How do I add this relationship?
Comment: Thank you very much! I will take a look at it, and accept your answer as soon as I know for sure it was the right one :)


Concatenate pandas string columns with separator for large dataframe

Question: I have a large dataframe (~1 million rows) with 20 string columns that I'm trying to concatenate into a single column with a separator, dropping NA values on the way. (Each row has a variable number of valid entries and NA values.)
Based on the solution here, I can get the output I need using df.apply but it is very slow:
raw['combined'] = raw.loc[:, 'record_1':'record_20'].apply(lambda x: '|'.join(x.dropna().values), axis=1)

Is there a faster way to do this concatenation or am I stuck with df.apply?
Comment: It is very difficult to answer your question without seeing both the data and the code produces your problem. Please read about how to ask a good question and try to post a [Minimal Reproducible Example](https://stackoverflow.com/help/minimal-reproducible-example "Minimal Reproducible Example") so we can better help you.
Comment: Check out: [Concatenate column values in a pandas DataFrame while ignoring NaNs](https://stackoverflow.com/questions/54468506/concatenate-column-values-in-a-pandas-dataframe-while-ignoring-nans) in particular solution by rafaelc.
Comment: What format are we talking about? CSV? Can the delimiter be part of the content? Is there anything else in the file except these 20 columns? I think if it is CSV, then the best way would be to not load it as DataFrame but work in the file text per line directly. Something like `with open('filename') as f: lines = [line.rstrip() for line in f]`, merge that in the required way by replacing the delimiter with `|` and write to an output file directly, so you don't keep anything in memory.
Answer: agg is much faster than apply. Use agg instead.
import time
import timeit
from pandas import DataFrame
import numpy as np
import pandas as pd
from datetime import datetime

df = pd.DataFrame({
    'date' : ['05/9/2023', '07/10/2023', '08/11/2023', '06/12/2023'],
    'A' : [1,  np.nan,4, 7],
    'B' : [2, np.nan, 5, 8],
    'C' : [3, 6, 9, np.nan]
}).set_index('date')

print(df)
"""
              A    B    C
date
05/9/2023   1.0  2.0  3.0
07/10/2023  NaN  NaN  6.0
08/11/2023  4.0  5.0  9.0
06/12/2023  7.0  8.0  NaN
"""
start_time = datetime.now()
df['Without_NAN'] = df[df.columns].agg(lambda x: ','.join(x.dropna().astype(str)),axis=1)
print(df)

"""

              A    B    C  Without_NAN
date
05/9/2023   1.0  2.0  3.0  1.0,2.0,3.0
07/10/2023  NaN  NaN  6.0          6.0
08/11/2023  4.0  5.0  9.0  4.0,5.0,9.0
06/12/2023  7.0  8.0  NaN      7.0,8.0

"""
end_time = datetime.now()
print('Duration: {}'.format(end_time - start_time))


Error in The type of the expression must be an array type but it resolved to Object

Question: In the following code:
public class ColorTableDialog extends Dialog
  implements View.OnClickListener
{
    public ColorTableDialog(Context paramContext)
      {
        super(paramContext);
        requestWindowFeature(1);
        Object localObject = new int[16];
      }

      ColorTableDialog(Context paramContext)
          {
            super(paramContext);
            requestWindowFeature(1);
            Object localObject = new int[16];
            localObject[0] = -1;
            localObject[1] = -4144960;
            localObject[2] = -8355712;
            localObject[3] = -16777216;
            localObject[4] = -65536;
            localObject[5] = -8388608;
            localObject[6] = -256;
            localObject[7] = -8355840;
            localObject[8] = -16711936;
            localObject[9] = -16744448;
            localObject[10] = -16711681;
            localObject[11] = -16744320;
            localObject[12] = -16776961;
            localObject[13] = -16777088;
            localObject[14] = -65281;
            localObject[15] = -8388480;
            this.mColors = ((I)localObject);
            setContentView(main);
            localObject = (ScrollView)findViewById(main);
    }
}

Here i got the error

Error in The type of the expression must be an array type but it resolved to Object.

Actually, I lost my source code.  I decompiled this code, and got this error.
Answer: I believe that your problem is in this line:
 Object localObject = new int[16];

Here, you're declaring localObject to have static type Object.  Although it's really referring to an array of ints, the compiler only remembers that its type is Object.  Accordingly, when you then say
localObject[0] = -1;

etc., the compiler only remembers that localObject is an Object, not an int[].  That is, it doesn't know that it's not referring to something like a String or HashSet<Integer>, in which case applying the braces is not allowed.
To fix this, change the type of localObject to be int[], as in
int[] localObject = new int[16];

That way, the compiler remembers that it's an array of ints, and all will work out just great.
More generally, unless you have a good reason not to, it's usually a good idea to give types to your variables that are as specific as possible.
Hope this helps!
Answer: you can use:
 ((int[])localObject)[0]=-1
to cast the localObject which is Objcet type to the int[] type.
Since the int[] type(not the int type) is one of the subclasses of Object type, and you have given an array which is int[] type to localObject, so the expression a=(int[])localObject will retrive the int[] type from localObject which is Object type, and by using a[0] you can get the element you want from the array a.
Hope this answer is helpful!
Comment: Check [how to write an answer](https://stackoverflow.com/help/how-to-answer).
Add more details to justify your answer.


Orthogonal basis of $\mathbb R^n$ consisting of $\pm 1$ vectors

Question: I have to prove that if orthogonal basis of $\mathbb R^n$ containing only vectors which coordinates are $1$ or $-1$ exists then $n \leqslant 2$ or $n$ is divisible by 4.
It's obvious that $n$ has to be even but I have no idea what to do next. I'm not allowed to use determinants.
Comment: Study the hadamard-matrices. There is a general upper bound for the determinant which only occurs if the vectors are mutually orthogonal. And the theoretical upper bound is only possible for numbers divisble by $4$. (With the exeptions $1$ and $2$, as you mentioned)
Comment: [The wiki article on Hadamard matrices](https://en.wikipedia.org/wiki/Hadamard_matrix) could be a useful resource here.
Comment: Thanks, but determinants haven't been covered on my course so I'm not allowed to use them in the problem.
Answer: Since exchanging the columns, and flipping the sign of an entire column, preserve orthogonality, we may assume that

The top row of the matrix is all-ones.
The second row is $n/2$ ones followed by $-1$s.

So far so good, but what should the third row be? Let $k$ be the number of $1$s in the first half of the row. There must be $k$ negative entries in the second half. But then the scalar product of the second and third rows is
$$
k -(n/2-k) +k-(n/2-k) = 4k-n
$$
which is not zero.


Check Network change in Progressive web app?

Question: How to get callback while changing network in Progressive web app?
Example : In Flipkart Lite, when ever we disconnect from internet, app color changes from blue to gray and when we connect from internet app color changes from gray to blue.
Please tell me, How to implement this functionality?
Comment: I don't see why this is too broad. The question is really simple, maybe it can be reworded for clarification, but it isn't broad at all.
Comment: Hi and welcome to SO! Please read [this](http://stackoverflow.com/help/how-to-ask) post for how to ask better questions, which will help people give you better answers.
Answer: You can use the window.navigator.online property and you can listen to the online and offline events.


Drush installed globally via composer as root user, but how to access Drush with ordinary user?

Question: By following the instructions on the Drush git page:
composer global require drush/drush:6.*
I have Drush up and running (it seems to live in /root/.composer/vendor/drush/drush). But I imagine I shouldn't be running it via root. So how do I run it as my ordinary shell users?
When I try running drush it says command not found. Although it lets me use Composer. I tried installing Drush again through Composer while logged in as ordinary user without any luck. The Drush folder is also inaccessible..
Comment: Have you read the installation docs? I'm 99% certain this is covered
Comment: I fixed it just now.. the PATH to composer's bin was incorrectly added, when I added it for the logged-in-user it started working. At least I think it was that, because .composer and .drush directories suddenly appeared in my home directory.
Answer: To install for all users on the server:
curl -sS https://getcomposer.org/installer | php
mv composer.phar /usr/local/bin/composer
ln -s /usr/local/bin/composer /usr/bin/composer

git clone https://github.com/drush-ops/drush.git /usr/local/src/drush
cd /usr/local/src/drush
git checkout 7.0.0-alpha5  #or whatever version you want.
ln -s /usr/local/src/drush/drush /usr/bin/drush
composer install
drush --version

Personally I don't bother making the composer symlink from /usr/local/bin to /usr/bin and made the drush symlink to /usr/local/bin (rather than /usr/bin) as I have /usr/local/bin in my $PATH but YMMV...
Source: http://docs.drush.org/en/master/install/
Comment: This is strange. Why do we need to use git clone at all? Is there no way to do this with `compser require`, or by adding a line in composer.json? This is what most tutorials / online instructions say, except that they will all give you drush in user home directory.
Comment: @donquixote - AFAIK you nailed it when you said "except that they will all give you drush in user home directory"! I am not aware of any way to explicitly install it to a specific location as my answer does. TBH, I'm not sure why, but I've always assumed that it's a limitation of composer itself?!
Comment: https://stackoverflow.com/questions/33380480/composer-global-system-wide-multi-user-install maybe this helps
Comment: Interesting... Personally, I'll still continue to use the above as I like to keep custom global binaries limited to /usr/local because IMO it's much cleaner. A quick read of the drush docs suggest that they now have a tool that allows all users to globally use drush from within a composer project, so it sounds like what you want is totally possible with current drush. IMO though, it's better to do it right (even if it requires an extra line), rather than work around the issues created by doing it hacky in the first place. But that's only my opinion...


Help using hook_theme() on custom module

Question: I've been writing a custom module to spit a content type into 2 pages, with custom fields accessible via a tab.
For ease I've built the test case on a fresh d7 install and using the predefined article content type.
My module folder has the following files:

Now, the template file is simply a copy of the bartik themes node.tpl.php file, but for some reason the module will not load it. I've read through the hook_theme() page and used the examples for developers theming_example, but I just can't get it to work.
Any help would be greatly appreciated.
-------- UPDATED CODE ----------------
<code>    <?php
    /**
     * Implements hook_menu().
     */
    function article_page_menu() {

      $items['node/%/info'] = array(
        'title' => 'Info',
        'page callback' => 'article_page_page_callback',
        'page arguments'   => array(1),
        'access callback' => 'article_page_access_callback',
        'access arguments' => array(1),
        'type' => MENU_LOCAL_TASK, // tab instead of MENU_CALLBACK
        'weight' => '1000', // last tab item
      );

      return $items;
    }

    /**
     *  Page Callback
     */
    function article_page_page_callback($nid) {
      if (is_numeric($nid)) {
        $node = node_load($nid);

        if($node->type == 'article') {
          return theme('article_page_template', array('node' => $node));
        }

        drupal_not_found();
        return;
      }
      return FALSE;
    }

    /**
     *  Create the access callback
     */
    function article_page_access_callback($nid) {
      if (is_numeric($nid)) {
        $node = node_load($nid);
        // only show for article types
        if($node->type != 'article'){
          return FALSE;
        } else {
          return TRUE;
        }
      }
      return FALSE;
    }

    /**
     * Implements hook_theme().
     */
    function article_page_theme($existing, $type, $theme, $path) {
      return array(
        'article_page_template'  => array(
          'template' => 'article_page_template',
        ),
      );
    }

    function theme_article_page_template($variables) {
      $node = $variables['node'];
      $build = node_view($node);
      $output = drupal_render($build);
      return $output;
    }
</code>
------------ END UPDATED CODE -----------
--------- BELOW IS THE OLD CODE ---------------------
Here is the code from the module file:
<code>        <?php
        /**
         * Implements hook_menu().
         */
        function article_page_menu() {

          $items['node/%/info'] = array(
            'title' => 'Info',
            'page callback' => 'article_page_load',
            'page arguments'   => array(1),
            'access callback' => 'article_page_access',
            'access arguments' => array(1),
            'type' => MENU_LOCAL_TASK, // tab instead of MENU_CALLBACK
            'weight' => '1000', // last tab item
          );

          return $items;
        }

        /**
         * Constructs a descriptive page.
         */
        function article_page_load($nid) {
          if (is_numeric($nid)) {
            $node = node_load($nid);

            if($node->type == 'article') {
              // convert object to array
              // else we get an error
              $build = node_view($node);
              $render = drupal_render($build);
              return $render;
            }
            drupal_not_found();
            return;
          }
          return FALSE;
        }

        /**
         *  Create the access callback
         */
        function article_page_access($nid) {
          if (is_numeric($nid)) {
            $node = node_load($nid);
            // only show for article types
            if($node->type != 'article'){
              return FALSE;
            } else {
              return TRUE;
            }
          }
          return FALSE;
        }

        /**
         * Implements hook_theme().
         */
        function article_page_theme($existing, $type, $theme, $path) {
          return array(
            'article_page_template'  => array(
              'template' => 'article_page_template',
            ),
          );
        }
</code>
Answer: It seems like there are quite a few elements in your module code that are used incorrectly. For example, your page callback should not be a hook (you are using hook_load()) and the callback should call theme() and invoke your custom theme function. In addition, your hook_theme() implementation is incorrect and you will also need to implement hook_theme_registry_alter() in your module to let the theme system know about your template file.
There is a good example of all this that you can base your code off of in this comment in the API for hook_theme()
Also, you seem to be mixing together the terms 'node' and 'page' so I am unsure whether you are using the terms correctly (i.e. I'm not sure if you're mistakenly using a node template as your basis when you may really want to use a page template, etc.)
Comment: I would say that your issues with creating the additional node page and redering its content are a separate issue from the template call not working and I'd suggest opening an new question for that issue.
Comment: Hi Sheena and thanks for your answer. I called the module article_page, but it should create a 1 to 1 copy of the full node view (which in the template file is defined as $page == true), but that doesn't work as the elements for if(!page){} are shown. Yes, the template file is the node.tpl.php file and I wish to display the $node and not $page content. So basically I want to display an exact copy of node/1 at the url node/1/info and with use of the template file show the specific fields I need.
Comment: Ok, i've edited my code - it's posted above - now the template is loaded (i know because i added a bit of text in the first line), but none of the defined variables in the template present. I guess I have to call them all using $node->element. Note that I did not use hook_theme_registry_alter. It says: 'Alter the theme registry information returned from hook_theme().' Why would I need to alter the info I set in my hook_theme() function?
Answer: You have a quick tutorial for hook_theme in D8 here if you need: http://westweb-solutions.com/blog/drupal-8-how-use-hooktheme. It's a bit more tricky, but D8 is gaining ground quickly.


C program crashes when accessing next element in array of struct

Question: void struct_tokens(struct Words **w_count, int size)
{
    *w_count = (struct Words*)calloc(size, sizeof(struct Words));
    char *temp;
    int n = 0;
    int i = 0;
    printf("Value 1: %s\n", (*w_count[0]).word);
    printf("Value 2: %s\n", (*w_count[1]).word);
}

My struct looks like this:
struct Words
{
    char word[20];
    unsigned int count;
};

It crashes as soon as I access the next element in the array, so w_count[0] is accessed but it cannot access w_count[1] without crashing. So the Value 1 prints to console but Value 2 does not, why is this?
Comment: Show us a full program that's as simple as possible that still has this issue.
Comment: @coderredoc I rechecked my code and it appears I didn't change fully one of your lines, cheers for that mate it seems to work now :).
Comment: How is `struct_tokens()` called, and how are the variables passed in set.
Comment: The answer holds - earlier within given code the way you accessed lead to undefined behavior. But Then correcting that if you still get error then there is something you didn;t show
Comment: The call to `calloc()` looks more like a call to `malloc()` with a typo in its name.
Comment: @alk changed the typo
Comment: There is no need to cast the result of `calloc()` in C. Does the real code `#include` ``?
Answer: The calloc call is wrong - it would be
*w_count = calloc(size, sizeof(struct Words));

Accessing the instance of the structure would be
printf("Value 1: %s\n", (*w_count)[0].word);

[] has higher precedence than *. In earlier case you were having undefined behavior (which lead to the crash).
Also note that the memory allocated will be initialized with 0. As a result the char arrays will contain nothing other than \0 - it won't print anything when used in printf.
Few points:

void* to struct Words * conversion is done implicitly - you don't need to cast it.
Check the return value of calloc in case it returns NULL you should handle it appropriately.
Free the dynamically allocated memory when you are done working with it. (using free() ).
Code wise the correct code for calloc would be like this:-
*w_count = calloc(size, sizeof(struct Words));
if( *w_count == NULL ){
   perror("calloc");
   exit(EXIT_FAILURE);
}


incorrect devicePixelRatio in Chrome

Question: I've been playing around with the device mode in Chrome to test my html5 game if it scales properly in other resolutions.
Now when I switch back to the desktop mode, my page is somewhat shrunk. After a short investiagtion it turns out it's due to incorrect windows.devicePixelRatio, which is all of a sudden set to 0.3333333432674408. Previously this value was set to 1.
Tested the game in other browsers , all of them show correct pixel ratio.
Tried changing the folder name and (voila) the pixel ratio is back to normal. But still when I rename the folder back, I'm getting incorrect pixel-ratio value again.
So it has to be cached somewhere but i have no idea where exactly.
Full cleanup of all browser data didn't help. Is there anything else i could try in this case?
Answer: it seems that either cleaning chrome temp files using CCleaner or removing GPU Cache (C:\Users\[user]\AppData\Local\Google\Chrome\User Data\Default\GPUCache) manually fixed the issue.

incorrect devicePixelRatio in Chrome


Text between two tags (

Question:
Possible Duplicate:
How to parse and process HTML with PHP?

please help me, i need script which select text between tag's (
any text in source soce
 ) on loaded page with file_get_contents.
A friend advised me, but it does not work:
$vyber = file_get_contents($url);
preg_match_all("'(.*?)'si", $vyber, $get);

Comment: So your friend advices you to search for spans when looking for divs? :o
Comment: Your expression looks for `` while your stated requirement is stuff inside `` (not to mention the lack of an `id='image'` attribute)
Comment: Try querypath with `print qp($url)->find("div#image")->text();`
Answer: I dont know whether regex is the best solution here.
You cannot create perefect regex (or you can but it will take much time) which will cover

What I would do is using html dom parser
http://simplehtmldom.sourceforge.net/
The code would be:
<?php
    require_once('DomParserFile.php'); //Replace this ofc
    $Html = file_get_html('http://YourUrlHere.com/'); //html not file :)
    $ContentInThisDiv = $Html->fing('div#image')->src;
    echo($ContentInThisDiv);
?>

Answer: $dom = new DOMDocument;
$dom->loadHTMLFile('http://urlhere.com');

$xpath = new DOMXPath($dom);
$nodes = $dom->getElementsByTagName('div');

    foreach($nodes as $val):
        $id = $val->getElementByid('image');
        foreach($id as $content){
            $text = $content->nodeValue;
        endforeach;
        echo $text . '
\n';
    endforeach;

This should work although not tested.

Text between two tags (


Cricket bowling versus baseball pitching speed?

Question: How do cricket bowlers deliver the ball at generally same speed as baseball pitchers inspite of a run up?  How much do the following factors play in: different balls (is the baseball more aerodynamic because of stitches?), different throwing height (baseball players throw from a elevated mound), different distance to where they measure ball speed from, (is wicket further than plate?)  Which other factors play in?
Answer: The essential difference is that bowlers must by law keep their elbows straight. This means that a run-up is used to generate pace, rather than the stepping motion pitchers use, and pitchers can use their upper-body muscles to generate further pace.
I'm not a bio-mechanic expert, so can't explain the actual processes involved, sorry.
Comment: To add a little to the answer above, the act of straightening the arm allows for greater force to be imparted to the ball and therefore greater speed.  In Cricket you are not allowed to do this and so the speed has to be generated by a combination of run up and arm rotation.


Como chamar uma function de outro arquivo, dentro de uma function do arquivo principal?

Question: Tenho no arquivo App.js
E na primeira vez que é carregado, ele chama a const response = await api.get('/searchDate');, e retorna uma lista de dates. Quero pegar a primeira posição da lista, chamar o arquivo Transaction.js e buscar no back, as informações de acordo com o date[0].
Teria como fazer isto?
Observação: Toda vez que uma nova date é selecionada o arquivo Transaction.js é chamado e envia o dateSelected e busca as informações. Com a chamada no html no return <Transaction dateSelected={dateSelected} />.
Porém, eu queria chama-lo a primeira vez que carrega a página, com a primeira date da lista.
Arquivo App.js
function App() {
  const [dates, setDates] = useState([]);
  const [dateSelected, setDateSelected] = useState();

  useEffect(() => {
    async function loadDates(){
      const response = await api.get('/searchDate');
      setDates(response.data.yearMonth);
    };
    console.log(dates[0]); // aqui ele mostra certinho o date da primeira posição - ele seria o dateSelected
    // Como chamar o function Transaction({dateSelected}) {
    loadDates();
  },[dates[0]]);

  const handleChange = (event) => {
    setDateSelected(event.target.value);
  };
  return (

        <Transaction dateSelected={dateSelected} />

  );
}

Arquivo Transaction.js
function Transaction({dateSelected}) {
  const [transactions, setTransactions] = useState([]);
  useEffect(() => {
    async function loadTransaction() {
      const response = await api.get('/search?yearMonth='+dateSelected);
      setTransactions(response.data.transaction);
    };
    loadTransaction();
  }, [dateSelected]);

Comment: o componente precisa de um estado e esse estado controlar se é carregado 1 ou mais vezes! só isso acho que é o necessário, agora se está mudando é porque você no mesmo código muda o estado ou talvez pega um estado que esteja mudando e por isso do carregamento do arquivo.
Answer: Fix um demo no CodeSandbox que certamente não corresponde a funcionalidade que você quer, mas exemplifica como importar arquivos e extrair hooks.
Para reaproveitamento de código, use import. Você tipicamente importa funções, classes ou constantes.
import React, { useState, useEffect } from "react";
import api from "../utils/fakeApi";
import Transaction from "./Transaction";

Para reaproveitamento de ciclo de vida, crie hooks customizados. Por convenção, um hook deve começar com use e ter um nome que começa com maiúsculo logo após.
import { useState, useEffect } from "react";
import api from "../utils/fakeApi";

export default function useTransaction(dateSelected) {
  const [transactions, setTransactions] = useState([]);

  useEffect(() => {
    async function loadTransaction() {
      const response = await api.get("/search?yearMonth=" + dateSelected);
      setTransactions(response.data.transaction);
    }
    loadTransaction();
  }, [dateSelected]);

  return transactions;
}

Não confunda hooks com componentes de UI. Estes retornam componentes e podem (ou não) usar hooks. Funções ou classes de UI devem começar com letra maiúscula.
import React from "react";
import useTransaction from "../hooks/useTransaction";

export default function Transaction({ dateSelected }) {
  const transactions = useTransaction(dateSelected);

  return (

transactions

para {dateSelected.toDateString()}:

        {transactions.map(item => (

{item}

        ))}

  );
}

Comment: entendi o que vc fez. Só tem uma coisa que preciso.

No código vc começa com o ```const [dateSelected, setDateSelected] = useState(new Date());```

Porém, não posso começar com o ```new Date()```, preciso começar com o primeiro ```Date``` que vier da chamada do ```const response = await api.get("/searchDate");```. Como faria isso?
Comment: APIs possuem combinações dos estados: carregando vs não-carregando e sucesso vs erro; você deve lidar com as 4 possibilidades. Enriqueça o seu hook para retornar tudo isso. Ex: https://andrewstevens.dev/posts/useApi-react-hook/


Target-Action problems with custom view built from standard views

Question: I have a custom view subclassing NSView, which is just an NSStackView containing a label, slider, a second label and a checkbox. The slider and checkbox are both configured to report changes to the view (and eventually, via a delegate to a ViewController):
fileprivate extension NSTextField {
    static func label(text: String? = nil) -> NSTextField {
        let label = NSTextField()
        label.isEditable = false
        label.isSelectable = false
        label.isBezeled = false
        label.drawsBackground = false
        label.stringValue = text ?? ""
        return label
    }
}

@IBDesignable
class Adjustable: NSView {

    private let sliderLabel = NSTextField.label()
    private let slider = NSSlider(target: self, action: #selector(sliderChanged(_:)))
    private let valueLabel = NSTextField.label()
    private let enabledCheckbox = NSButton(checkboxWithTitle: "Enabled", target: self, action: #selector(enabledChanged(_:)))

    var valueFormatter: (Double)->(String) = { String(format:"%5.2f", $0) }

    ...

    @objc func sliderChanged(_ sender: Any) {
        guard let slider = sender as? NSSlider else { return }

        valueLabel.stringValue = valueFormatter(slider.doubleValue)
        print("Slider now: \(slider.doubleValue)")

        delegate?.adjustable(self, changedValue: slider.doubleValue)
    }

    @objc func enabledChanged(_ sender: Any) {
        guard let checkbox = sender as? NSButton else { return }
        print("Enabled now: \(checkbox.state == .on)")

        delegate?.adjustable(self, changedEnabled: checkbox.state == .on)
    }
}

Using InterfaceBuilder, I can add one instance of this to a ViewController by dragging in a CustomView and setting it's class in the Identity Inspector. Toggling the checkbox or changing the slider will have the desired effect.
However, if I have multiple instances then in the target-action functions self will always refer to the same instance of the view, rather than the one being interacted with. In other words, self.slider == sender is only true in sliderChanged for one of the sliders. While I can get the correct slider value via sender, I cannot update the correct label as self.valueLabel is always the label in the first instance of the custom view.
Incidentally, @IBDesignable and the code intended to support it have no effect so there's something I'm missing there too - Interface Builder just shows empty space.
The whole file:
import Cocoa

fileprivate extension NSTextField {
    static func label(text: String? = nil) -> NSTextField {
        let label = NSTextField()
        label.isEditable = false
        label.isSelectable = false
        label.isBezeled = false
        label.drawsBackground = false
        label.stringValue = text ?? ""
        return label
    }
}

protocol AdjustableDelegate {
    func adjustable(_ adjustable: Adjustable, changedEnabled: Bool)
    func adjustable(_ adjustable: Adjustable, changedValue: Double)
}

@IBDesignable
class Adjustable: NSView {
    var delegate: AdjustableDelegate? = nil

    private let sliderLabel = NSTextField.label()
    private let slider = NSSlider(target: self, action: #selector(sliderChanged(_:)))
    private let valueLabel = NSTextField.label()
    private let enabledCheckbox = NSButton(checkboxWithTitle: "Enabled", target: self, action: #selector(enabledChanged(_:)))

    var valueFormatter: (Double)->(String) = { String(format:"%5.2f", $0) }

    @IBInspectable
    var label: String = "" {
        didSet {
            sliderLabel.stringValue = label
        }
    }

    @IBInspectable
    var value: Double = 0 {
        didSet {
            slider.doubleValue = value
            valueLabel.stringValue = valueFormatter(value)
        }
    }

    @IBInspectable
    var enabled: Bool = false {
        didSet {
            enabledCheckbox.isEnabled = enabled
        }
    }

    @IBInspectable
    var minimum: Double = 0 {
        didSet {
            slider.minValue = minimum
        }
    }

    @IBInspectable
    var maximum: Double = 100 {
        didSet {
            slider.maxValue = maximum
        }
    }

    @IBInspectable
    var tickMarks: Int = 0

    override init(frame: CGRect) {
        super.init(frame: frame)
        setup()
    }

    required init?(coder decoder: NSCoder) {
        super.init(coder: decoder)
        setup()
    }

    override func prepareForInterfaceBuilder() {
        setup()
    }

    override func awakeFromNib() {
        setup()
    }

    private func setup() {
        let stack = NSStackView()
        stack.orientation = .horizontal
        stack.translatesAutoresizingMaskIntoConstraints = false

        stack.addArrangedSubview(sliderLabel)
        stack.addArrangedSubview(slider)
        stack.addArrangedSubview(valueLabel)
        stack.addArrangedSubview(enabledCheckbox)

        sliderLabel.stringValue = label
        slider.doubleValue = value
        valueLabel.stringValue = valueFormatter(value)
        slider.minValue = minimum
        slider.maxValue = maximum
        slider.numberOfTickMarks = tickMarks

        // Make the slider be the one that expands to fill available space
        slider.setContentHuggingPriority(NSLayoutConstraint.Priority(rawValue: 249), for: .horizontal)

        sliderLabel.widthAnchor.constraint(equalToConstant: 60).isActive = true
        valueLabel.widthAnchor.constraint(equalToConstant: 60).isActive = true

        addSubview(stack)

        stack.leadingAnchor.constraint(equalTo: leadingAnchor).isActive = true
        stack.trailingAnchor.constraint(equalTo: trailingAnchor).isActive = true
        stack.topAnchor.constraint(equalTo: topAnchor).isActive = true
        stack.bottomAnchor.constraint(equalTo: bottomAnchor).isActive = true
    }

    @objc func sliderChanged(_ sender: Any) {
        guard let slider = sender as? NSSlider else { return }

        valueLabel.stringValue = valueFormatter(slider.doubleValue)
        print("Slider now: \(slider.doubleValue)")

        delegate?.adjustable(self, changedValue: slider.doubleValue)
    }

    @objc func enabledChanged(_ sender: Any) {
        guard let checkbox = sender as? NSButton else { return }
        print("Enabled now: \(checkbox.state == .on)")

        delegate?.adjustable(self, changedEnabled: checkbox.state == .on)
    }
}

Comment: Related: [Referring to self during property declaration in Swift](https://stackoverflow.com/questions/31021390/referring-to-self-during-property-declaration-in-swift).
Comment: Not related to the issue: `setup` is called twice, from `init?(coder decoder: NSCoder)` and `awakeFromNib()`.
Comment: Changing the two relevant `private let`s to `private lazy var` does indeed fix things.
Comment: Any idea why the `@IBDesignable` might not be working? It calls `prepareForInterfaceBuilder` and the view has a sensible frame in `setup`, but Interface Builder just shows empty space.
Answer: The solution, as described in the question linked by Willeke, was to ensure init had completed before referencing self. (I'm slightly surprised the compiler allowed it to be used in a property initialiser)
Wrong:
private let slider = NSSlider(target: self, action: #selector(sliderChanged(_:)))
private let enabledCheckbox = NSButton(checkboxWithTitle: "Enabled", target: self, action: #selector(enabledChanged(_:)))

Right:
private lazy var slider = NSSlider(target: self, action: #selector(sliderChanged(_:)))
private lazy var enabledCheckbox = NSButton(checkboxWithTitle: "Enabled", target: self, action: #selector(enabledChanged(_:)))


Help with Problem 10 in Chapter 7 of Lang's Algebra

Question: I have no idea how to proceed with the following problem from Lang's Algebra:
Let $n$ be a positive integer and let $\zeta,\zeta'$ be primitive $n$-th roots of unity.
a) Show that $\frac{1-\zeta}{1-\zeta'}$ is an algebraic integer.
b) If $n\geq 6$ is divisible by at least two primes, show that $1-\zeta$ is a unit in the ring $\mathbb{Z}[\zeta]$.
This has been asked twice before, here and here.
However, I don't fully understand the approach given in either. In the first, I don't understand why $1-\zeta^{p^k}$ is a unit mod $p$ if $\zeta^{p^k}$ is an $m$-th root of unity. In the second, I don't understand how the substitution advised in the comments helps to solve the problem. This is probably supposed to be obvious but please help, I don't get it.
Thanks.
Answer: For a): Fix some primitive $n$-th root of unity $\zeta$. Then all other primitive $n$-th roots of unity are of the form $\zeta^k$ with $(k,n)=1$. If this is the case, then there is $k'$ such that $kk'\equiv1\mod n$. Now write $\zeta'=\zeta^{k}$ and $\zeta=(\zeta^k)^{k'}$ and note the following:
$$\frac{1-\zeta}{1-\zeta'}=\frac{1-(\zeta^k)^{k'}}{1-\zeta^k}=\sum_{i=0}^{k'-1}(\zeta^k)^i\in\mathbb Z[\zeta]$$
This proves a) as $\zeta$ is an algebraic integers and hence all its powers and sums of these.
For b): This is best done using a norm argument (as mentioned in one of the linked posts). Let $G=\operatorname{Gal}(\mathbb Q(\zeta)/\mathbb Q)$. Define the norm
$$\mathbf{N}_{\mathbb Q}^{\mathbb Q(\zeta)}\colon\mathbb Q(\zeta)\to\mathbb Q,\,\alpha\mapsto\prod_{\sigma\in G}\sigma(\alpha)\, .$$
Restricted to $\mathbb Z[\zeta]$ the image will be contained in $\mathbb Z$ and $\alpha\in\mathbb Z[\zeta]$ is a unit iff $\mathbf{N}_{\mathbb Q}^{\mathbb Q(\zeta)}(\alpha)=\{\pm1\}$. So computing the norm of $1-\zeta$ in the given cases will suffices for showing that $1-\zeta$ is a unit. Note that $\sigma(\zeta)$ just ranges over the different primitive roots of unity and so
$$\mathbf{N}_{\mathbb Q}^{\mathbb Q(\zeta)}(1-\zeta)=\prod_{\sigma\in G}\sigma(\alpha)=\prod_{(k,n)=1}(1-\zeta^k)$$
Claim. $\displaystyle\prod_{(k,n)=1}(1-\zeta^k)=1$
Proof. Let $\Phi(X)=\frac{X^n-1}{X-1}=X^{n-1}+\cdots+1$ and denote by $\Phi_d(X)$ the $d$-th cyclotomic polynomial. Then
$$\Phi(X)=\prod_{\substack{d\mid n\\d>1}}\Phi_d(X)$$
Note that our polynomial is $\Phi_n(X)$. Now, $\Phi(1)=n$ and for prime $p$ also $\Phi_p(1)=p$. Moreover, $\Phi_{p^r}(1)=p$ for all $r\ge1$. To see this, consider
$$\frac{X^{p^r}-1}{X^{p^{r-1}}-1}=X^{(p-1)p^{r-1}}+\cdots+1$$
and note that this polynomial divides $X^{p^r}-1$ and is of degree $(p-1)p^{r-1}$. But $\varphi(p^r)=(p-1)p^{r-1}$ is the exact number of primitive $p^r$-th roots of unity. Hence $\Phi_{p^r}(X)=X^{(p-1)p^{r-1}}+\cdots+1$ and $\Phi_{p^r}(1)=p$.
We return to $\Phi(1)=n$ written as
$$n=\Phi(1)=\prod_{\substack{d\mid n\\d>1}}\Phi_d(1)\ .$$
Now, $n$ factors $p_1^{r_1}\cdots p_s^{r_s}$ for some distinct primes $p_1,\dots,p_s$. But these factors already occur only considering the prime power factors. Hence the remaining factors, that is $\Phi_d(1)$ for $d>1$ and $d\ne p_i^{r_i}$ have to be $\pm1$. Inductively we see that $\Phi_d(1)=1$ for all $d$ as described, and so in particular $\Phi_n(1)=1$. $\square$
(This argument can be found in Lang's Algebraic Number Theory who credits Bass for it.)
The assumption that $n$ is divisible by at least two distinct primes is used subtly: it ensures that $n$ is not a prime power (or prime) in which case the above argument would collapse as would have no factors like $d$ in the end. As shown the product evaluates to $p$ in case of primes powers.


mlr: nested resampling for feature selection

Question: I am running a benchmark experiment in which I tune a filtered learner, similar to the example given in the mlr tutorial under nested resampling and titled "Example 3: One task, two learners, feature filtering with tuning". My code is as follows:
library(survival)
library(mlr)

data(veteran)
set.seed(24601)
configureMlr(show.learner.output=TRUE, show.info=TRUE)

task_id = "MAS"
mas.task <- makeSurvTask(id = task_id, data = veteran, target = c("time", "status"))
mas.task <- createDummyFeatures(mas.task)

inner = makeResampleDesc("CV", iters=2, stratify=TRUE)  # Tuning
outer = makeResampleDesc("CV", iters=3, stratify=TRUE)  # Benchmarking

cox.lrn <- makeLearner(cl="surv.coxph", id = "coxph", predict.type="response")
cox.filt.uni.thresh.lrn = makeTuneWrapper(
  makeFilterWrapper(
    makeLearner(cl="surv.coxph", id = "cox.filt.uni.thresh", predict.type="response"),
    fw.method="univariate.model.score",
    perf.learner=cox.lrn
  ),
  resampling = inner,
  par.set = makeParamSet(makeDiscreteParam("fw.threshold", values=c(0.5, 0.6, 0.7))),
  control = makeTuneControlGrid(),
  show.info = TRUE)

learners = list( cox.filt.uni.thresh.lrn )
bmr = benchmark(learners=learners, tasks=mas.task, resamplings=outer, measures=list(cindex), show.info = TRUE)

Using this method it seems that each iteration of the outer resampling loop will use a possibly different value for fw.threshold - it will use the value that was determined best in the inner loop. My question is, is this acceptable or would it be better to tune that parameter first, using tuneParams and cross validation, and then run the benchmark using the previously tuned parameters like this:
library(survival)
library(mlr)

data(veteran)
set.seed(24601)
configureMlr(show.learner.output=TRUE, show.info=TRUE)

task_id = "MAS"
mas.task <- makeSurvTask(id = task_id, data = veteran, target = c("time", "status"))
mas.task <- createDummyFeatures(mas.task)

inner = makeResampleDesc("CV", iters=2, stratify=TRUE)  # Tuning
outer = makeResampleDesc("CV", iters=3, stratify=TRUE)  # Benchmarking

cox.lrn <- makeLearner(cl="surv.coxph", id = "coxph", predict.type="response")
cox.filt.uni.thresh.lrn =
  makeFilterWrapper(
    makeLearner(cl="surv.coxph", id = "cox.filt.uni.thresh", predict.type="response"),
    fw.method="univariate.model.score",
    perf.learner=cox.lrn
  )
params = makeParamSet(makeDiscreteParam("fw.threshold", values=c(0.5, 0.6, 0.7)))
ctrl = makeTuneControlGrid()

tuned.params = tuneParams(cox.filt.uni.thresh.lrn, mas.task, resampling = inner, par.set=params, control=ctrl, show.info = TRUE)
tuned.lrn = setHyperPars(cox.filt.uni.thresh.lrn, par.vals = tuned.params$x)

learners = list( tuned.lrn )
bmr = benchmark(learners=learners, tasks=mas.task, resamplings=outer, measures=list(cindex), show.info = TRUE)

In this case the second method gives a slightly inferior result, but I'd like to know which is the correct method.
Answer:
Using this method it seems that each iteration of the outer resampling
  loop will use a possibly different value for fw.threshold - it will
  use the value that was determined best in the inner loop. My question
  is, is this acceptable or would it be better to tune that parameter
  first, using tuneParams and cross validation, and then run the
  benchmark using the previously tuned parameters like this:

No, because in this case your model has already seen the data.
This introduces bias.
You should do all optimizations within the CV, for each fold separately.
So method #1 is correct.
In addition, instead of using Grid Search I would suggest to use Random Search or MBO.


Setting up web development envirnoment with a VM (ssh + browser testing)

Question: I am running VMware Fusion on my Mac (10.6) with an Ubuntu 9.10 (32 bit) VM for my development environment. How would I setup SSH to be able to SSH into the Ubuntu VM from the Mac? Also, when I am testing websites in browsers, how would I set it up so that I can go to the site on FF on the Mac and have it point to the site running on the Apache server on Ubuntu?
Answer: You need to set the VM networking in a "bridged" mode. That way, your VM will have it's own IP address. They you access it like you would access any other server.
Comment: @Brandon, that would depend on your network.  You could set a static address or you could set a reservation on your DHCP server.
Comment: Thank you. Will this IP address ever change?


Convert angular sass project to scss

Question: I kicked off my Angular 7 project with sass instead of scss, is there a way to convert all the files to scss from the command line? And update the references in all the .ts files?
Comment: you want to change the file extension or you want to convert the syntax?
Comment: looking for a built-in way to do it with angular-cli...change all the files, including package.json, *.ts, etc
Answer: You can convert all your files extension using the following command in window machine
forfiles /S /M *.sass /C "cmd /c rename @file @fname.scss"
If you want to change the ts references, you can use vs code search / replace.

Convert angular sass project to scss


What do classes in non leaves of Decision Tree represent?

Question: I am unable to understand what does class = setosa in depth 0 mean? In general, do nonleaf classes have any significance?
Answer: It means that the majority of the units in that node are of class setosa, so if you were to make a prediction at that point it would be that the class is setosa.