Advantage of Stack-Based Allocation for Local Variables

While learning stack allocation, I came across this paragraph in the textbook (Programming Language Pragmatics – 3rd Edition):

Even in a language without recursion, it can be advantageous to use a stack for local variables, rather than allocating them statically. In most programs the pattern of potential calls among subroutines does not permit all of those subroutines to be active at the same time. As a result, the total space needed for local variables of currently active subroutines is seldom as large as the total space across all subroutines, active or not. A stack may therefore require substantially less memory at run time than would be required for static allocation.

I would appreciate if anyone could explain how stack allocation would save memory when used for allocating local variables. I tried reading this many times. But I can’t understand the author meant.

¿.toUpperCase() o .equalsIgnoreCase() en variables tipo char?

public void setGenero(char genero) {     System.out.println("Ingrese el genero");;     if (genero.equalsIgnoreCase().chatAt(0)=='H'){ //Aqui esta el error. En el equalsIgnoreCase()         this.genero=genero;     } } 

En este codigo tengo una variable de tipo char a la cual busco que solo se le pueda ingresar M (De mujer) o H (De hombre) para especificar el genero de una persona. Pero el usuario puede ingresar esas letras en mayusculas o en minusculas y quiero que el programa las ignore. Tambien lo he intentado con el .toUpperCase() pero me sale el mismo error.

He visto que el .equalsIgnoreCase() y el .toUpperCase() se usan en variables de tipo String pero tambien que funciona con los Char. Mi profesor de Programacion nos enseño eso pero no recuerdo el codigo.

solve for two variables for each n related to Collatz conjecture

For this code, for each x I would like to solve for all value ranges for c1 and c2 in a bounded range ie c1 and c2 in the range of real numbers +-100 for c1 and c2 for each x, which combined give “Length[stepsForEachN] == nRangeToCheck – 1”. Here is the code so far, I am not sure how to solve for the two variables c1 and c2 for each x:

(*stepsForEachN output is A006577={1,7,2,5,8,16,3,19} if c1=c2=1*) c1 = 1;  c2 = 1; nRangeToCheck = 10; stepsForEachNwithIndex = {}; stepsForEachN = {}; stepsForEachNIndex = {}; maxStepsToCheck = 10000;  c1ValuesForEachN = {};  For[x = 2, x <= nRangeToCheck, x++,   n = x;   For[i = 1, i <= maxStepsToCheck, i++,   If[EvenQ[n], n = Floor[(n/2)*c1],    If[OddQ[n], n = Floor[(3*n + 1)*c2]]    ];    If[n < 1.9,    AppendTo[stepsForEachN, i];    AppendTo[stepsForEachNIndex, x];    AppendTo[stepsForEachNwithIndex, {x, i}];    i = maxStepsToCheck + 1    ]   ]  ] Length[stepsForEachN] == nRangeToCheck - 1 

¿Cómo podemos mantener sólo las variables más importantes para predicciones?

Tengo un gran número de variables y me gustaría elegir sólo las que tienen más peso para predecir una variable: grade.

Sé que hay técnicas (como Lasso), pero aún no las he puesto en práctica.

    Unnamed: 0  id  member_id   loan_amnt   funded_amnt funded_amnt_inv term    int_rate    installment grade   sub_grade   emp_title   emp_length  home_ownership  annual_inc  verification_status issue_d loan_status pymnt_plan  url desc    purpose title   zip_code    addr_state  dti delinq_2yrs earliest_cr_line    inq_last_6mths  mths_since_last_delinq  mths_since_last_record  open_acc    pub_rec revol_bal   revol_util  total_acc   initial_list_status out_prncp   out_prncp_inv   total_pymnt total_pymnt_inv total_rec_prncp total_rec_int   total_rec_late_fee  recoveries  collection_recovery_fee last_pymnt_d    last_pymnt_amnt next_pymnt_d    last_credit_pull_d  collections_12_mths_ex_med  mths_since_last_major_derog policy_code application_type    annual_inc_joint    dti_joint   verification_status_joint   acc_now_delinq  tot_coll_amt    tot_cur_bal open_acc_6m open_act_il open_il_12m open_il_24m mths_since_rcnt_il  total_bal_il    il_util open_rv_12m open_rv_24m max_bal_bc  all_util    total_rev_hi_lim    inq_fi  total_cu_tl inq_last_12m    acc_open_past_24mths    avg_cur_bal bc_open_to_buy  bc_util chargeoff_within_12_mths    delinq_amnt mo_sin_old_il_acct  mo_sin_old_rev_tl_op    mo_sin_rcnt_rev_tl_op   mo_sin_rcnt_tl  mort_acc    mths_since_recent_bc    mths_since_recent_bc_dlq    mths_since_recent_inq   mths_since_recent_revol_delinq  num_accts_ever_120_pd   num_actv_bc_tl  num_actv_rev_tl num_bc_sats num_bc_tl   num_il_tl   num_op_rev_tl   num_rev_accts   num_rev_tl_bal_gt_0 num_sats    num_tl_120dpd_2m    num_tl_30dpd    num_tl_90g_dpd_24m  num_tl_op_past_12m  pct_tl_nvr_dlq  percent_bc_gt_75    pub_rec_bankruptcies    tax_liens   tot_hi_cred_lim total_bal_ex_mort   total_bc_limit  total_il_high_credit_limit  revol_bal_joint sec_app_earliest_cr_line    sec_app_inq_last_6mths  sec_app_mort_acc    sec_app_open_acc    sec_app_revol_util  sec_app_open_act_il sec_app_num_rev_accts   sec_app_chargeoff_within_12_mths    sec_app_collections_12_mths_ex_med  sec_app_mths_since_last_major_derog hardship_flag   hardship_type   hardship_reason hardship_status deferral_term   hardship_amount hardship_start_date hardship_end_date   payment_plan_start_date hardship_length hardship_dpd    hardship_loan_status    orig_projected_additional_accrued_interest  hardship_payoff_balance_amount  hardship_last_payment_amount    disbursement_method debt_settlement_flag    debt_settlement_flag_date   settlement_status   settlement_date settlement_amount   settlement_percentage   settlement_term 749995  7605    NaN NaN 15000   15000   15000.0 36 months   13.56   509.47  C   C1  Driver  4 years RENT    55000.0 Not Verified    2018-12-01  Current n   NaN NaN debt_consolidation  Debt consolidation  171xx   PA  17.15   0.0 Oct-2012    0.0 NaN NaN 9.0 0.0 7277    40.0    14.0    w   14316.22    14316.22    1001.99 1001.99 683.78  318.21  0.0 0.0 0.0 Feb-2019    509.47  Mar-2019    Feb-2019    0.0 NaN 1   Individual  NaN NaN NaN 0.0 0.0 21229.0 0.0 2.0 1.0 3.0 8.0 13952.0 85.0    1.0 1.0 4778.0  61.0    18200.0 1.0 0.0 2.0 4.0 2359.0  2457.0  69.7    0.0 0.0 74.0    54.0    12.0    8.0 0.0 35.0    NaN 8.0 NaN 0.0 2.0 5.0 2.0 2.0 4.0 7.0 10.0    5.0 9.0 0.0 0.0 0.0 2.0 100.0   50.0    0.0 0.0 34632.0 21229.0 8100.0  16432.0 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN N   NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN Cash    N   NaN NaN NaN NaN NaN NaN 749996  35399   NaN NaN 8000    8000    8000.0  36 months   6.46    245.05  A   A1  Realtor 2 years MORTGAGE    100000.0    Not Verified    2018-12-01  Current n   NaN NaN debt_consolidation  Debt consolidation  231xx   VA  9.90    1.0 Sep-2001    0.0 21.0    NaN 13.0    0.0 17646   51.7    29.0    w   7389.00 7389.00 692.18  692.18  611.00  81.18   0.0 0.0 0.0 Feb-2019    245.05  Mar-2019    Feb-2019    0.0 NaN 1   Individual  NaN NaN NaN 0.0 3323.0  326631.0    1.0 2.0 0.0 0.0 31.0    13286.0 57.0    2.0 3.0 2173.0  54.0    34100.0 0.0 3.0 0.0 3.0 27219.0 12434.0 26.0    0.0 0.0 82.0    206.0   2.0 2.0 2.0 2.0 63.0    17.0    21.0    0.0 4.0 5.0 5.0 11.0    3.0 10.0    24.0    5.0 13.0    0.0 0.0 0.0 2.0 82.8    40.0    0.0 0.0 381832.0    30932.0 16800.0 23370.0 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN N   NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN DirectPay   N   NaN NaN NaN NaN NaN NaN 

Should my game’s entities use global variables?

I have a base class called Entity and several sub classes like Player and Goblin. They all have the method update(delta), but that’s not enough to update Goblin for example, which also requires setTargetPosition(vec2) to get updated properly.

All sub classes are stored together in a single vector vector<Entity*> entities.

Solution 1 is to use some C++ version of JavaScript’s instanceof and depending on class call methods like update() and setTargetPosition().

Solution 2 is to have a source file with global variables like Goblin‘s target position and thus only update() is necessary because all the data that’s needed is in the file with global variables.

Please give me a better solution than those above. Thanks.

¿Cómo hacer un Query con Variables de Sesión en PHP?

Tengo la siguiente tabla en mysql conectada a mi sistema en PHP.

 ID  |  PIN  |  respuesta1  |   respuesta2   |  respuesta3  |   1    DD33         0                1               0   2    DD33         1                3               1   3    DD33         2                1               2   4    EE42         2                1               2 

Cómo puedo formular una consulta que cuente la cantidad de “pin” iguales usando la variable de sesión?

Mis variables de inicio de sesión es la siguiente:

 <?php     session_start();     $  sesion = $  _SESSION['username']; $  name = $  _SESSION['name']; $  cate = $  _SESSION['cate']; $  rang = $  _SESSION['rang']; $  pin = $  _SESSION['pin']; -------------------Usaré esta     if(!isset($  sesion)){         header("location: login.php");      }else{          echo "<center><h3> BIENVENIDA/O $  sesion </h3></center><br>";     }      ?> 

Una consulta similar cuenta la cantidad total de registros, pero yo quiero que cuente la cantidad de registros que existan con la variable que se inicia sesión (pin).

 $  cuenta = mysqli_query($  conectar, "SELECT * FROM   respuestas");  $  total = mysqli_num_rows($  cuenta); 

Cargar varios archivos con mismos nombres en variables

me encuentro trabajando en matlab y tengo una duda con el comando load. Estoy trabajando con una gran cantidad de variables (alrededor de 30). Las que finalmente guardo en archivos con el comando save y cuando necesito acceder uso load. Mi problema radica en que una medición tomé muy pocos datos, los cuales procese y almacene en un archivo, luego al percatarme de esto tomé más datos, los cuales nuevamente procesé, ahora mi duda radica en como abrir los archivos y acoplar las variables que poseen los mismos nombres, ya que el abrir un archivo con load, automáticamente las variables se sobreescriben sobre las anteriores. Por ejemplo, en la medición uno tengo 1000 datos para cada variables y en la siguiente 2000, ¿cómo podría acoplar los 2000 datos luegos de los primeros 1000, para obtener 3000 datos para cada variable? Antes cuando tenía este problema guardaba los datos que necesitaba en una variable con otro nombre y los iba agregando, pero al ser muchas variables no me es conveniente hacer lo mismo, ya que tengo otros códigos que funcionan en base a los nombres que tienen los archivos guardados. Agradeciendo su tiempo me despido, gracias!

Is resampling random variables to maximize value NP-hard?

Setup Let $ S = {X_1, …, X_n}$ be a set of binary random variable, i.e. $ X_i \in \{0, 1\}$ . Let $ A = \{a_0, a_1, …, a_n\}$ represent different values of outcomes of $ S$ , more specifically if for a given outcome of $ S$ , say $ \{X_1 = x_1, …, X_n = x_n\}$ , let $ j = \sum_{i=1}^nx_i$ , then we get value $ a_j$ .

Objective Given an outcome $ \{X_1 = x_1, …, X_n = x_n\}$ , with associated value $ a_j$ , suppose you can select up to $ \alpha \leq n$ number of $ X_i$ ‘s to have their outcomes re-rolled. Select the set of $ X_i$ ‘s that, in expectation, yields the greatest value of $ A$ . (For clarity, the nodes are selected all at once, then all re-rolls happen simultaneously, no node may be re-rolled more than once.)

Question Is this problem and NP optimization problem, or does their exist a polynomial time algorithm to solve it.

Work so Far So far iv worked out that if $ A$ defines a monotone sequence, then the optimal set of variables to resample can be computed in polynomial time. To see this, suppose that $ A$ is monotone increasing, then a greedy selection scheme is optimal. Namely, from all nodes that have outcome $ X_i = 0$ that have not yet been selected to be resampled, pick the $ X_i$ with the greatest $ P(X_i=1)$ . Do this until you select $ \alpha$ variables, or no such variables with outcome 0 exist. A similar scheme works when $ A$ is decreasing.

I also tried a dynamic programming approach which has not yet been fruitful.

But it is not clear to me if in the general case, there exists a polynomial time algorithm to compute the optimal solution or if the problem is NP-hard. To me, although I dont have much to back this up yet, it seems like it should be commutable in polynomial time.

Any help is greatly appreciated.

Como actualizar el valor de las variables de TimelineMax en el evento window.resize?

Estoy desarrollando una web con scroll vertical y horizontal. Me gustaría desplazarme horizontalmente cuando bajo la rueda del mouse. Lo he logrado con ScrollMagic y GSAP (TimelineMax).

Pero cuando cambio el tamaño de la ventana (window.resize), necesito actualizar las variables que contienen la cantidad de píxeles que tengo que desplazar hacia la derecha o izquierda.

Cuando se carga la web, hago una serie de cálculos para saber cuántos píxeles tengo que desplazar hacia la derecha (var amount_to_scroll):

function calculateCarruselDimensions() {     var total_width = 0;     var total_global_width = 0;     var amount_to_scroll = 0;      $  ('.carrusel').find('.carrusel_item').each(function() {         _this = $  (this);         _this.css('width', _this.find('img').width() + 'px');         console.log(_this.find('img').width());         total_width += _this.find('img').width();         //console.log( _this.attr('id') + '=' + total_width );     });      total_global_width = total_width;     $  ('.carrusel').find('.panel').css('width', total_global_width + 'px');     amount_to_scroll = total_global_width - $  (window).width();      return amount_to_scroll; }  $  (window).on("load", function() {     if ($  ('.carrusel').length) {         var controller = new ScrollMagic.Controller();         var horizontalSlide = new TimelineMax();          $  ('.carrusel').imagesLoaded(function() {              amount_to_scroll = calculateCarruselDimensions();             console.log(amount_to_scroll);              horizontalSlide.fromTo("#slideContainer", 10,             {                 x: "0"             }, {                 x: amount_to_scroll * (-1) + 'px',                 ease: Linear.easeNone,             });              scene = new ScrollMagic.Scene({                 triggerElement: "#slideWrapper",                 triggerHook: "onLeave",                 duration: amount_to_scroll + 'px' }).             setPin("#slideWrapper").             setTween(horizontalSlide).             addTo(controller);         });     } }); 

Ahora, cuando el tamaño de la ventana cambia, he hecho esto:

$  (window).bind("resize", function() {     amount_to_scroll = calculateCarruselDimensions();     //console.log(amount_to_scroll);     scene.duration(amount_to_scroll + 'px'); }); 

Actualizo la variable scene de ScrollMagic, pero también necesito actualizar la coordenada x de la variable horizontalSlide (TimelineMax.fromTo). Concretamente, esta línea de código:

x: amount_to_scroll * (-1) + 'px', 

Aquí tenéis el código funcionando en un Pen (enlace)

No tengo idea de cómo puedo lograrlo. He buscado en internet, pero no he encontrado nada 🙁

¿Alguien puede mostrarme el camino, por favor?


Is finding a minimal set of seed variables for a complete deduction of a system of equations NP-complete?

Suppose we have a set of variables $ V$ . We also have a set of equations $ E$ , which are sets of at least two variables. We don’t know anything about these equations, except if we know all but one of the variables in an equation, we can deduce the missing one.

Does there exist a set of variables $ R \subseteq V$ with $ |R| \leq k$ such that revealing these variables allows us to deduce all variables?

Is this problem NP-complete? What if all equations have degree $ \leq d$ ?

I’m ultimately interested in the search version of this problem (where we actually need to find minimal $ R$ ).