ShippingOrderProcessor not registered well?

Question: I'm trying to implement @jsacksick solution which should force displaying shipping costs on cart page (normally it doesn't exist at that step yet). I created a new module for this and it's structure is simple:
shipping_fix
  src
    ShippingOrderProcessor.php
  shipping_fix.info.yml
  shipping_fix.module
  shipping_fix.services.yml

ShippingOrderProcessor.php is exact copy of @jsacksick class:
https://gist.github.com/jsacksick/fde031197df92236ef5a916775e17a2e
info file contains:
name: Shipping fix
description: Fixes missing shipping info on cart page
type: module
core: 8.x
dependencies:

module file is empty and services file contains:
services:
  shipping_fix.shipping_order_processor:
    class: Drupal\shipping_fix\ShippingOrderProcessor
    tags:
      - { name: commerce_shipping.shipping_order_processor, priority: -300 }

But it's not working. I tried setting break points inside __construct() and process() methods of that class, but they are never reached.
Tried changing last row here to:
 - { name: commerce_order.order_processor, priority: -300 }

as explained here: https://docs.drupalcommerce.org/commerce2/developer-guide/orders/order-refresh-and-process
but then my site crashes when I try to clear the cache?
So to me it looks like that I didn't register this processor object well. Most likely problem is in services file, but I can't figure out what it is ("commerce_shipping.shipping_order_processor" is correct value?).
Tried dumping services with drush like:
drush devel:services
drush devel-container-services
drush devel-services

and even devel mode is turned on for each try I get:
Command "devel-container-services" is not defined.
or similar.
I activated the my module of course, tried clearing caches, but didn't help.
Update:
The error which I get when I change last row of services file to:
 - { name: commerce_order.order_processor, priority: -300 }

is:
Service 'shipping_fix.shipping_order_processor' for consumer 'commerce_order.order_refresh' does not implement Drupal\commerce_order\OrderProcessorInterface.
And ShippingOrderProcess.php file starts with:
<?php declare(strict_types=1);

namespace Drupal\my_module\OrderProcessor;

use Drupal\commerce_order\Entity\OrderInterface;
use Drupal\commerce_order\OrderProcessorInterface;
use Drupal\commerce_shipping\ShipmentManagerInterface;
use Drupal\commerce_shipping\ShippingOrderManagerInterface;
use Drupal\profile\Entity\Profile;

/**
 * Ensures there are shipments from the start.
 */
final class ShippingProcessor implements OrderProcessorInterface {

  /**
   * The shipping order manager.
   *
   * @var \Drupal\commerce_shipping\ShippingOrderManagerInterface
   */
  protected $shippingOrderManager;

  /**
   * The shipment manager.
   *
   * @var \Drupal\commerce_shipping\ShipmentManagerInterface
   */
  protected $shipmentManager;

  public function __construct(ShippingOrderManagerInterface $shippingOrderManager, ShipmentManagerInterface $shipmentManager) {
    $this->shippingOrderManager = $shippingOrderManager;
    $this->shipmentManager = $shipmentManager;
  }

...

Update 2:
Managed to clear the cache:
For my file structure name space has to be:
namespace Drupal\shipping_fix;

Also changed servies file and now it looks like:
services:
  shipping_fix.shipping_order_processor:
    class: Drupal\shipping_fix\ShippingProcessor
    arguments: ['@commerce_shipping.order_manager', '@commerce_shipping.shipment_manager']
    tags:
      - { name: commerce_order.order_processor, priority: -300 }

Now cache clearing works, but I still don't see shipping costs on cart page...
Comment: In **ShippingOrderProcessor.php** you probably have `namespace Drupal\my_module\OrderProcessor;` and forgot to replace the `my_module` part with `shipping_fix`.
Comment: `but then my site crashes when I try to clear the cache?` what error do you get?
Comment: "Service 'shipping_fix.shipping_order_processor' for consumer 'commerce_order.order_refresh' does not implement Drupal\commerce_order\OrderProcessorInterface." ?!?
Comment: Yes, that was the case, but do I have also to pass somehow those parameters for the constructor?
Comment: Should I add something like:
arguments: ['@commerce_shipping.order_manager', '@commerce_shipping.shipment_manager']
Answer:
In this case, you'll want to run this before the commerce_shipping.early_order_processor, set priority to 300
services:
  shipping_fix.shipping_order_processor:
    class: Drupal\shipping_fix\ShippingProcessor
    arguments: ['@commerce_shipping.order_manager', '@commerce_shipping.shipment_manager']
    tags:
      - { name: commerce_order.order_processor, priority: 300 }

Comment: I'm afraid to say it (after all this trouble) but it seems to work! Thank you so much for helping me!


How can I hide a link and reveal it onhover?

Question: What I want is to use HTML and CSS (no JavaScript) to create a link that only appears when the mouse pointer hovers over it.  Attempts to use CSS' display: none and then switch to display:block for mouse hovers haven't worked for me. That's also true for switching visibility: hidden to visibility: visible for hovering.  In both cases, the link is invisible, but hovering over where it should be doesn't make it appear.
Thus, I've resorted to simply setting the foreground color to match the background color.  Crude but effective for now, but that means I have to make sure both settings are updated if the color scheme changes.  A simple example:
HTML:

 Lorem ipsum sum blah blah blah the link

Just

some

nonsense

to

take

up

space

destination
You have reached your destination!

CSS:
.outOfSight {
    color: white;
}
.outOfSight:hover {
    color: black;
}

It's also at http://jsfiddle.net/Bc4pB/4/.
Is this the only way? Or is there some subtlety to either the display or visibility property I don't know? Is there another way?
Comment: have you tried using the z-index in css?
Answer: What about using opacity?
.outOfSight {
    opacity: 0;
    color: black;
}
.outOfSight:hover {
    opacity: 1;
}

JS Fiddle
Comment: Thanks.  I wasn't aware of the opacity property.
Answer: You can't hover over something that is not there (visibility and display can both take the element out).  I would just set opacity: 0 / opacity: 1.
Comment: The explanation is appreciated!
Answer: Without using something like jQuery, that's going to be your only answer.
Setting it to 'visibility:hidden' or 'display:none' take away the interactivity. 'display:none' just completely hides it like it's not there while 'visibility:hidden' keeps its 'mass' but hides it from sight but unfortunately takes away all of the interactivity.
Someone else suggested using opacity, which would work but it's not super browser friendly (if you're supporting the less fortunate that are still using older IEs).
Comment: Thanks for the explanation about what `display` and `visibility` do.  Fortunately, I don't have to support older IE's for this.
Answer: Here is an example in JSFiddle.
Surround the anchor in a , and then apply the hidden to the child of the span as so:

 Lorem ipsum sum blah blah blah
    the link

Just

some

nonsense

destination
You have reached your destination!

Then your CSS would be:
.outOfSight { display: inline-block; }
.outOfSight a {
    visibility: hidden;
}
.outOfSight:hover a {
    visibility: visible;
}

Comment: Thanks for the suggestion, although I've think that layering elements like this is no better than putting tables inside tables.
Comment: No problem.  I can understand not wanting to add tags without a semantic purpose, but it is definitely not as bad as stacked Tables!
Answer: I think it will work for you.
CSS
.outOfSight {
    display:inline-block;
    text-indent:-9999px;
}
.outOfSight:hover {
    text-indent:0;
}

More about text-indent property http://www.w3schools.com/cssref/pr_text_text-indent.asp
Comment: Thanks for the suggestion, although "indenting" off the screen seems like a worse kludge to me than making the foreground and background colors match.
Answer: .Out {
display:none;
color:black;
text-decoration:none;
}
.Out:hover {
display:inline:
color:red;
}

Comment: Neither of those are valid classes, and are being applied to html elements called `Out`
Comment: Mistaken, written in my iphone


Scrolling down on click

Question: When I click on my image (it is a down arrow) it scrolls down smoothly just like I want, but it seems like it doesn't scroll far enough.
My scroll goes down to 90% of my header but still shows the 10% remaining.
How is that possible?

$(document).ready(function() {
  $('.js-scrollTo').on('click', function() {
    var page = $(this).attr('href');
    var speed = 700;
    $('html, body').animate( { scrollTop: $(page).offset().top }, speed );
    return false;
  });
});

ACCEUIL

TARIF

LIVRAISON

SUIVI

CONTACT

Le service de livraison
 de lettres et colis
 ultra-rapide à Bruxelles

Nos livraisons sont effectuées
 dans les 19 communes de Bruxelles
 en moins de 24 heures

Nous utilisons uniquement
 des vélos, vélos électriques
 et scooter électriques

Livraison de lettres et colis à domicile

Sans pollution
Sans émission de CO2
 et à petit prix!

Comment: use this [link](https://css-tricks.com/snippets/jquery/smooth-scrolling/)
Answer: Your JavaScript is telling the window to scroll down to the position of the ID #down, which happens to be the arrow button.
In other words, currently clicking the arrow button will scroll the page down to the top of that arrow button.
To fix this, remove the id="down" surrounding your button link, and move it to the  element (so it becomes ).
Per your request, a more detailed explanation of what's happening:

User clicks this link: ...
JavaScript sets var page based on href of your link: var page = $(this).attr('href'), so now page = #down
JavaScript scrolls to the top of #down: $(page).offset().top
Comment: @raggz I added an explanation to my answer.
Comment: Just to understand, may I ask you which line calls for the scroll down to id #down in my JavaScript?

Scrolling down on click


Pegar valor da coluna de uma tabela HTML e passar para variável PHP

Question: Já vi que há bastante exemplo na web de como pegar o valor da coluna de uma tabela HTML, como também de passar o valor de uma variável JavaScript para o PHP. Porém, quando eu estou usando os dois juntos não está dando certo. Já fiz e refiz várias vezes o código, ele agora está desta forma:

index.php
<?php
session_start();
?>

    <meta charset="utf-8">
    <title>JS Bin</title>

";
$_SESSION['codigo'] = "Este é Código:  $variavelphp";
?>
</script>

                Código
                Nome
                Ação

            111
            Joaquim Caetano
            <button class="btn-danger">Pegar Valor do Código</button>

            222
            Maria da Silva
            <button class="btn-danger">Pegar Valor do Código</button>

Este é o código da página que vou utilizar o valor da sessão criada:

ValidaCliente.php
<?php
session_start();
$idCliente = $_SESSION['codigo'];
echo $idCliente;

Na página index.phpa mensagem de alerta está correta, porém ao chegar no ValidaCliente.php é mostrado somente o texto fixo que é adicionado à sessão e não o código. Vejam nas imagens:

Desde já grato pela ajuda!
Comment: Você vai ter que usar [ajax](http://www.w3schools.com/xml/ajax_intro.asp) mano, desse jeito não vai dar certo, porque o PHP carrega antes, só depois que o PHP finaliza a execução, que a página carrega com o JavaScript.
Comment: Completando o que o @JuniorNunes disse acima. Tenha em mente que o PHP é executado no servidor enquanto o Javascript é executado no cliente(browser)
Comment: Bem lembrado, como ainda estou aprendendo a linguagem alguns desses detalhes as vezes termino esquecendo, mas irei ver como posso fazer estes procedimentos aqui para o meu exemplo.
Answer: index.php:

    <meta charset="utf-8">
    <title>JS Bin</title>

                Código
                Nome
                Ação

            111
            Joaquim Caetano
            <button class="btn-danger">Pegar Valor do Código</button>

            222
            Maria da Silva
            <button class="btn-danger">Pegar Valor do Código</button>

CriaSession.php
<?php
if(!isset($_SESSION)){session_start();}

if (isset($_GET['codigo'])){
    $_SESSION['codigo'] = $_GET['codigo'];
}
else {
    $_SESSION['codigo'] = NULL;
}

ValidaCliente.php
<?php
if(!isset($_SESSION)){session_start();}
$idCliente = $_SESSION['codigo'];
echo $idCliente;


Forecasting model

Question: My task is 'unemployment forecasting'. I have data with monthly ammount of unemployed.
First as I do was : simple exp smoothing, holt's method, Holt-Winters method, ARMA model. All this models take only 1 series and build prediction based only on historical data.
Now I need to forecast unemployment using such data as unemployment benefits, gross domestic product, Consumer price index, etc.
example of dataset:

My scientific adviser suggest to use neural network. But I dont think that it will do good forecasts (because of small amount of features).
What methods (which based not only on 1 column, but on all predictors) can I use for forecasting?
Answer: I'd review the chapter here: https://www.otexts.org/fpp/9/1
Neural networks require extreme amounts of data and many more features than you have for them to typically outperform other time series methods.

Forecasting model


How to detect rendered new lines in text node

Question: Heyy guys.
First of all, I'm not trying to detect a \n in a text node. What I need to know is when/where a text will wrap to the other line.
My idea was to iterate over the TextNode, letter by letter, create a new TextNode compound of all letters until the current step, after that I would calculate the height of the text node, if the height of the current step is different from the previous one, then the line wrapped.
The problem is I'm having a hard time to figure out the height of the current text. This is what I have so far: http://jsfiddle.net/mfnAT/2/
You can see that the height returned by getTextNodeHeight is incorrect and I don't know what is wrong. I found this function here.
Any of you guys know how to solve this? Or a better approach for this problem?
Comment: Why did you get the text height ...??? You need to get text width only i think...
Comment: As I said "if the height of the current step is different from the previous one, then the line wrapped". Width? o.O
Comment: Are you trying to collect the position information when you detect a /n or call a function?
Comment: When I detect a new line I wanna insert something there.
Comment: Found what I wanted here: http://stackoverflow.com/questions/4671713/detecting-line-breaks-with-jquery =)
Answer: Set a coordinate somewhere in the middle of your text. call the left offset relative to this position at a given time interval measured by setTimeout. Initialize one event listener on page load that listens for the left offset to be negative ( meaning it is now to the right of this position) That event listener simply Initializes a second event listener that listens for the left offset to be positive, which would symbolize a \n. Call the two event listeners back and forth. I will be back on in a few hours if you have questions.
Comment: Yeah, I didn't understand. Any examples? =)
Comment: Yeah I am not good with explaining, I will add in some code. I just wanted to know what happens when you get an /n occurance. just in general like run a function or what?


Modelagem Ruby on Rails

Question: Pessoal tenho uma dúvida que eu não consigo enxergar qual a forma de resolver.
Eu tenho que realizar um programa de estoque em Ruby on Rails que contenham alguns equipamentos, esses os quais vão conter algumas avergiguações.
Por exemplo, vou ter computadores, impressoras,  telefones, dentre outros, cada um com sua tabela, pois contém elementos únicos cada um.
Então eu precisaria criar uma relação 1 pra N em Ruby on Rails, porque um computador pode ter N averiguações, porém uma impressora também pode conter N averiguações, o telefone, e todos os outros equipamentos.
Então a pergunta é, eu tenho que referenciar todas as tabelas na criação da averiguação, porém só preencher aquela qual eu iria usar? por exemplo:
Rails g scaffold Averiguacao descricao:string data:date computador:reference impressora:reference telefone:reference
Acho que não é assim porém não consigo entender qual seria a forma certa.
Answer: Eu não criaria uma tabela para cada tipo de equipamento, e sim uma tabela de equipamentos.
Nesse caso, equipamento tem N averiguações normalmente.
Answer: Acho que é na lógica que o Alex disse. Cada equipamento, possui várias averiguações, enquanto que várias averiguações pertence a um equipamento. Essa é uma relação um para vários (one_to_many).
Então mais ou menos seria
Rails g scaffold Equipment name:string description:string

E depois
Rails g scaffold Inquiry inquiry:text equipment:references

Feito isso, depois do rails db:migrate, basta especificar a relação entre esses dois models.
No model Equipment has_many :inquiries
No model Inquiry belongs_to :equipment
Provavelmente alguns ajustes deverão ser feitos na Views, desde que em Equipamentos será possível ver, e editar as averiguações. Se você estiver fazendo vários testes, lembre-se que é possível desfazer mudanças apenas trocando o "g" de generate para "d" de destroy.
Ex: rails d scaffold Equipment

Sei que isto parece simples, mas isso pode evitar bastante problemas. Principalmente quando estamos apenas testando.

Modelagem Ruby on Rails


Telecom provider not supporting MTU higher than 1515 for leased line

Question: We have ordered a 100 Mbps leased line and did not specify our requirement to have a minimum of 1530 MTU supported. The telco now sent us a feedback that they do not support 1530, but only 1515.
Did anyone experience something similar? And what can be the rational behind for the Telecom provider not supporting higher MTU. What kind of hardware is deciding this in the case of a leased line service?

Edit: line protocol is Ethernet; also I corrected: it is a 100 Mbps we ordered.
Hope it clarifies. Thanks for your help.
Comment: The standard MTU for ethernet is 1500.  Jumbo frames are required for larger MTUs. What line protocol are you using.  Omitting address information could get you an additions 16 bytes or so.
Comment: Why do you have a 1530 MTU requirement??? Packet fragmentation should take care of packets that are larger than 1515 (which is an odd number too).
Answer: In all likelihood, one or more segments of the leased line are tunnelled through some other technology (e.g. IP, ATM, Frame Relay). Adding up all the different networking layers tends to create this sort of problem. I've experienced this directly, and companies generally discover this "minor detail" from the telco only after signing multi-year contracts that they can't pull out of. Changing every single device in your network to support a smaller-than-standard MTU is a nightmare, and should be avoided if at all possible.
Comment: And some segments are probably tunneled inside tunnels inside tunnels, each chipping away at MTU.
Comment: I guess the lesson is if you need a MTU over 1500 make sure that is specified in the contract you sign.
Comment: @Joris Fortunately, you can resolve the problem by creating your own tunnel that splits overly-large packets for transmission across the link. So the problem is that he has one tunnel too few.


Random forest subscript out of bounds error?

Question: I am trying to create a random forest in R, using the following code:
forest <-
randomForest(Responder_7yr ~ CD4_num_log + CD8_num_log + anergy_CD8_num_log +
             anergy_CD4_num_log + part_exhaust_CD8_num_log + exhaustion_CD8_num_log +
             exhaustion_CD4_num_log + senescence_CD8_num_log +
             senescence_CD4_num_log + tcm_CD4negCD8pos_num_log +
             nTreg_CD4posCD8neg_num_log + ln_cpep + A1C + Ins,
             data=resp, na.action=na.omit, importance=TRUE)

I'm getting the following error:
Error in `[.default`(table(observed = y, predicted = out.class), levels(y),  :
  subscript out of bounds

I've confirmed all predictors are in the proper format, and the outcome is in factor format. Any help is greatly appreciated!
Answer: Check your data to see the distribution in levels of your various predictors and outcomes. You may find that some of your predictor levels or outcome levels are very highly skewed, or some outcomes or predictor levels are very rare. I got that error when I was trying to predict a very rare outcome with a heavily tuned random forest, and so some of the predictor levels were not actually in the training data. Thus a factor level appears in the test data that the training data thinks is out of bounds.


Viddler webcam recording

Question: How to perform an action after webcam recording complete and saved. Viddler webcam recording javascript API. Is there any onsave event. Please let me know with example.
Answer: Look at the Docuemntation of Viddler api there is nice documention on developer site..
Recorder JavaScript API
CONTROLLING THE RECORDER
The webcam controller can be controlled using the following JavaScript functions:
doStartRecord()

start the recording

doStopRecord()

stop recording

doDelRecord()

delete recorded footage

doSaveRecord()

save the footage

CALLBACKS
recordConnected()

when recorder swf connects to the recording service.

recordAuthorised()

when recorder swf authorises it's record token

successfully.

streamAccessDenied()

when a user denies Flash access to the camera and Microphone (by
  clicking "Deny" at the Flash prompt.)

streamAccessAllowed()

when a user allows Flash access to the camera and Microphone (by
  clicking "Allow" at the Flash prompt.)

recordStarted()

when user starts recording.

recordStopped()

when user stops recording.

recordBuffering(percent)

when the preview beings to buffer before playback

.
recordBufferFull()

when the recorded video buffer is complete and begins preview
  playback.

recordFlushed()

when the recorder flushes the record buffer. After this callback, you
  can call the doDelRecord() or doSaveRecord() functions.

recordDeleted()

when user decides to delete the footage and re-record.

recordSave()

when user decides to save video (yet before the request is sent to the
  server for actual processing).

recordDone(username, videoNum, videoKey) –

when a video is successfully registered with backend systems and
  accessible on the site, Passes along the Viddler username, video
  number and video key back.

Look at this Link
Comment: I have gone through viddler documentation but i could not understand how to use javascript api with these functions. Would you please give me a example code of viddler javascript api where these functions have been used ?

Viddler webcam recording


Spivak's Change of Variables Proof

Question: In Spivak's Calculus on Manifolds, pg. 69, he claims that, if we define $T = Dg(a)$, then $(T^{-1}\circ g)' (a) = I$, where $I$ is the identity. Using the inverse function theorem, I am getting
$(T^{-1}\circ g)' (a) = (T^{-1}\circ T')^{-1})\circ g(a) \cdot g'(a)$,
after which I get
$(T')^{-1}\circ T \circ g(a) \cdot g'(a)$.
I believe $(T')^{-1}$ is the identity, considering this $T$ is a constant matrix, but I can't make anymore progress.
Answer: $T$ is a fixed linear map. The derivative of any linear map is itself (at any point of the vector space). Go back to the definition if you're not sure about this. You should have
$$(T^{-1})'(g(a))\cdot g'(a) = T^{-1}\cdot g'(a) = (g'(a))^{-1}\cdot g'(a) = I.$$

Spivak’s Change of Variables Proof


Why is three requests being made?

Question: I have this function to check if a username exists. It should only run after the user stops typing. So every time the user types the timer is reset and only once it gets to 3 seconds should a GET request be sent to the server. It works in the sense that I can see the counter counting from 1 to 3 and then it stops counting. If I type again the counter starts again. Only if I stop long enough does the counter reach 3. Why if I look in the console are there 3 requests (for 3 letters typed more than 3) to the api instead of just one. So it's sending a request even if the timer does not reach 3. so does the counter continue counting for a given time the user entered a character, even if it restarts?
Here is my code:
Vue html:
<input
    type="text"
    name="username"
    class="border pd5"
    v-model="username"
    required
    placeholder="Start typing and it will check if the username exists"
    @input="checkusername"
/>

Javascript:
const username = ref("")

function checkusername() {
    if (username.value.length > 3) {
        let time = 0;
        let timer = setInterval(function () {
            time = time + 1;
            console.log(time);
            if (time === 3) {
                clearTimeout(timer);
                axios
                    .get("api/v1/users/check/username/"+ username.value + "/")
                    .then((response) => {
                        console.log(response.data);
                    })
                    .catch((error) => {
                        console.log(error);
                    });
            }
        }, 1000);
    }
}

How can I make it so it just sends one request if the user stops typing? I have tried other solutions but because the function is called each time the user types they do not work for me and they all call the api multiple times, that is why I created this but it seems that no matter what the function call triggers an API call even if the counter never reaches 3.
Comment: There will be as many requests as there are checkusername calls because there are multiple simultaneous intervals. In order to avoid this, `timer` should be in component scope, not checkusername function. Btw you're trying to reinvent the wheel, it seems that you need debounce here
Comment: Yeah. Use debounce or simply listen to the change event but it forces user to press enter to trigger the event.
Answer: The following snippet illustrates how you can wait for 3 seconds after the last keystroke before making a request, only if there are more than three characters. But I find 3 seconds too long a waiting time.

var timer;

function restart(input) {
  if (timer) clearTimeout(timer);
  if (input.value.length > 3)
    timer = setTimeout(function() {
      alert("Making request with " + input.value);
    }, 3000);
}
<input onkeyup="restart(this)" />

Why is three requests being made?


Movable end points Calculus of Variation.

Question: Given problem is
$J[y] =\int_{0}^{x_1}y'^2dx$ with $y(0)=0$ and $y(x_1)=-x_1-1$.
After solving Euler Lagrange equation I got  $y=Ax+B$ .
And using first boundry conditon I got $y=Ax$
We have  transversatity condition $[F+(\phi'-y')F_{y'}]=0 $ at $x=x_1$.
But solving this I am getting $A=0$ but the solution is given as $y = - 2 x \,, x_1= 1.$
Any help will be appreciated.
Answer: Here $\phi=-x-1$
So  transversatity condition will give us $A^2+[-1-A ]2A=0$
$\Longrightarrow$ $A^2-2A-2A^2=0$
$\Longrightarrow$ Either $A=0 $ or $A=-2$
But we  also have $y(x_1)=Ax_1$
$\Longrightarrow$ $-x_1-1=Ax_1$
$\Longrightarrow$ $A=-{1\over x_1}-1$
$\Longrightarrow$ $x_1=-{1\over A+1}$
$\Longrightarrow$ $x_1=1$
Therefore $y=-2x$ and $x_1=1$
I had made a mistake therefore I was getting wrong answer.


Index was out of bounds. For Loops and Arrays

Question: I'm trying to create two arrays filled with a set of strings from two tables in a database and then compare them. For example:
array1[0]="1101" and
array2[0]="0110"
If both respective characters equals 1 then perform an action. But when I run this code I receive the error: Index was outside the bounds of the array. System.IndexOutOfRangeException.
For some reason I believe the problem area is with the following two statements:
comparestringa = userintarray(x) and
comparestringb = eventintarray(x)
When i comment them out, the error doesn't show.
    myconnect = New SqlConnection("xxxx")
    Dim Table1 As New SqlCommand("SELECT * FROM Table1", myconnect)
    Dim Table2 As New SqlCommand("SELECT * FROM Table2", myconnect)

    Dim array1 As New ArrayList
    Dim array2 As New ArrayList

    Table1.Connection.Open()
    Dim r As SqlDataReader
    r = Table1.ExecuteReader(CommandBehavior.CloseConnection)
    While r.Read
        array1.Add(r(1).ToString())
        array1.Add(r(2).ToString())
        array1.Add(r(3).ToString())
        array1.Add(r(4).ToString())

    End While
    r.Close()
    myconnect.Close()

    Table2.Connection.Open()
    Dim r2 As SqlDataReader
    r2 = Table2.ExecuteReader(CommandBehavior.CloseConnection)
    While r2.Read
        array2.Add(r2(1).ToString())
        array2.Add(r2(2).ToString())
        array2.Add(r2(3).ToString())
        array2.Add(r2(4).ToString())

    End While
    r2.Close()
    myconnect.Close()

    Dim comparestringa, comparestringb As String
    Dim compare_string_counter As Int16 = 1

    comparestringa = userintarray(0)
    comparestringb = eventintarray(0)

     For x = 0 To array1.Count - 1

        If comparestringa(x) = "1" And comparestringa(x) = comparestringb(x) Then

              Label4.Text = Label4.Text + " 1 "

        Else
            compare_string_counter = compare_string_counter + 1
        End If
        comparestringa = userintarray(x)
        comparestringb = eventintarray(x)

    Next

Answer: userintarray and eventintarray are not declared (at least not in the code you posted.) Apparently they are dimensioned too small, or they are not dimensioned at all.
Comment: those arrays are actually array1 and array 2 respectively
Answer: Your
userintarray(x)

eventintarray(x)

Are not defined in your code snippet. Can you check whether you allocate enough array items on them before you use them?
Comment: those arrays are actually array1 and array 2 respectively
Answer: The code that loops through the arrays has only one index variable and uses it for both arrays.  Given the index out of bounds error, I suspect that the arrays do not contain the same number of items.  Since the index is based on array1, it's likely that array2 is smaller and thus the index is invalid.
Answer: Assuming your "select * from x" (really, fill in the column names!) returns 4 values you'll have to do:
array1.Add(r(0).ToString())
array1.Add(r(1).ToString())
array1.Add(r(2).ToString())
array1.Add(r(3).ToString())

The datareader starts at position 0 just like everything else in dotnet.


Apply styles inside useEffect

Question: I use react js library for my application and i want to apply some styles depending by a state, like:

  const chooseAnAnswer = () => {
  if (answer.length > 2) {
    document.querySelector('.selector.new').style.background = 'red';
  }
  }

The chooseAnAnswer is a function from a select component. Depending of what you select, it changes the state.
Now it works, but i want to change my code to:

const chooseAnAnswer = () => {
  useEffect(()=> {
    if (answer.length > 2) {
    document.querySelector('.selector.new').style.background = 'red';
  }
  }, [var])
  }

... to keep the state updated.
The issue is that i can't use useEffect() inside a function.

How to wrap my condition in useEffect() hook?
Answer: You should not manipulate the DOM when using React. You can use a state for the color and then rerender the component using this color:
const [color, setColor] = useState();

const chooseAnAnswer = () => {
  if (answer.length > 2) setColor('red');
}

<div style={{backgroundColor: color}} ...

Answer: useEffect is a hook that needs to be used at the top level of functional React component. see the Rules of Hooks
    function MyCoolComponent() {
      const [color, setColor] = useState();
      useEffect(() => {
        if(answerLength > 2) { setColor('red') }
      }, [answerLength]);
  ......

Comment: how to wrap my condition in useEffect?

Apply styles inside useEffect


Disable the Service Help Page and also .asmx?wsdl definitions

Question: I have created a ASMX web service. Now it shows help page with definition ,.asmx?wsdl definitions etc in the url . So i found a method to hide it here
It says "Modify the webServices section of Web.config to explicitly remove the Documentation protocol"
<webServices>
 <protocols>
   <remove name="Documentation" />
 </protocols>
</webServices>

But in my case i dont see any  tag in web.config. So where should i add this? Am i missing anythging?
EDIT:
I just added below lines in web.config  and it removed service help page with MyBlank.aspx but still .asmx?wsdl is visible from browser.
<webServices>
<wsdlHelpGenerator href="MyBlank.aspx"></wsdlHelpGenerator>
</webServices>

Then I again found that just adding   actually disables help page and .asmx?wsdl but it shows service error message which is described here.
Now I want to know does this method has got any disadvantage or problem?
Comment: Yes if it doesn't exist - add it to appropriate place
Comment: @YuriyGalanter But to where it should be added? under which tag?
Answer: As I know, we can not completely disable WSDL document. But you can use a Custom WSDL File in ASP.NET Web Services. Which VS version you are using?
Comment: I am using Visual studio 2008


Prolog delayed evaluation: LIFO or FIFO wake-up?

Question: Many Prolog systems have a freeze/2 predicate, a predicate
that should possibly have the name geler/2 since it was
even invented before Prolog-II.
Assume I have a condition on the same variable, but two
different goals, i.e.:
 ?- freeze(X, G1), freeze(X, G2), X=1.

What is the preferred wake-up strategy, is G1 first executed
or is G2 first executed? What if G1 and G2 do spawn new
freezes, which are also woken up:
 G1 :- freeze(Y, G3), Y=1.
 G2 :- freeze(Z, G4), Z=1.

Is G3 or G4 always executed in-between G1 and G2, or could it be
that G3 or G4 is executed after G1 and G2, or even any time later?
Bye
Comment: Interesting question, but a bit hairy. What could be the reason - apart some implementation specific nitpick - to break the left-to-right evaluation schema ?
Comment: @false Warren mentions already Co-routines here:
https://www.sri.com/sites/default/files/uploads/publications/pdf/656.pdf , which was 1977, Prolog II manual is from 1982.
Comment: "it was even invented before Prolog II". What are you referring to here, exactly?
Answer: It depends a little bit how freeze/2 is implemented under the hood. The two main types of attribute variable interfaces that can come into play are type 1 and type 2 with respect to wake-up. Namely:
Type 1: Post-Unify
The wake-up would happen after X is instantiated and the current goal succeeded, before the next goal is called. With this type the frozen goal would see any instantiations but the execution is not immediate and not always.
Type 2: Pre-Unify
The wake-up would happen before X is instantiated during unification. A pre-unify doesn't make any sense for freeze/2, since then the frozen goal wouldn't see any instantiation.
In the above example the goal that succeeds is X=1, and the next goal is the pseudo goal of the end of the query. The woken-up goals, read off from the attribute value of the variable, are pushed on a list so that they are available for this next goal.
Lets see whether this list is a FIFO:
SWI-Prolog:
?- freeze(X, write('ha ')), freeze(X, write('tschi ')), X=1, nl.
ha tschi
X = 1.

?- freeze(X, write('ha ')), freeze(X, write('tschi ')), (X=1; X=2), nl.
ha tschi
X = 1 ;
ha tschi
X = 2.

Jekejeke Prolog with Minlog Extension:
?- use_module(library(term/suspend)).
% 5 consults and 0 unloads in 90 ms.
Yes

?- freeze(X, write('ha ')), freeze(X, write('tschi ')), X=1, nl.
ha tschi
X = 1

?- freeze(X, write('ha ')), freeze(X, write('tschi ')), (X=1; X=2), nl.
ha tschi
X = 1 ;
ha tschi
X = 2

So the list is a FIFO. So freezing and immediately waking up,
gives left to right execution in the above two Prolog systems. From this one can also deduce what would happen if the goals do further freezing and immediate wake up by themselves.


Mostrar DIV quando clico no Botão via JQuery

Question: Tô usando o seguinte código pra mostrar a DIV quando clico no botão:
$(".button").click(function(){
  $(".div").css("display","flex");
});

Está funcionando normalmente quando clico no botão criado direto no html.
Acontece que eu quando eu crio o mesmo botão com jquery ele não funciona.
var divs = '
<button data-action="addCart" class="addCart" type="button" name="button">+</button>
';

        $(".container").append(divs);

Tanto o botão que eu estava criando direto no html quanto o que é gerado via jquery (pq são vários divs) estão exatamente iguais na inspeção do chrome, mas o segundo não muda o CSS para flex. Tô usando a mesma classe para ambos.
Comment: Nao sei ao certo, mas talvez não funcione pq ele foi criado depois que o DOM foi renderizado... não sei se resolve, mas vc pode por o script no final do documento depois de todo o conteúdo e testar pra ver se resolve
Answer: Realmente ele não vai funcionar porque o elemento foi criado depois que o DOM foi renderizado.
Mas você pode contornar isso da seguinte maneira:
$(document).on('click', '.button', function(){
    $(".div").css("display","flex");
});

O método on trabalha para elementos adicionados dinamicamente.

Complementando:
Difference between .on('click') vs .click()
Qual a diferença entre o .on("click", function() {}) e o .click(function() {})?
Comment: Funcionou perfeitamente. Obrigado!!


How do I receive and record Paypal transaction variables from POST?

Question: I have a service I want my customers to subscribe to, and I want to be able to update a field within my DB based on their subscription. Was it cancelled? Did it successfully begin/recur?  I'd like to get this information, so I can perform the update within my database accordingly.
I would like to capture the transaction variables that Paypal POSTS to a specified successful payment URL, but I have no idea how. I obviously need to create a page that does this, but I'd like to know what I need to do.
Answer: Look at the uc_paypal module included with Ubercart for a fantastic example of this. Look at uc_paypal_menu() (in uc_paypal.module) and uc_paypal_ipn() (in uc_paypal.pages.inc).


"The pdf.js library could not be found." (PDF module)

Question: I installed pdf.js with the PDF module in an effort to show pdf on the fly on my Drupal 7 site. I keep Drupal 7 constantly upgraded on Ubuntu on an instance an AWS.
I installed the module using drush which placed the module at sites/all/modules/pdf. I then copied pdf.js to: sites/all/libraries.
After installing I have created a new content type called PDF and I added a file field that is able to only include a pdf file.
I selected the display to show: "PDF: Default viewer of PDF.js". I then added a content with a PDF file in it selected and uploaded.
While trying to show it I get the message: The pdf.js library could not be found. And down the page: pdf: Please download and install pdf.js!
Can anyone help?
Where do I put the JS file?
Is there a problem with the FDF module?
Comment: How you installed it? Where this message came from? What modules are supposed to use it?.. You know what you mean and what you did. We don't; we only know what you actually wrote.
Comment: Sorry' you are absolutely right' here is everything:
I installed Drupal 7 (the latest and constantly upgraded on Ubuntu on an instance an AWS.
In an attempt to show PDF file to people that have no PDF client installed I have installed the PDF module From: https://www.drupal.org/project/pdf
I installed the module using drush  which placed the module at sites/all/modules/pdf
I thene copied  pdf.js to: " sites/all/libraries "
After installing I have created a new content type called PDF and I added a file field that is able to only include a pdf file
(I will continue an another comment down)
Comment: I selected the display to show: "PDF: Default viewer of PDF.js"
I then added a content with a PDF file in it selected and uploaded and while trying to show it I get the message: The pdf.js library could not be found.
And down the page: pdf:  Please download and install pdf.js!
Can anyone  help with this?
Thanks
Shimon Dekel
Comment: Please use [edit](http://drupal.stackexchange.com/posts/130012/edit) link.
Answer: The path will be like this /sites/all/libraries/pdf.js.
pdf.js is a FOLDER not a FILE. It is very strange to have a folder with a DOT in the name.
I have attached a screenshot on the folder hierarchy that works.
SUMMARY:
The folder in your libraries folder must be named: pdf.js, you will have to rename the top folder of anything you download to pdf.js (in this instance pdf.js is not a FILE, but the container of the library)
See screenshot for the correct file hierarchy.


In Jetty 6.1.14, how can you get a basic file/we server running alongside a Java webapp?

Question: HP Operations Orchestration 9.07 (now near EOL) runs in a Jetty 6.1.14 webapp on port 8443.
How can I get Jetty 6.1.14 to run a separate, basic web/file server on port 80?
What I have done so far in the jetty.xml config file has been unsuccessful:
<Configure id="FileServer" class="org.mortbay.jetty.Server">
    <Call name="addConnector">
      <Arg>
          <New class="org.mortbay.jetty.nio.SelectChannelConnector">
            <Set name="port">80</Set>
          </New>
      </Arg>
    </Call>

    <Set name="handler">
      <New id="Handlers" class="org.mortbay.jetty.handler.HandlerCollection">
        <Set name="handlers">
          <Array type="org.mortbay.jetty.ResourceHandler">
            <Item>
              <New id="Contexts" class="org.mortbay.jetty.handler.ResourceHandler"/>
            <Set name="directoriesListed">true</Set>
        <Set name="welcomeFiles">
          <Array type="String"><Item>index.html</Item></Array>
        </Set>
            <Set name="resourceBase">.</Set>
          </New>
            </Item>
<Item>
<New class="org.mortbay.jetty.server.handler.DefaultHandler"></New>
</Item>
          </Array>
        </Set>
      </New>
    </Set>

    <Call name="addLifeCycle">
      <Arg>
        <New class="org.mortbay.jetty.deployer.WebAppDeployer">
          <Set name="contexts"><Ref id="Contexts"/></Set>
          <Set name="webAppDir"><SystemProperty name="jetty.home" default="."/>/webapps</Set>
        </New>
      </Arg>
    </Call>
</Configure>

This has come from a combination of courses, including https://wiki.eclipse.org/Jetty/Tutorial/Embedding_Jetty#Configuring_a_File_Server_with_XML
Answer: That version of Jetty is over 6 years old, and Jetty 6 itself has been EOL for over 4 years.  We are releasing milestone versions of Jetty 9.3.x now which contain HTTP/2 support.
Referencing the Jetty 7/8 documentation will be difficult since we migrated over to the Eclipse foundation between 6 and 7 so all of the packaging changed, not to mention how the modules themselves were sliced up. Jetty 6 documentation can still be found here:
http://docs.codehaus.org/display/JETTY/Jetty+Documentation
This is the section you would want to look at:
http://docs.codehaus.org/display/JETTY/Static+Content
Basically, you need to register either a DefaultServlet to serve the static content, or wire up a ResourceHandler to do the same.  Both will require you to set up a context to serve the static content from.
Comment: I know it's very old - like I said, it's used by HP OO 9.x (which is nearing its EOL, too): and I'm trying to avoid needing to spin-up a second webserver alongside Jetty to serve on port 80 on the same server
Answer: Based on help received in a Google+ community regarding this question, it is not possible in Jetty 6.1.14.

directoriesListed option did not exist in Jetty6.


Time-Series Data and Omitted Variable Bias

Question: I understand that ,usually, time-series studies do not aim to provide a causal explanation of anything but rather aim to forecast. In which case it does make sense that most time series studies aren't concerned with omitted variable bias.
However, I've come across a time series study that seeks to explain Soviet defense expenditures over a specific time period. The authors caution against using their model for forecasting purposes. Is it fair to say that omitted variable bias would be something we are concerned with in this specific case?
Maybe the answer is obvious to most of you but just looking to verify my thoughts. Thanks!
JL
Answer: Econometric models often try to determine causality in a time series context. For example, studying the impact of tax rate changes on economic growth.
Panel data, a time series of cross-section data sets, is often employed to estimate causal effects. Difference-in-difference estimators are commonly employed here for precisely this exercise (essentially, omitted variables are differenced out).
To answer your direct question, yes, we would be concerned about omitted variables when we are trying to determine causal links. If these variables are correlated with our treatment variable, then we can get a biased estimate of the causal effect.
For prediction, we aren't looking to ascribe causal links and thus omitted variables bias may be less of a concern. Knowing that the number of people carrying umbrellas is a good predictor of whether or not it will rain in the afternoon is useful enough for me to forecast the weather, but I can't explain it.
The explain-predict difference is key if the omitted factor is changing over time. If people decide that they don't want to be exposed to the sun and start carrying umbrellas on rainy and sunny days, then my forecasting ability breaks down. Without a causal factor, I can't anticipate these model failures. This is how omitted variables bias can be important even "just" for forecasting.
Given that the model doesn't break down, I might be able to generate better predictions using non-causal factors in addition to causal ones. Whatever I can get my hands on to reduce my prediction variance.
Comment: Thank you Charlie! That really cleared things up for me!


Is it good practice to style the panel layout?

Question: I have a panel layout. I was wondering if its okay to apply additional css ids / classes to this or to style elsewhere? I am using panels everywhere and I have moved the layout into my theme.
Answer: It's perfectly acceptable to add CSS ids and classes to panel layouts.


Get location of specific SCCM device collection in Powershell

Question: I am writing a script to export the names of all computer in a device collection to a txt file. My script works as expected but I would like to preserve the folder structure in the exported file structure. For this I need to get the location of the Device Collection.
My Question:
Is there a way to get the location of a SCCM Device Collection in PowerShell?
I've stumbled across a few posts like this and this that use WMI and WQL for this, but I wasn't able to get those working in my script and I would like to do everything in PowerShell whenever possible.
<code>$collections = (Get-CMDeviceCollection | Select -ExpandProperty "Name")

$totalCollections = $collections.length

"Number of Collections: $totalCollections"

$i = 0
foreach($name in $collections){
    ForEach-Object -Process {
        $i++
        "Writing File $i of $totalCollections"
        $SanitizedName = $name -replace '/','(slash)' -replace '\\','(backslash)' -replace ':','(colon)' -replace '\*','(asterisk)' -replace '\?','(questionmark)' -replace '"','(quote)' -replace '<','(less)' -replace '>','(more)' -replace '\|','(pipe)'
        $file = New-Item -Path "C:\Temp\exporte\$SanitizedName.txt"
        Add-Content -Path $file.FullName -Value (Get-CMCollectionMember -CollectionName $name | Select -ExpandProperty "Name")
    }
}
</code>
I would like to expand this code so that the txt files are placed in the corresponding subfolder analog to the SCCM file structure. E.g rootFolder/rooms/
I was using this module until now but wasn't able to find anything that gives me back the specific location of a collection.
Thanks in advance
Comment: Might want to think about querying SQL directly, if you have a *really* huge SCCM deployment, as something to consider.
Comment: If you want to do everything from PowerShell, I understand that.  Just query SCCM's SQL Database from PowerShell as seen in this guide.  https://github.com/fredbainbridge/mms2019ConfigMgrPowershellDemos/blob/master/demo4-SQL.ps1
Comment: @FoxDeploy I have thought about this too. But I was wondering if there was a way to do it all in "normal PowerShell" since I would like to minimize the complexity of the script. But if nothing turns up I will look into this. thx
Answer: I wasn't able to find a way to do this in plain PowerShell and the SCCM Module. In the end I did it like @FoxDeploy suggested. I made a SQL query select for each collection (performance isn't an issue in my case) on our SCCM database to get the folder path. I then used this to place the export file in the appropriate place.
This is my working example with some confidential lines removed
<code>## Parameter ##
$exportLocation = [removed]
$sqlServer = [removed]
$db = [removed]

$query = "SELECT [ObjectPath] FROM [removed].[v_Collections] WHERE CollectionName ="

$SiteCode = [removed] # Site code
$ProviderMachineName = [removed] # SMS Provider machine name

# Customizations
$initParams = @{}

# Import the ConfigurationManager.psd1 module
if((Get-Module ConfigurationManager) -eq $null) {
    Import-Module [removed]\..\ConfigurationManager.psd1" @initParams
}

# Connect to the site's drive if it is not already present
if((Get-PSDrive -Name $SiteCode -PSProvider CMSite -ErrorAction SilentlyContinue) -eq $null) {
    New-PSDrive -Name $SiteCode -PSProvider CMSite -Root $ProviderMachineName @initParams
}

Set-Location "$($SiteCode):\" @initParams

# get all collections and save them to an array
$collections = (Get-CMDeviceCollection | Select -ExpandProperty "Name")

# total number of collections
$totalCollections = $collections.length

# output to console
"Number of Collections: $totalCollections"

# empty output directory
Set-Location [removed]
Remove-Item $exportLocation\* -Recurse -Force
Set-Location [removed]

# loop through all collections
$i = 0
foreach($name in $collections){
    ForEach-Object -Process {
        # print progress
        $i++
        "Writing File $i of $totalCollections"
        # remove all characters, that aren't compatible with the windows file naming scheme (/\:*?"<>|)
        $SanitizedName = $name -replace '/','(slash)' -replace '\\','(backslash)' -replace ':','(colon)' -replace '\*','(asterisk)' -replace '\?','(questionmark)' -replace '"','(quote)' -replace '<','(less)' -replace '>','(more)' -replace '\|','(pipe)'
        # get members of collection
        $collectionMembers = (Get-CMCollectionMember -CollectionName $name | Select -ExpandProperty "Name")
        # write to file
        Set-Location [removed]
        $path = (Invoke-Sqlcmd -ServerInstance $sqlServer -Database $db -Query "$query '$collection'").Item("ObjectPath")
        New-Item -ItemType Directory -Force -Path "$exportLocation$path"
        $file = New-Item -Path "$exportLocation$path\$SanitizedName.txt"
        Add-Content -Path $file.FullName -Value $collectionMembers
        Set-Location [removed]
    }
}
</code>
hope this helps someone. Thanks @FoxDeploy


angular6:Request header field Access-Control-Allow-Origin is not allowed by Access-Control-Allow-Headers in preflight response

Question: Using back end yii2 advanced framework, calling api request using POST method getting the error as: Request header field Access-Control-Allow-Origin is not allowed by Access-Control-Allow-Headers in preflight response.
const BASE_API_URL = 'http://localhost/harshini/kpa/backend/frontend/web/index.php?r=site%2Flogin';

const httpOptions = {
  headers: new HttpHeaders({ 'Content-Type': 'application/json',
  'Access-Control-Allow-Origin': '*'})
};
sendValue(message: Kpa) {
    return this.http.put(BASE_API_URL, message, httpOptions);
  }

Here am adding image please help.
Comment: Please any one help me solve this issue,i stuck in this problem from past four days.
Answer: Looks like cors issue,
Enable cors from server side.
Please refer this link Yii2 cors filters error that No 'Access-Control-Allow-Origin' header is present
Comment: i already enabled cors in server side,but still am getting same error.@AmolBJamkar
Comment: Your image shows that `Access-Control-Allow-Origin` header is not present in preflight call response, means you need to add it `Access-Control-Allow-Origin:*` or enable cors to handle that. check your options call again.


Mathematical algorithm to alter values to specific range

Question:

I have a scroll bar in a computer program that scrolls from is -1 to 1.Its initial value is 0 .I need it to scroll from 0 to 1 and the initial value to be 0.5
What is the mathematical way to multiply the numbers by something in order to have the range 0 to 1 and the center to be 0.5
Can it be done in some type of function ? Any help will be appreciated
Note : The red values are the range I want to reach in my scrolling bar
Comment: yes , I fixed it now
Answer: If the original value is $x$, add 1 and divide it by 2 ($\frac{x+1}{2}$) to get what you want.
The range will go from $\frac{-1 + 1}{2}=0$ to $\frac{1+1}{2} = 1$, and the inital value will be $\frac{0 + 1}{2} = 0.5$.


How do I write case logic using PowerBI?

Question: I have the following case logic that I use in SQL that I need to replicate in PowerBI. I have tried both DAX and Power Query but keep running into errors:
CASE
            WHEN LEN((Ltrim(Rtrim(cast([Colum1] as BIGINT ))))) < 11
                THEN CONCAT('5', RIGHT('000000000' +Ltrim(Rtrim(cast([Colum1] as bigint))), 10))
                ELSE Ltrim(Rtrim(cast([Colum1] as BIGINT)))
        END as Account_Number

Example Output:
Current
9002682982
2
Desired
59002682982
50000000002
Thanks!
Answer: Assuming that Column1 is a text column, you can create a calculated column on your table with the following expression:
Account Number =
 VAR acc = TRIM(table[Column1])
 RETURN IF( LEN(acc) < 11,
       CONCATENATE("5", RIGHT(CONCATENATE("0000000000", acc),10)),
       acc)


Drupal 7 how can I alter page content generated with module?

Question: I have one module:
function MYMODULE_menu() {
    $items = array();
    $items['mymodule'] = array(
      'title' => t('My Module'),
      'page callback' => 'MYMODULE_view',
      'access arguments' => array('access content'),
      'page arguments' => array(1),
      'type' => MENU_NORMAL_ITEM,
    );

    return $items;
}
function MYMODULE_view() {
   return array(
        '#theme' => 'my_module_theme',
        '#variable' => 'some variable'
    );
}

In the other module I want to alter this content to change the theme and add some variables. How can I do it?
Comment: I think there is no need to use 'page arguments' => array(1)
Answer: You can change the variables of the page content implementing the template_preprocess_page() function in your module or theme. As of Clive's comment, I want to update that you can preferably use hook_page_alter(), which is called earlier than preprocess function.
function YOURMODULE_preprocess_page(&$variables) {
  // Do your changes here
  // If have Devel module installed
  // You can use dpm() function to print the contents of $variables array.
  // dpm($variables)
}

or
function YOURMODULE_page_alter(&$page) {
  // Do your changes here
  // If have Devel module installed
  // You can use dpm() function to print the contents of $variables array.
  // dpm($page)
}

Additional Reference:

Render Arrays in Drupal 7 See the section "Creating Content As Render Array"

A page callback should return a render array, as should hook_block_view()'s $block['content']. This allows your module and other modules to treat the content as data for as long as possible in the page generation process.
Comment: Perfectly valid, but personally I'd prefer [`hook_page_alter()`](https://api.drupal.org/api/drupal/modules!system!system.api.php/function/hook_page_alter/7), where you still have the page content as a render array
Comment: hook_preprocess_page() contains my data rather hook_page_alter() does not
Comment: It's definitely there, you just need to find it on the nested arrays
Comment: hook_page_alter() does not always work. The render array that's returned from a custom page callback like in OP's example is NOT available in hook_page_alter(). It is only available in the hook_preprocess_page(). I followed the rendering code with XDebug and confirmed this.
Answer: You can use module_load_include($type, $module, $name = NULL) to include other module;s content.

$type: The include file's type (file extension).
$module: The module to which the include file belongs.
$name: (optional) The base file name (without the $type extension). If
  omitted, $module is used; i.e., resulting in "$module.$type" by
  default.
Answer: If you want to alter your menu link item you can use hook_menu_alter(&$items) function and change your 'page callback' with it. E.g:
function myAnotherModule_menu_alter(&$items) {
  $items['mymodule']['page callback'] = 'MYMODULE_another_view';
}

function MYMODULE_another_view() {
  return array(
    '#theme' => 'my_module_another_theme',
    '#variable' => 'some variable'
  );
}

p.s// Don't forget to flush your cache after implementing the hook
Comment: The OP is asking to alter the page content, not to change the page callback. They are not the same.
Comment: @ЕлинЙ. MYMODULE_view() is not an alterable function. You can alter 'mymodule' page callback or 'my_module_theme' with hook_theme_registry_alter. Do you have any solution to the OP's question?
Comment: The function returns a render array, thus it is alterable, and yes I have an answer.
Comment: @ЕлинЙ. Interesting solution.. I don't have much experience with template_preprocess_page() function (because I don't like to work with theme layer functions). Can you explain how you alter the theme and variables of MYMODULE_view(), please (this would be useful)? Thanks for advance.
Comment: I have added an additional reference to my answer.


Não entra na função e dá segmentation fault

Question: Olá, por favor, considere a estrutura e funções dados abaixo e os tipos definidos.
Na função main, quando entra na função par ímpar da erro de segmentation fault.
Eu não estou entendendo o por quê disto. Alguém poderia me ajudar, por favor?
    #include <stdio.h>
    #include <stdlib.h>

    typedef struct cel {
        int info;
        struct cel * prox;
    } celula;

    typedef celula * apontador;

    /*dado um apontador (lista) imprime o camp info recursivamente*/
    void imprimeRec(apontador inicio) {
        if (inicio != NULL) {
            printf("%d\n", inicio->info);
            imprimeRec(inicio->prox);
        }
    }

   /*dada uma lisata ligada, insere um no no final*/
apontador insereNoFimRec(apontador inicio, int x) {
    apontador novo;

    if (inicio == NULL) {
        novo = malloc(sizeof(celula));
        novo->info = x;
        novo->prox = NULL;
        return novo;
    }
    inicio->prox = insereNoFimRec(inicio->prox, x);

    return inicio;
}

    /*recebe um int n e retorna um apaontador para uma lista ligada*/
    apontador criaLista(int n) {
        int i = 0;
        int info;
        apontador lista = NULL;

        while (i < n) {
            printf("L[%d] = ", i);
            if (!scanf("%d", &info))
                return NULL;
            lista = insereNoFimRec(lista, info);
            i++;
        }

        return lista;
    }

    void parImpar(apontador *par, apontador *impar, apontador inicio) {
        apontador t1, t2;

        t1 = t2 = NULL;

        if ((inicio->info % 2) == 0)
            *par = t1 = inicio;
        else
            *impar = t2 = inicio;

        inicio = inicio->prox;

        while (inicio != NULL) {
            if ((inicio->info % 2) == 0) {
                t1->prox = inicio;
                t1 = t1->prox;
            }
            else {
                t2->prox = inicio;
                t2 = t2->prox;
            }
            inicio = inicio->prox;
        }
        t1 = t2 = NULL;
    }

    int main() {
        int tamanho;
        apontador lista, *par, *impar;

        par = impar = NULL;
        printf("Tamanho da lista: ");
        if (!scanf("%d", &tamanho))
            return 0;

        lista = criaLista(tamanho);
        imprimeRec(lista);

        printf("Agora, vamos separar a ultima lista em numeros pares e impares\n");

        parImpar(par, impar, lista);

        printf("Par:\n");
        imprimeRec(*par);
        printf("Impar:\n");
        imprimeRec(*impar);

        return 0;
    }

Answer: Declare par e impar como
apontador par, impar;

Passe o endereço para a função parImpar:
parImpar(&par, &impar, lista);

Na função parImpar() chame insereNoFimRec() para inserir na lista par ou na lista impar dependendo do valor do item.
Comment: Obrigado pela resposta, @josuegomes. Acontece que o exercício pede para fazer isso manipulando os ponteiros dentro da função. Acho que esqueci de mencionar esse detalhe.
Comment: Dentro da função parimpar() você vai continuar manipulando como ponteiros.


Graphml generated from tinkerpop cannot be opened by yEd Graph Editor

Question: I have saved a graph using the Tinkergraph API.
The file is here: https://pastebin.com/C81rZYa2
I was trying to open the file using yEd and I am getting the following error:
<code>    at y.H.A.K.ā(Unknown Source)
    at y.H.H.ā(Unknown Source)
    at y.H.H.ā(Unknown Source)
    at y.H.G.ā(Unknown Source)
    at y.B.A.M.Đ(Unknown Source)
    at y.B.h.č(Unknown Source)
    at y.B.h.ā(Unknown Source)
    at y.B.h.ă(Unknown Source)
    at com.yworks.A.B.Z.ă(Unknown Source)
    at com.yworks.A.B.Z.ā(Unknown Source)
    at com.yworks.A.K.P.ā(Unknown Source)
    at com.yworks.A.K.P.ā(Unknown Source)
    at com.yworks.A.K.G.ā(Unknown Source)
    at com.yworks.A.K.G.ą(Unknown Source)
    at com.yworks.A.K.P$B.Ă(Unknown Source)
    at com.yworks.A.K.P.ā(Unknown Source)
    at com.yworks.A.L.D.ā(Unknown Source)
    at com.yworks.A.L.j.actionPerformed(Unknown Source)
    at java.desktop/javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:1967)
    at java.desktop/javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2308)
    at java.desktop/javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:405)
    at java.desktop/javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:262)
    at java.desktop/javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:279)
    at com.jidesoft.plaf.basic.BasicJideButtonListener.mouseReleased(Unknown Source)
    at java.desktop/java.awt.AWTEventMulticaster.mouseReleased(AWTEventMulticaster.java:297)
    at java.desktop/java.awt.Component.processMouseEvent(Component.java:6614)
    at java.desktop/javax.swing.JComponent.processMouseEvent(JComponent.java:3342)
    at java.desktop/java.awt.Component.processEvent(Component.java:6379)
    at java.desktop/java.awt.Container.processEvent(Container.java:2263)
    at java.desktop/java.awt.Component.dispatchEventImpl(Component.java:4990)
    at java.desktop/java.awt.Container.dispatchEventImpl(Container.java:2321)
    at java.desktop/java.awt.Component.dispatchEvent(Component.java:4822)
    at java.desktop/java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4919)
    at java.desktop/java.awt.LightweightDispatcher.processMouseEvent(Container.java:4548)
    at java.desktop/java.awt.LightweightDispatcher.dispatchEvent(Container.java:4489)
    at java.desktop/java.awt.Container.dispatchEventImpl(Container.java:2307)
    at java.desktop/java.awt.Window.dispatchEventImpl(Window.java:2769)
    at java.desktop/java.awt.Component.dispatchEvent(Component.java:4822)
    at java.desktop/java.awt.EventQueue.dispatchEventImpl(EventQueue.java:772)
    at java.desktop/java.awt.EventQueue$4.run(EventQueue.java:721)
    at java.desktop/java.awt.EventQueue$4.run(EventQueue.java:715)
    at java.base/java.security.AccessController.doPrivileged(AccessController.java:391)
    at java.base/java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:85)
    at java.base/java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:95)
    at java.desktop/java.awt.EventQueue$5.run(EventQueue.java:745)
    at java.desktop/java.awt.EventQueue$5.run(EventQueue.java:743)
    at java.base/java.security.AccessController.doPrivileged(AccessController.java:391)
    at java.base/java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:85)
    at java.desktop/java.awt.EventQueue.dispatchEvent(EventQueue.java:742)
    at java.desktop/java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:203)
    at java.desktop/java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:124)
    at java.desktop/java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:113)
    at java.desktop/java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:109)
    at java.desktop/java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
    at java.desktop/java.awt.EventDispatchThread.run(EventDispatchThread.java:90)
Caused by: java.io.IOException: ParseException, did not find LETTER, EOF or ] but '<'
    at y.H.A.K.ă(Unknown Source)
    ... 55 more
</code>
Is there a version mismatch between yEd and Tinkergraph? I am using tinkerpop 2.6.0 i.e. the following dependency:
<code><dependency>
            <groupId>com.tinkerpop.blueprints</groupId>
            <artifactId>blueprints-core</artifactId>
            <version>2.6.0</version>
        </dependency>
</code>
Comment: That is a really old version of TinkerPop - are you able to test with the latest version? The one you are using is many years old. Everything was renamed starting with TinkerPop 3 also.
Answer: I think you have a version mismatch. Kelvin Lawrence suggested you are using an old version of TinkerPop. I think you may also be using an old version of yEd.
I have successfully opened your file using yEd v3.21.1 without any errors.
The nodes have the following custom properties:

reference
identifier
modifier
text
type
parentType

After installing a recent version version of yEd you probably also want to create a custom node that exposes some or all of these properties, otherwise there is nothing to distinguish the nodes.
The graph also appears to contain two loops - two nodes that link to themselves.


How SpringMVC @SessionAttributes sends session object to JSP

Question: I am learning SpringMVC framework and I have got the following example from here. Java Controller:
SessionController.java

package javabeat.net.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.SessionAttributes;

@Controller
@RequestMapping("/sessiontest")
@SessionAttributes("sessionValue")
public class SessionController {
    @RequestMapping(method = RequestMethod.GET)
    public String getForm(@RequestParam("param") String paramVal, ModelMap map){
        System.out.println("Param Value : " + paramVal);
        map.addAttribute("sessionValue", "Test Object");
        return "hello";
    }

}

JSP page:
hello.jsp

<%@ page contentType="text/html; charset=UTF-8" %>

<title>Hello World</title>

<%
    String value = (String)session.getAttribute("sessionValue");
    out.print(value);
%>

I am trying to understand the flow of the execution:
to the best of my knowledge, it assumes that in the execution flow the URL /sessiontest?param=paramVal is going to be hit first. Then paramVal is screened to the console. Then the collection map is enriched with the key-value pair "sessionValue"/"Test Object".  Then "hello" is returned . So when hello.jsp is being hit, it retrieves the just added value, and the html body screens Test Object.
If my above interpretation is correct, I would like to know:
1) who is passing ModelMap map object to the method getForm?
2) what is the purpose of returning hello to nowhere?
3) how session object in the JSP is tied with the ModelMap map where the new key-value pair is being added?
Answer: I guess I'm not really good at explaining things since my words are clumsy.
But here is the thing :

1) who is passing ModelMap map object to the method getForm?

Spring container generates this model object and (behind the scene) invokes it as the argument to the method , it's working just like JSP Implicit Objects (request, response, .etc) where JSP Container makes them available in each page and these objects can be called directly without being explicitly declared .
ModelMap is used to wrap some attributes (key & value) so that you can deliver these values to the view returned from the method. So later, you can access these values in the view via its corresponding keys.

2). what is the purpose of returning hello to nowhere?

hello is the view name (hello.jsp) forwarded from the method where you can access the previous wrapped attributes in the map

3) how session object in the JSP is tied with the ModelMap map where
  the new key-value pair is being added?

Spring's @SessionAttributes is used on a controller to designate which model attributes (think these attributes as keys &  values wrapped in the map) should be stored in a session.
In simple explanation : Since this controller is annotated with @SessionAttributes("sessionValue")  so whenever a map wrap a value mapped with a key of "sessionValue" then the value will be available in HttpSession.
So then later you access this session attribute via implicit  session object in your view.
String value = (String)session.getAttribute("sessionValue"); // gives you "Test Object"


Flex graphic editor - samples open source projects

Question: I need to create an application, the main срфддутпу will be to work with graphics. The application will contain the basic operations with geometric shapes and creating your own shapes.
When creating, I would like to rely on ready-made examples of graphic editors. To do this, I'm looking for examples of open source projects.
Does anyone know any examples of similar projects?
Thank you.
Answer: How about Degrafa ?
http://code.google.com/p/degrafa/
http://jameswhittaker.com/journal/skinning-flex-with-degrafa-and-fxg


Checkbox list in a DataGrid Cell edit template

Question: I try to check only couple checkbox in a WPF datagrid cell, base on database data.
I created the checkbox list with a list coming from my database, and the list appear when I'm in editing mode on the cell. At the moment, I can only check them all or none.
This is the XAML code from the column where I want to display the checkbox.
<DataGridTemplateColumn Header="Teacher" Width="100">
    <DataGridTemplateColumn.CellTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding TeacherName}"/>
        </DataTemplate>
    </DataGridTemplateColumn.CellTemplate>
    <DataGridTemplateColumn.CellEditingTemplate>
        <DataTemplate>
            <ItemsControl ItemsSource="{StaticResource TeacherList}">
                <ItemsControl.ItemTemplate>
                    <DataTemplate>
                        <CheckBox Content="{Binding}" IsChecked="False"/>
                    </DataTemplate>
                </ItemsControl.ItemTemplate>
            </ItemsControl>
        </DataTemplate>
    </DataGridTemplateColumn.CellEditingTemplate>
</DataGridTemplateColumn>

At the end, I want a DataGrid with classes and a column for the Teacher. I want to be able to associate multiple Teacher to the class. When I enter edit mode on a cell, I want to be able to display all my teacher's name from my Database (so I don't know them and I don't know the quantity) and only check those who are associate with the class from the row i'm on.
To associate the multiple teacher and the class, I have a table in my database with the teacher ID and the class ID.
Thank you in advance.
UPDATE
I've acheived something with your help. I've create a "Teacher" class with the name and a boolean 'IsCheck'.
In my object "Class", the field teacher take a List. I create each list for each classes and set IsCheck to appropriate Teacher.
In my XAML I set the source of the checkbox DataTemplate to this teacher list.
<DataGridTemplateColumn.CellEditingTemplate>
    <DataTemplate>
        <ItemsControl ItemsSource="{Binding TEACHERLIST}">
            <ItemsControl.ItemTemplate>
                <DataTemplate>
                    <CheckBox Content="{Binding NAME}" IsChecked="{Binding ISCHECK}"/>
                </DataTemplate>
            </ItemsControl.ItemTemplate>
        </ItemsControl>
    </DataTemplate>
</DataGridTemplateColumn.CellEditingTemplate>

Comment: Bindings to C# properties are case-sensitive. That means that `ISCHECK` and `IsCheck` are totally different. Are you able to determine which spelling you used in your C# class? Also, you can't bind a field, only a property. A property has a `get` and maybe a `set` block; a field does not. Is the code in your latest update working for you?
Answer: When you do
 <CheckBox Content="{Binding}" IsChecked="False"/>

You are not binding IsChecked to anything.
So whatever you do with that checkbox, I won't be persisted to what's bound.
You should make Teacher a class with at least two public properties. String Name and bool Checked.  Give Checked a default value of false. It should also implement inotifypropertychanged.
Change your markup to:
 <CheckBox Content="{Binding Name}" IsChecked="{Binding Checked, Mode=TwoWay"/>

Once you do that you should be able to check and uncheck each of those teachers and it will be persisted in the Teacher (instance) that checkbox is bound to.
As an aside.
This UI design seems a bit weird.
A more usual sort of a design would have a Listbox of classes. You select one and the selected class is used to drive what you see in another listbox.
That'd give you a separate list of teachers in another listbox.
Comment: Another problem is that he says "I want to be able to associate multiple Teacher to the class", and it looks like he means one class per row. However, there's only one `TeacherList` resource, so once the binding is correct, if you check Mrs. Krabapple in one row, she's checked in all of them. Each row needs to have its own `TeacherList` with its own set of Teacher instances.
Comment: Thanks for your answer, I keep trying stuff. But yeah, it's for outdoor classes, and sometime they have 2 or 3 teacher, in exemple for sea kayak class where 1 teacher can only have 6 students at a time.
Comment: Indeed, good point Ed. You'd want a list of teachers allocated and a list of all teachers and some logic. Allocating multiple teachers to a class seems a bit odd now I think about it.  Been a while since i was at school but i seem to recall just the one teacher at the blackboard.
Comment: I guess there could be a student teacher and a real teacher, or something. I had one class in high school that the art teacher and the music teacher alternated/cooperated on for some reason.


Timer com tempo de sessão ativa: Momento de expiração no cookie - momento autal

Question: Estou trabalhando com Angular e, quando guardo o token de acesso em um cookie, também guardo (em um outro cookie) seu tempo de expiração (30 minutos). Quero fazer um timer que mostra ao usuário quanto tempo ele ainda tem de sessão, porém estou tendo algumas dificuldades.
Quero que o timer funcione da seguinte maneira:
Sempre que alguém entra no componente inicial do Angular, é pego no cookie o momento em que irá expirar o token e feito um cálculo baseado no momento atual e são salvos os minutos e segundos restantes em duas variáveis do tipo number. Que irá se atualizar e diminuir automaticamente com a função setInterval().
Alguém tem alguma ideia como eu faço essa matemática? Não posso simplesmente pegar a diferença de minutos e segundos, pois digamos que no cookie esteja que a sessão expirará às 17:20, e agora são 16:51, eu terei uma diferença de 31 (usando a função Math.abs()) minutos, o que está errado.
Eu precisaria de alguma maneira para converter tudo isso para o mesmo formato, subtrair e depois reconverter para minutos e segundos novamente.
Talez resolveria se eu multiplicasse os minutos por 60 para transformar em segundos e subtrair. Mas tem-se a questão da virada do dia, em que a expiração pode ser 00:10 e o tempo atual 23:50 tornando esse método não funcional. E, assim como temos a virada do dia, temos a do mês e do ano. E nem todos os meses tem a mesma quantidade de dias para eu sair multiplicando assim.
Answer: Consegui fazer o que queria. Com a função getTime() da classe Date.
Basicamente pego ambos os tempos em milisegundos com a função e, depois de calcular a diferença, transformo a diferença
<code>console.log(`Expiração ${expirationDate.getMinutes()}:${expirationDate.getSeconds()}`)
console.log(`Agora ${new Date().getMinutes()}:${new Date().getSeconds()}`)

let difference = expirationDate.getTime() - new Date().getTime()

console.log(`Diferença ${Math.trunc((difference / 1000)  / 60)}:${Math.trunc((difference / 1000) % 60)}`)
</code>


How to nest and loop step function in R, then output into separate Excel sheets

Question: I am trying to loop the step function in R through several Excel sheets of countries (AUD, EUR and SGD). I have merged the sheets into a single dataframe and I am trying to use nest and then step to do stepwise regression for each country. However, I am unable to integrate the loop into the step function.
After looping the step function, I would like to output the coefficients data (including t-stats, p-value etc.) into separate Excel sheets labelled by each country.
Would someone be able to help? I have included my attempt at looping, the step code without loop, and the data in dput.
### Loop with error
dfraw %>% group_by(dfraw, 'Country') %>%
          nest() %>%
          mutate(both_model = map(data, ~lm(VarY ~ ., data = dfraw))) %>%
          step(both_model, direction = "both") %>%
          group_by(Country) %>%
          summary(both_model)

### Functional Step code
both_model <- lm(VarY ~ ., data = dfSGD)
both_model <- step(both_model, direction = "both")
summary(both_model)
Out <- createWorkbook()
addWorksheet(Out, "SGD")
writeData(Out, sheet = "SGD", x = both_model$coefficients)
saveWorkbook(Out, "output.xlsx")

### dput(dfraw)
structure(list(Country = c("AUD", "AUD", "AUD", "AUD", "AUD",
"AUD", "AUD", "AUD", "AUD", "AUD", "EUR", "EUR", "EUR", "EUR",
"EUR", "EUR", "EUR", "EUR", "EUR", "EUR", "SGD", "SGD", "SGD",
"SGD", "SGD", "SGD", "SGD", "SGD", "SGD", "SGD"), VarY = c(-0.0244845360824741,
-0.0624174372523117, 0.0452624163437831, 0.0530749789385003,
0.00624000000000002, -0.0295754491970107, 0.0327707684745209,
-0.0182452800253847, 0.025048480930834, 0.0425666088601608, 0.0141000829416644,
0.00154489276626668, 0.0621540695036749, 0.00905518537502115,
-0.0209109380291228, 0.0147859922178988, -0.0318677573278799,
-0.0293082203837354, -0.024208903799075, -0.0178405500836277,
-0.0188187608569775, -0.0269326121253097, 0.0527939257325898,
0.0383738835848475, -0.0163586791881248, 0.000606244316459614,
-0.0250029554320841, -0.0177659080352996, -0.00352907144923342,
0.0195835545331209), VarX1 = c(-0.000207994636117426, -0.14021214097687,
0.019987000188707, 0.0905973411305785, 0.0606271485403591, 0.0460107119360711,
0.0197995343444735, -0.0253560472301735, 0.045979341688096, 0.0432113473174549,
-0.000207994636117426, -0.14021214097687, 0.019987000188707,
0.0905973411305785, 0.0606271485403591, 0.0460107119360711, 0.0197995343444735,
-0.0253560472301735, 0.045979341688096, 0.0432113473174549, -0.000207994636117426,
-0.14021214097687, 0.019987000188707, 0.0905973411305785, 0.0606271485403591,
0.0460107119360711, 0.0197995343444735, -0.0253560472301735,
0.045979341688096, 0.0432113473174549), VarX2 = c(-0.04, 0.390000000000001,
-1.015, -0.149999999999999, 0.234999999999999, 0.0650000000000004,
0.0750000000000002, 0.22, -0.0449999999999999, 0.115, -0.115,
-0.241, -0.252, -0.102, -0.0249999999999999, -0.0840000000000001,
-0.47202, 0.28388, -0.21801, -0.2159, 0.43, 1.02, -0.919999999999999,
-0.65, 0.0700000000000003, -0.63, -0.02, 0, -0.44, -0.29), VarX3 = c(0.0199999999999996,
-0.734999999999999, 0.229, 0.220000000000001, 0.0739999999999998,
-0.0760000000000005, 0.00800000000000001, 0.151, -0.04, -0.0739999999999998,
0.146, -0.117999999999999, -0.234, -0.024, 0.266, 0.101999999999999,
0.31286, 0.25693, -0.0321999999999996, 0.236699999999999, -0.0819999999999999,
-0.778, -0.116, 1.075, -0.151, 0.073999999999999, 0.133000000000001,
0.545999999999999, 0.175000000000001, 0.346), VarX4 = c(-0.0602317110633257,
-0.0633604956143422, 0.0775846309806723, -0.0297417548946277,
-0.0720518811692337, -0.0339499828708462, -0.00436185680343282,
-0.0348429263427839, 0.0958382153499828, 0.0404280217883632,
-0.0602317110633257, -0.0633604956143422, 0.0775846309806723,
-0.0297417548946277, -0.0720518811692337, -0.0339499828708462,
-0.00436185680343282, -0.0348429263427839, 0.0958382153499828,
0.0404280217883632, -0.0602317110633257, -0.0633604956143422,
0.0775846309806723, -0.0297417548946277, -0.0720518811692337,
-0.0339499828708462, -0.00436185680343282, -0.0348429263427839,
0.0958382153499828, 0.0404280217883632)), class = c("tbl_df",
"tbl", "data.frame"), row.names = c(NA, -30L))

Answer: Just as you are wrapping the lm() in a map() call, you need to wrap
the step() part in map() too. Since step() expects the data used in lm() we need to make sure that we also pass the original data to each step() call. We can use map2() to pass the lm object and the data to the step() calls. Here is what that can look like:
library(tidyverse)

res <-
  dfraw |>
  # If you want to run one model for each country you only need to
  # `group_by()` `Country`.
  group_by(Country) |>
  nest() |>
  mutate(both_model = map(data, ~ lm(VarY ~ ., data = .x)),
         step_model = map2(data, both_model, ~step(.y, direction = "both", trace = 0)))

summary() is not that useful for programmatically evaluating model results.
You can use broom::glance() and broom::tidy() instead:
library(broom)

eval_res <-
  res |>
  mutate(quality = map(step_model, glance),
         estimates = map(step_model, tidy))

eval_res |>
  select(Country, quality) |>
  unnest(quality)
#> # A tibble: 3 × 13
#> # Groups:   Country [3]
#>   Country r.squared adj.r.squared  sigma statistic p.value    df logLik   AIC
#>   <chr>       <dbl>         <dbl>  <dbl>     <dbl>   <dbl> <dbl>  <dbl> <dbl>
#> 1 AUD         0.728         0.650 0.0230      9.35 0.0106      2   25.3 -42.6
#> 2 EUR         0.551         0.495 0.0206      9.81 0.0140      1   25.8 -45.5
#> 3 SGD         0.628         0.582 0.0180     13.5  0.00625     1   27.1 -48.2
#> # ℹ 4 more variables: BIC <dbl>, deviance <dbl>, df.residual <int>, nobs <int>

eval_res |>
  select(Country, estimates) |>
  unnest(estimates)
#> # A tibble: 7 × 6
#> # Groups:   Country [3]
#>   Country term        estimate std.error statistic p.value
#>   <chr>   <chr>          <dbl>     <dbl>     <dbl>   <dbl>
#> 1 AUD     (Intercept)  0.00355   0.00773     0.459 0.660
#> 2 AUD     VarX1        0.370     0.126       2.93  0.0219
#> 3 AUD     VarX4        0.291     0.134       2.17  0.0670
#> 4 EUR     (Intercept)  0.00831   0.00732     1.14  0.289
#> 5 EUR     VarX3       -0.116     0.0370     -3.13  0.0140
#> 6 SGD     (Intercept) -0.00519   0.00587    -0.883 0.403
#> 7 SGD     VarX2       -0.0383    0.0104     -3.68  0.00625

NOTE: There are
widely published
concerns with using stepwise model selection.
Comment: thanks @Till. However, the stepwise regression seems to be running on the full dataset, rather than the individual countries. As shown in the output of `unnest(estimates)`, the terms (Intercept, VarX1, VarX2) have the same values for all countries AUD, EUR and SGD. There is the same issue for `unnest(quality)`, same values
Comment: I updated my answer to process only the data for one country per model. Check out [this tidymodels tutorial](https://www.tidymodels.org/learn/statistics/tidy-analysis/), it has some practical examples for this.


Bijection between two orbit's spaces

Question: Take $\mathbb A_\mathbb Q$ the adele ring of $\mathbb Q$ and let
$$\vert \cdot\vert:\mathbb A_\mathbb Q\to \mathbb R_{>0}, x=(x_p)\mapsto \prod_{p\leq \infty}\vert x_p\vert_p$$ the absolute value induced by each $p$-adic absolute value.
Define $$GL_2(\mathbb A_\mathbb Q)^1=\{g\in GL_2(\mathbb A_\mathbb Q):\vert det(g)\vert=1\}.$$
Could you give me some idea to see that there exist a bijection between
$$GL_2(\mathbb Q)\setminus GL_2(\mathbb A_\mathbb Q)^1$$
and
$$GL_2(\mathbb Q)Z(GL_2(\mathbb R))\setminus GL_2(\mathbb A_\mathbb Q),$$
with $Z(GL_2(\mathbb R))$ the center of $GL_2(\mathbb R)$.
Comment: First note that you can multiply an element of GL(2,A_Q) by a scalar over R so that the norm of the determinant is 1.
Answer: I think the center $Z(\mathrm{GL}_{2}(\mathbb{R}))$ in your bijection should be replaced by its identity component $Z(\mathrm{GL}_{2}(\mathbb{R}))^{\circ}$.
Otherwise you will get the bijection:
$$\pm\mathrm{Id}_{2}\mathrm{GL}_{2}(\mathbb{Q})\backslash\mathrm{GL}_{2}(\mathbb{A}_{\mathbb{Q}})^{1}\simeq\mathrm{GL}_{2}(\mathbb{Q})Z(\mathrm{GL}_{2}(\mathbb{R}))\backslash\mathrm{GL}_{2}(\mathbb{A}_{\mathbb{Q}}),$$
where $\pm\mathrm{Id}_{2}\in\mathrm{GL}_{2}(\mathbb{R}).$
Consider the composition $\varphi$ of the embedding $\mathrm{GL}_{2}(\mathbb{A}_{\mathbb{Q}})^{1}\hookrightarrow \mathrm{GL}_{2}(\mathbb{A}_{\mathbb{Q}})$ with the quotient morphism $\mathrm{GL}_{2}(\mathbb{A_{\mathbb{Q}}})\rightarrow \mathrm{GL}_{2}(\mathbb{Q})Z(\mathrm{GL}_{2}(\mathbb{R}))^{\circ}\backslash\mathrm{GL}_{2}(\mathbb{A}_{\mathbb{Q}}).$
The kernel of $\varphi$ is $\mathrm{GL}_{2}(\mathbb{A}_{\mathbb{Q}})^{1}\cap \mathbb{GL}_{2}(\mathbb{Q})Z(\mathrm{GL}_{2}(\mathbb{R}))^{\circ}$. Notice that $\mathrm{GL}_{2}(\mathbb{Q})$ is contained in $\mathrm{GL}_{2}(\mathbb{A}_{\mathbb{Q}})^{1}$ naturally. An element $\mathrm{diag}(r,r),r>0$ in the center of $\mathrm{GL}_{2}(\mathbb{R})$ is in the kernel of $\varphi$ if and only if $r^{2}=1$, thus $\ker\varphi\cap Z(\mathrm{GL}_{2}(\mathbb{R}))^{\circ}=\mathrm{Id}_{2}$. So $\ker\varphi=\mathrm{GL}_{2}(\mathbb{Q}).$
On the other side, for any $X\in\mathrm{GL}_{2}(\mathbb{A}_{\mathbb{Q}})$ its norm $|\det X|$ is a positive number.
Take $r=\sqrt{\det X}$ and then $\mathrm{diag}(r,r)^{-1}X\in\mathrm{GL}_{2}(\mathbb{A}_{\mathbb{Q}})^{1}$, which implies that $\varphi$ is surjective and we obtain the bijection between these two quotient spaces.

Bijection between two orbit's spaces


Why do the leading eigenvectors of $A$ maximize $\text{Tr}(D^TAD)$?

Question: Given a matrix $X\in\mathbb{R}^{m\times n}$, I am trying to maximize $\text{Tr}(D^TX^TXD)$ over $D\in\mathbb{R}^{n\times l}$ ($n<l$) subject to $D^TD=I_l$, where $\text{Tr}$ denotes the trace, and $I_l$ denotes the identity matrix of size $l$.
More specifically, I am trying to find $$D^{*}=\arg\limits_{D}\max\text{Tr}(D^TX^TXD)\text{ subject to } D^TD=I_l.$$
The solution is that the matrix $D^*$ is given by the $l$ eigenvectors corresponding to the largest eigenvalues. However, I can't prove this.
I noticed that $D^TX^TXD$ is a real symmetric matrix, and thus we can decompose it to obtain $D^TX^TXD=Q\Lambda Q^T$, where $Q$ is an orthogonal matrix composed of eigenvectors of $D^TX^TXD$. I couldn't continue much from this. Any suggestions for this optimization problem?
Comment: Already the first sentence shows some confusion: your $D$ is not "given", you want to find it.
Comment: Hint: for orthogonal matrices $Q$, $\operatorname{Tr}(Q\Lambda Q^\prime)=\operatorname{Tr}(\Lambda).$
Comment: Hi @Supreeth. Did you have a chance to look at the answers? Do they help?
Comment: @amoeba Yeah, your answer was really helpful
Comment: I have fixed the first sentence, please make sure that my edit makes sense.
Answer: Let us denote $X^\top X$ by $A$. By construction, it is a $n\times n$ square symmetric positive semi-definite matrix, i.e. it has an eigenvalue decomposition $A=V\Lambda V^\top$, where $V$ is the matrix of eigenvectors (each column is an eigenvector) and $\Lambda$ is a diagonal matrix of non-negative eigenvalues $\lambda_i$ sorted in the descending order.
You want to maximize $$\operatorname{Tr}(D^\top A D),$$ where $D$ has $l$ orthonormal columns. Let us write it as $$\operatorname{Tr}(D^\top V\Lambda V^\top D)=\operatorname{Tr}(\tilde D^\top\Lambda \tilde D)=\operatorname{Tr}\big(\tilde D^\top \operatorname{diag}\{\lambda_i\}\, \tilde D\big)=\sum_{i=1}^n\lambda_i\sum_{j=1}^l\tilde D_{ij}^2.$$
This algebraic manipulation corresponds to rotating the coordinate frame such that $A$ becomes diagonal. The matrix $D$ gets transformed as $\tilde D=V^\top D$ which also has $l$ orthonormal columns. And the whole trace is reduced to a linear combination of eigenvalues $\lambda_i$.
What can we say about the coefficients $a_i=\sum_{j=1}^l\tilde D_{ij}^2$ in this linear combination? They are row sums of squares in $\tilde D$, and hence (i) they are all $\le 1$ and (ii) they sum to $l$. If so, then it is rather obvious that to maximize the sum, one should take these coefficients to be $(1,\ldots, 1, 0, \ldots, 0)$, simply selecting the top $l$ eigenvalues. Indeed, if e.g. $a_1<1$ then the sum will increase if we set $a_1=1$ and reduce the size of the last non-zero $a_i$ term accordingly.
This means that the maximum will be achieved if  $\tilde D$ is the first $l$ columns of the identity matrix. And accordingly if $D$ is the first $l$ columns of $V$, i.e. the first $l$ eigenvectors. QED.
(Of course this is a not a unique solution. $D$ can be rotated/reflected with any $l\times l$ orthogonal matrix without changing the value of the trace.)

This is very close to my answer in Why does PCA maximize total variance of the projection? This reasoning follows @whuber's comment in that thread:

[I]s it not intuitively obvious that given a collection of wallets of various amounts of cash (modeling the non-negative eigenvalues), and a fixed number $k$ that you can pick, that selecting the $k$ richest wallets will maximize your total cash? The proof that this intuition is correct is almost trivial: if you haven't taken the $k$ largest, then you can improve your sum by exchanging the smallest one you took for a larger amount.
Answer: Define $W=X^TX$, and denote by $v_i$ a unit-norm eigenvector corresponding to its $i$-th largest eigenvalue.
By the variational characterization of eigenvalues,
$$
v_1 = \underset{x,\|x\|_2=1}{\arg\max} ~ ~ x^T W x
$$
Since you are looking for an orthogonal matrix, your next vector should be in a space orthogonal to $v_2$. Define $W^{(2)}=W-v_1v_1^TW$. It just so happens that
$$
v_2 = \underset{x,\|x\|_2=1}{\arg\max} ~ ~ x^T W^{(2)} x
$$
And so on.
Why are we sure that it is indeed the eigenvectors that maximize the sum? Can't we start with a different pair of vectors and then make up for it afterwards, as whuber pointed out?
If $X=U\Sigma V^T$ is the singular value decomposition of $X$, then $X^TX=W=V\Sigma^2 V^T$ is the eigendecomposition of $W$.
Define $X_l=U_l\Sigma_l V_l^T$, where $U_l, V_l$ are $U,V$ truncated to the first $l$ columns and $\Sigma_l$ to the leading $l\times l$ block.
By the Eckart-Young-Mirsky theorem we know that
$$
\|X-X_l\|_F^2=\min_{A,rank(A)\leq l} \|X-A\|_F^2
$$
And it is easy to see that $\underset{A}{\arg\min} \|X-A\|_F^2=\underset{A}{\arg\max} \|A\|_F^2$ whenever $A$ is the result of projecting a matrix onto the span of $X$, so
$$
\|X_l\|_F^2=\max_{A,rank(A)\leq l} \|A\|_F^2
$$
Now, observe that

$X_l^TX_l=V_l\Sigma_l^2V_l^T$, that is, $V_l^TX_l^TX_lV_l=\Sigma_l^2$
$\|X_l\|_F^2=\sum_{i=1}^l\sigma_i^2$

Therefore, $\mbox{tr}(V_l^TX_l^TX_lV_l)=\mbox{tr}(\Sigma_l^2)=\sum_{i=1}^l\sigma_i^2$ is optimal.
Finally, note that $V_l^TX_l^TX_lV_l=V_l^TX^TXV_l$
Comment: This answer is unconvincing: how do we know that you can't do better by, say, *not* optimizing the value at the first step, thereby accepting a slightly suboptimal value, in return for doing much better in the second step?
Comment: @whuber Fair point. I'll try to improve it.


Para que serve a malloc?

Question: Sou novato em C++ então tenho algumas dúvidas. Uma delas que eu já vi em vários códigos por ai é a função malloc. Para que serve a malloc?
Answer: Primeiramente malloc é uma função introduzida na linguagem C, ela serve para a alocação dinâmica de memória na região conhecida como memory heap, uma região continua de espaços na memória principal que o sistema operacional disponibiliza para o seu programa utilizar.
Diferente da alocação estática e da alocação automática, em que o gerenciamento da memória alocada por variáveis é feito pelo compilador juntamente com o linker, mais especificamente  esses utilitários controlam quando a variável deve ser criada - alocada da memória, e destruída - desalocada da memória; a alocação dinâmica, feita por malloc no C, é de responsabilidade do programador, sendo esse espaço disponibilizado pelo SO, porém gerenciado pelo programador, gerenciando quando esse espaço deve ser desalocado ou mudado de estado.
No C++ o operador new, assim como em outras linguagens, é o equivalente ao malloc do C.
PS: Algumas linguagens possuem um "coletor de lixo", onde o programador não necessita se preocupar com o gerenciamento da alocação dinâmica.

Para que serve a malloc?


Version Support - RHEL 6.10

Question: My server administration team is going to migrate all the servers running on RHEL 6.x to 6.10. Could anyone let me know whether the following applications would be supported by RHEL 6.10?

SONARQube - 4.5.4 (currently running on RHEL 6.8)
Artifactory - 3.9.0 (currently running on RHEL 6.8)
Postgres - 9.4.4 (currently running on RHEL 6.8)
IBM RTC/RSA - 6.0.4 (currently running on RHEL 6.4)

Thank you in advance for the help.
Comment: If you want to know what RedHat supports, you are asking the wrong forum. If you want to know what PostgreSQL supports, the web site will tell you that 9.4 is supported. But you won't use 9.4.4, you will use 9.4.latest.
Comment: Thankx for the response. Could you please re-direct me to the correct forum for RHEL support? If you are aware of it.
Answer: You should open a service request with RedHat to get a reliable answer.

Version Support - RHEL 6.10


Hazard and density function in survival analysis with discrete time

Question: I am running a survival analysis with descrete time. For that purpose I use the R package survival with this function
surv.km <- survfit(formula = Surv(analyse$Time, analyse$Event) ~ 1, conf.type = "log",
  conf.int = 0.95, type = "kaplan-meier", error = "greenwood", data = analyse)

In the following the terms, notation and symbols from Wikipedia are used.
I can plot the survival function S(t), the event function resp. cumulative density function F(t) (fun="event"), the cumulativ hazard function H(t) (fun="cumhaz") and some other functions.
However, is there a way to calculate the density function f(t) or the hazard function h(t)? Both are actually defined for continuous time. At the moment I use the following formulas:
$f(t) = F(t+1) - F(t) = S(t) - S(t+1)$ where $t$ is discrete
$h(t) = \frac{f(t)}{S(t)} = 1 - \frac{S(t+1)}{S(t)}$ where $t$ is discrete
Does this make sense and is mathematical well founded? References to books or papers are welcome!
Answer: According to Survival Analysis (Techniques for Censored and Truncated Data
), Klein and Moeschberger pg. 30-31, 1997, the discrete time density function would be
$P(X=t)= P(t-1<X\leq t) = P(X\leq t) - P(X\leq t-1)  = F(t) - F(t-1) = (1-S(t))- (1-S(t-1)) = S(t-1)-S(t)$
S(0)=1
Likewise, the discrete hazard is defined to be
$P(X=t \mid X \geq t) = P( X=t \mid X> t-1) = \dfrac{P(X=t , X>t-1)}{P(X>t-1)} = \dfrac{P(X=t )}{S(t-1)}= \dfrac{S(t-1)-S(t)}{S(t-1)}=1-\dfrac{S(t)}{S(t-1)}$


Setting up drush ini path in my site alias

Question: Unfortunately, i use shared hosting for my dev site to show to clients.
I'd like to specify an ini path in my example.aliases.drush.php file.
I couldn't find that particular custom variable in the example file.
Is it possible to set the drush.ini path so i don't get these nagging open basedir errors?
<?php
        $aliases['dev'] = array(
        'remote-host' => 'foohost',
        'root' => '/home/xxxxxx/users/.home/domains/xxxxxx/html',
        'php' => '/usr/bin/php',
        'path-aliases' => array(
         '%drush' => '$HOME/bin/drush/',
         '%drush-ini'=>'/home/xxxxxx/etc/drush.ini',
         '%drush-script' => '$HOME/bin/drush/drush/drush.php',
         '%dump' => ' ../db/dev.xxx.sql',
        '%files' => 'sites/all/files',
        ),
    );

Comment: buddy you raised a good question - you deserve a monster congrats - sure thing!
Answer: Drush processes drush.ini in the drush bash script prior to calling drush.php.  Here is the relevant code it uses:
for conf_dir in $(dirname "$SELF_PATH") /etc/drush $HOME/.drush ; do
  if [ -f $conf_dir/php.ini ] ; then
    drush_php_ini=$conf_dir/php.ini
  fi
  if [ -f $conf_dir/drush.ini ] ; then
    drush_php_override=$conf_dir/drush.ini
  fi
done

You will need to make sure that your drush.ini file is in one of those location in order for it to be found and processed.  Note that the drush bash script never acts on command line parameters; those are parsed in php.  There are some environment variables that affect the drush bash script, but there are no environment variables that affect the selection of drush.ini, and there is no facility in site aliases to pass environment variable values to drush on the remote machine.
Sorry.
Edit: You could try setting %drush-script in your alias file to point to a script on the remote machine that called php /path/to/drush/drush.php.  Read the advice in the README.txt for Drush-4 on how to make an alias to drush.php if you do this; you will want to make sure that --php is passed to Drush correctly, etc.