How do you pack three 4 bit signed integers (so 5 bits) into a single 16 bit integer?

Question: I want to pack 3 signed 4 bit integers (4 bits data, 1 bit sign bit) into one 16 bit integer, but I have no idea how to do it or where to start :(
I need this to represent a position in a 3D grid in as little data as possible (Since with higher grid sizes, it REALLY adds up). If it helps, I'm using GLM (OpenGL Mathematics Library, So I have access to functions such as glm::sign())
If possible, please give me the code to pack and unpack it.
Thankyou
Comment: @PepijnKramer: Bit-fields are not generally suitable for packing and unpacking bits, because the C standard does not define the order they are packed into storage units, the storage units used for them, or whether they straddle storage units or are padded. They can be used for this purpose when using a specific compiler that documents the necessary behaviors, but it is not generally portable code. Proper methods for bit-packing simply use shifts and bitwise operators.
Comment: Do you want twos-complement, sign-magnitude, or something else?
Comment: Maybe this will set you on your way : https://en.cppreference.com/w/cpp/language/bit_field... well might be tricky too : https://stackoverflow.com/questions/28091060/sizeof-pragma-packed-bitfield-struct-array
Comment: @Eric, yeah I just found out that it's implementation specific.
Comment: Bit shifting and masking. Unpacking looks like `n & 0b11111`, `(n >> 5) & 0b11111`, etc.
Comment: @NateEldredge I need to pack 3 positions into as little data as possible, since the memory footprint increases rapidly as the size of a 3D volume increases
Comment: @PepijnKramer Yes, I want to use shifts and bitwise operations, I just dont know how to do it well, I just need packing and unpacking code
Comment: duplicates: [How to pack data in binary format in c++](https://stackoverflow.com/q/8887364/995714), [Bit Manipulation to store multiple values in one int C++](https://stackoverflow.com/q/43769622/995714)
Answer: struct s {
   int16_t x : 5;
   int16_t y : 5;
   int16_t z : 5;
};
static_assert (sizeof(s) == sizeof(int16_t));

The packing and unpacking is automatic: just use it like any other struct.  E.g. given s val;, val.x=-17; packs and foo(val.z); unpacks.
This is fine for when you want to cram stuff together for use within the program itself, but not for documented interchange such as file formats, since (as comments have noted) how it packs is implementation defined.
Furthermore, the static_assert will ensure it really did what you intended, using only one word for all the fields.  All compilers I've ever heard of for conventional platforms will pack as expected.
Answer: @JDługosz 's answer is great if you're on a platform that supports that struct syntax. However, you mention OpenGL.
Here's a version that will work in a shader.
Basically, test the sign in a platform-agnostic way, set a bit for that (1 for negative, 0 for positive), add the lower four bits of the int you want to pack, then shift the result over by five bits to make room for the next value.
Since you're dealing with values from -15 to +15, you can simplify things a bit. Rather than checking the sign, just add a constant to the value to force it to be positive. (Though, I'd recommend adding an assert on the packing side to make sure that input values will actually fit within 4 bits.) When unpacking, subtract that constant.
TL;DR: Convert your input into a positive integer, grab the lower 5 bits, and mask/shift/add.
int pack3 (int a, int b, int c)
{
    a = (a + 16) & 0x1F;
    b = (b + 16) & 0x1F;
    c = (c + 16) & 0x1F;

    return (a << 10) | (b << 5) | c;
}

void unpack3 (int p, int &a, int &b, int &c)
{
  // The 3 mask & subtraction ops could be done in one step on P, but
  // I left them separate here for something resembling clarity.
  c = (p & 0x1f) - 16;
  b = ((p >> 5) & 0x1f) - 16;
  a = ((p >> 10) & 0x1f) - 16;
}

For a shader implementation, unpack3() will need to replace & references with inout or equivalent for your shader model & language.
See it working with a test driver here.
Comment: @SamuelWesley I was thinking about this some more. If you've only got 5 bits available on each axis, you *might* be better off just creating an array to hold everything. 32*32*32 = 32k; pretty small relatively speaking. Sample that in your shader rather than worrying about this sort of calculation & packing.


Matching order based on grouping variable

Question: I want to match in a certain order.
I am aware of the argument order, available in package {MatchIt} - but this refers to the propensity score.
However, I want to match in ascending order using a grouping variable named set.
Thus, matching begins within the least value of set, 1:1, without replacement.
Some IDs contribute to multiple set values. That's why the order is important if I want to match without replacement.
Data and set variable:
library(cobalt)
library(dplyr)

lalonde$set[lalonde$treat == 1] <- sample(c(5, 10, 15, 3), sum(lalonde$treat == 1), replace = TRUE)
lalonde$set[lalonde$treat == 0] <- sample(c(5, 10, 15, 3), sum(lalonde$treat == 0), replace = TRUE)
lalonde$ID <- seq_len(nrow(lalonde))
copy <- subset(lalonde, ID %in% c(1, 2, 3, 4, 5))
permute_values <- function() {
  sample(c(5, 10, 15, 3), 4, replace = FALSE)
}
copy <- copy[rep(seq_len(nrow(copy)), each = 4), ]
copy$set <- unlist(lapply(1:(nrow(copy)/4), function(x) permute_values()))
combined_data <- rbind(lalonde, copy)
unique_data <- unique(combined_data)

Creating a formula for propensity score calculation
formula <- treat ~ age + educ + married + nodegree + re74 + re75 + re78

Calculate the propensity score within variable set
data_with_ps <- unique_data %>%
  group_by(set) %>%
  mutate(pscore = glm(formula, data = .[cur_group_rows(),],
                      family = binomial(link = "logit"))$fitted.values)

Now let's carry out the matching.
This is my approach.
Argument exact = "set" does not solve the problem, because some IDs contribute to multiple values of grouping variable set and the exact argument does not include the order.
library(MatchIt)

data_with_ps_sorted <- data_with_ps[order(data_with_ps$set), ]

m.out <- matchit(formula = formula,
                 data = data_with_ps_sorted,
                 method = "nearest",
                 distance = data_with_ps_sorted$pscore,
                 ratio = 1,
                 caliper = 0.02,
                 replace = FALSE)

mdata <- match.data(m.out)

As you can see, ID 1 has been matched 3 times, whereas it may only occur once. Since it was matched in set == 3, it may not be used again in set == 10 or 15.
Thanks in advance
Answer: I think the first question you want to ask is "when a unit occurs multiple times in a single dataset, how do prevent it from being matched multiple times?" For that, you need the unit.it argument, which is documented in the help file for method_nearest. You need to supply "ID" to the unit.id argument so that once a unit with a given ID is matched, it is never used as a match again (note the documentation has a slight error; it applies to treated AND control units, not just to control units).
Now that that is taken care of, the next question is how to match in order of set. First, you need to order the dataset by set, which you did. But the next step is to set m.order = "data", which will match treated units in the order they appear in the dataset (starting from the top). If you additionally want control units to come from the same set as each treated unit, you need to set exact = ~set as well.
So, your final call to matchit() should look something like the following:
matchit(formula,
        data = data_with_ps_sorted,
        unit.id = "ID",
        m.order = "data")

Comment: Thank you very much for your comprehensive answer. I appreciate that! Assuming an `ID` with `treat == 1` also functions as a comparator if it previously had `treat == 0`(with the `treat == 0` observation). Does it make sense (because of argument `unit.id`) to extend the `ID`s which previously function as comparators with, e.g. `_1`, so that this `ID` is only excluded if it has served as a comparator?
Comment: It sounds like your matching problem is way more complex than a typical one if individual units can switch treatment statuses. `MatchIt` was not designed with this in mind. The way it is currently implemented, if any unit with a give unit ID is used as a match (either as treated or control), no units with that same unit ID can be matched (either as treated or control).
Comment: Thank you. I will give it a try using my suggestion.
Comment: It works like that


what is a `Scheduler` in RxJS

Question: I'v seen the term Scheduler very frequently in the documentation.
But, what does this term mean? I even don't know how to use a so called Scheduler. The official documentation didn't tell me what a Scheduler exactly is. Is this just a common concept or a specific concept in RxJS?
Answer: Rx schedulers provide an abstraction that allows work to be scheduled to run, possibly in the future, without the calling code needing to be aware of the mechanism used to schedule the work.
Whenever an Rx method needs to generate a notification, it schedules the work on a scheduler.  By supplying a scheduler to the Rx method instead of using the default, you can subtly control how those notifications are sent out.
In server-side implementations of Rx (such as Rx.NET), schedulers play an important role.  They allow you to schedule heavy duty work on the thread pool or dedicated threads, and run the final subscription on the UI thread so you can update your UI.
When using RxJs, it is actually pretty rare that you need to worry about the scheduler argument to most methods.  Since JavaScript is essentially single-threaded, there are not a lot of options for scheduling and the default schedulers are usually the right choice.
The only real choices are:

immediateScheduler - Runs the work synchronously and immediately.  Sort of like not using a scheduler at all.  Work scheduled thus is guaranteed to run synchronously.
currentThreadScheduler - Similar to immediateScheduler in that the work is run immediately.  However, it does not run work recursively.  So, if the work is running and schedules more work, then that additional work is put into queue to be run after the current work finishes.  Thus work sometimes runs synchronously and sometimes asynchronously.  This scheduler is useful to avoid stack overflows or infinite recursion.  For example Rx.Observable.of(42).repeat().subscribe() would cause infinite recursion if it ran on the immediate scheduler, but since return runs on the currentThread scheduler by default, infinite recursion is avoided.
timeoutScheduler - The only scheduler that supports work scheduled to be run in the future.  Essentially uses setTimeout to schedule all work (though if you schedule the work to be run "now", then it uses other faster asynchronous methods to schedule the work).  Any work scheduled on this scheduler is guaranteed to be run asynchronously.

There may be some more now, such as a scheduler that schedules work on the browser animation frames, etc.
If you are trying to write testable code, then you almost always want to supply the scheduler argument.  This is because in your unit tests, you will be creating testScheduler instances, which will let your unit test control the clock used by your Rx code (and thus control the exact timing of the operations).
Comment: @LukeTO'Brien - Web Worker schedulers would be difficult since you'd be executing "random" functions that might have closures.  Not clear how you'd serialize that action and send it to a web worker to be executed.  However, there are RxJS factory methods that let you treat web workers as Subjects that consume/produce messages.
Comment: Hi @Brandon - I've been researching Rxjs for use in my company for some time, I am surprised that Schedulers do not make use of Web Workers https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Using_web_workers (although workers are separate .js files) - But it seems to me that Web Workers would be an idea fit to Schedulers
Comment: Excellent answer. This should go in a wiki somewhere.

what is a `Scheduler` in RxJS


Understanding a characterization of minimal sufficient statistics

Question: I have some questions regarding the proof of the theorem below.
First we need a definition:

A statistic $T$ is minimal sufficient iff $T$ is a function of any other sufficient statistic.

That is, for any sufficient statistic $S$ there exists a function $H$ such that $T=H(S)$.
Also consider this:

Let $\mathcal{K}$  be the set of all pairs $(\boldsymbol{x,y})$ for which there is a $k(\boldsymbol{x,y})>0$ such that $L(\theta;\boldsymbol{x}) = k(\boldsymbol{x,y})L(\theta;\boldsymbol{y})$.

Theorem

Let $T$ be a sufficient statistic for $\mathcal{P} = \{P_{\theta}:\theta \in \Theta \} $. If for all $(\boldsymbol{x,y}) \in \mathcal{K}, T(\boldsymbol{x}) =T(\boldsymbol{y}) $, then $T$ is minimal sufficient.

The Proof
Let $S$ be an arbitrary sufficient statistic and the pair $(\boldsymbol{x,y})$ such that $S(\boldsymbol{x}) =S(\boldsymbol{y}) $. By the factorization criterion we have:
\begin{equation}L(\theta; \boldsymbol{x}) = g(S(\boldsymbol{x});\theta)h(\boldsymbol{x}) \quad and \quad L(\theta; \boldsymbol{y})=g(S(\boldsymbol{y});\theta)h(\boldsymbol{y})  \end{equation}
and therefore
\begin{equation}L(\theta;\boldsymbol{x}) = \dfrac{h(\boldsymbol{x})}{h(\boldsymbol{y})}L(\theta;\boldsymbol{y}) \end{equation}
Thus $(\boldsymbol{x,y}) \in \mathcal{K}$ and  $T(\boldsymbol{y}) = T(\boldsymbol{x})$. But this means $T$ is a function of $S$.
Question
How does one see that $T$ is a function of $S$ in the proof?
Also, why are they imposing a restriction $S(\boldsymbol{x}) = S(\boldsymbol{y})$ in the proof? what if  $S(\boldsymbol{x}) \neq S(\boldsymbol{y})$?
Answer: The symbols $\boldsymbol{x,y}$ refer to data.  Associated with each possible value $v$ of the statistic $S$ is a collection of possible data values $S^{-1}(v)$ for which $S$ has the value $v$.  Since $T$ has the same value (call it $w$) on every such dataset, we may define $H(v) = w$.
The case $S(\boldsymbol{x}) \ne S(\boldsymbol{y})$ is irrelevant to the theorem.

Let's interpret the theorem.  Say that two datasets $\boldsymbol{x,y}$ are equivalent if the relative likelihood function
$$\theta \to \frac{L(\theta,\boldsymbol{x})}{L(\theta,\boldsymbol{y})}$$
is constant.  This means that any analysis based on comparing likelihoods (for different values of $\theta$) will not make any distinction between any two equivalent datasets.  The theorem informs us that a minimal sufficient statistic will not ever distinguish between two equivalent datasets (that is, it must have the same value on each).
The proof of the theorem proceeds by noting that any two datasets having the same value of $S$ must be equivalent (provided that $S$ is sufficient) and therefore $T$ will have the same value on those datasets.
We might picture this by supposing that this equivalence relation among datasets partitions $\Omega$ into separate, overlapping components, each being a collection of equivalent datasets.  Sufficient statistics have different values on different components: this guarantees that they can discriminate among inequivalent datasets.  However, their values within any given component might vary (thereby discriminating among some equivalent datasets, too).  Any minimal sufficient statistic, though, will be constant on each component: it will not discriminate between two equivalent datasets.

The following is a formal mathematical demonstration that $T$ is a function of $S$.
Let the set of all possible such data be $\Omega$.  A statistic, such as $S$ or $T$, assigns some kind of mathematical object  to each dataset $\boldsymbol{x}\in\Omega$--such as a number or vector--that we can calculate with.  The details don't matter, so suppose $S$ assigns objects in a set $V$ and $T$ assigns objects in a set $W$.  If the function $H$ exists, then it is a map from $V$ to $W$ (depending on $S$, by the way):
$$\begin{array}{rrcll}
           \;   &&\Omega  \\
           \; &^S\swarrow & &\searrow^T  \\
           \; V & &\xrightarrow{H} &&W \\
\end{array}$$
Given $T$ and $S$ as in the question, what we know is that

For all $\boldsymbol{x,y}\in\Omega$, $S(\boldsymbol{x}) = S(\boldsymbol{y})$ implies $T(\boldsymbol{x}) = T(\boldsymbol{y})$.

From this we would like to deduce the existence of a function $H:V\to W$ such that $T = H\circ S$: that is, $T(\boldsymbol{x}) = H(S(\boldsymbol{x}))$ for all $\boldsymbol{x}\in\Omega$.
$H$ can be found with an explicit construction.  One way begins with a function $H^{*}$ defined on $V$ whose values are subsets of $W$ defined as
$$H^{*}(v) = T(S^{-1}(v)) = \{T(\boldsymbol{x})\,|\, S(\boldsymbol{x}) = v\}.$$
I claim that all elements of $H^{*}(v)$ are equal, no matter what $v\in V$ might be.  To prove the claim let $u, w\in H^{*}(v)$.  By definition, this means there are $\boldsymbol{x,y}\in\Omega$ such that $u=T(\boldsymbol{x})$ and $w=T(\boldsymbol{y})$ and $S(\boldsymbol{x}) = S(\boldsymbol{y}) = v$.  The latter equality implies $u = T(\boldsymbol{x}) = T(\boldsymbol{y}) = w$, proving the claim.
This claim enables us to define $H(v)$ whenever $H^{*}(v)$ is nonempty: it's the unique element of $H^{*}(v)$.  To complete the definition of $H$, pick an arbitrary $w_0\in W$ and set $H(v) = w_0$ when $H(v)$ is empty.  Formally,
$$H(v) = \left\{ \begin{array}{ll}
         w & \text{if } H^{*}(v) = \{w\}\\
        w_0 & \text{if } H^{*}(v) = \emptyset.
\end{array} \right. $$


Is it possible to get a slice of an array in constant time?

Question: Is it possible to get a slice of an array in constant time. if so what is the method .preferably in python .
Answer: It is possible, and I don't know why people were saying differently. You just have to write your own class to do it and be careful with mutability. Basically you need to implement the same interface as a list, but be careful how you handle slices.
You could create a class called SliceList that is iterable and stores internally a list and two offsets into that list start and end. You would overload the [] operators so that x[i] really accessess x.internal_list[x.start + i]. You would also overload the __len__ to return end - start. The big issue would be you'd have a shallow copy of the internal data structure so modification of the original list would also modify any slices of the list. But this does make some algorithms, like a binary search algorithm, a lot cleaner to code, since the data structure would handle the internal index math and you would have to pass all of that explicitly.
Slicing then returns a new SliceList object with the same internal list, but a different start and end. Slices are now O(1).
Answer: Let the array be of size n. Constructing a slice that is a fraction of n takes O(n) time. In this related post the python notation is explained. You may also take a look at the python documentation on the time complexities. So the answer is no in general, only for a constant size slice it can be constant time.
Comment: How does it answer OP question ?
Comment: @gue then is it possible to insert an element in constant time in any programming language because i have an algorithm that will sort in O(log(n!))  if it is possible either to slice or insert in constant time
Comment: Thank you for your help so far
Comment: The complexities are not dependent on the programming language. If we are speaking of an array we have a fixed size memory block that is addressed consecutively. Thus, inserting a new element always takes O(sizeof(array)) time as all elements behind have to be moved, or event the array resized. In a list this is of course no problem.
Comment: but in a list accesing any ith element will take O(i) time. i cant have that i need O(1) time indexing any element and O(1) time for insertion for the sort to work in log(n!)
Comment: i guess its not possible Thank you for your help
Comment: So if your data structure has to be sorted (and presumably should stay sorted) you want most likely a priority queue. Searching in the sorted structure is O(log n) take a look at https://en.wikipedia.org/wiki/Priority_queue
Comment: i dont think that will work too i briefly thought  it was possible to beat nlogn
Comment: the algorithm was basically applying binary search to the sorted array formed during insertion sort to find the position  where to insert the next element . assuming insertion of the element to the sorted part will be done in constant time t e runtime will be =log(1)+ log(2)..log(n)=log(n!) which would have been faster than nlogn


iPhone app testing and debugging from windows

Question: I have got the provisioning profiles and .app files to load the app into iPhone and test it. I am using windows machine so i am accessing xcode from a remote mac machine to see the full source code. After editing the code or after making some changes in the code in mac m/c, how can i build and load it in my device and test the app with the latest changes made in the code?
Answer: make a build in your remote mac using the provisioning profile and send it to yourself. Then install via iTunes. Have a look at this link:
http://www.innerfence.com/howto/install-iphone-application-ad-hoc-distribution
Comment: Hi, after building in the remote mac, how to archive the code or create an .app file and send it to my windows machine?
Comment: When you build, .app file is automatically created. What xcode version are you using?
Comment: I am using xcode version 4.0.2. Where can i find the .app file?
Comment: /Users//Library/Developer/Xcode/DerivedData/-/Build/Products/-iphoneos
Comment: yeah thanks a lot, i was able to find .app file and test it. Can you suggest me how to redirect the log messages of the running app that are written in console to DCIM folder so that when i connect my iphone to windows m/c, by default it opens only photos and videos, and after redirecting, will i be able to view logs of the app?
Comment: i dont think that is possible. Since I answered your original question please consider accepting this answer as correct


Atualizar a versão do package.json automaticamente

Question: Antes de fazer um pequeno release e marcá-lo, gostaria de atualizar o package.json para refletir a nova versão do programa.
Existe uma maneira de editar o arquivo package.json automaticamente?
Ex: atualmente a aplicação está na versão 1.0.2 e quando eu fizer uma alteração na branch X ele muda para 1.0.3 automaticamente
Comment: @RenatoC.Francisco versão da aplicação não das bibliotecas
Comment: npm update....?
Answer: Tente rodar o comando:
npm version patch


8 How do I display "Showing content between date1 and date2" on the current pager item?

Question: I am creating a list of content with a mini pager. I can't seem to find an option to print the date range of all the nodes being displayed in the current pager item. The content type has a date field. I would like to say "Showing content between date1 and date2" on each pager item based on the date field in the content type.
Clarification:
Except the date1 and date2 are the same field. This approach would not print the date range automatically based on a single date field... Let's say I have 100 node items with a NewsDate field. On each page, filter should show the the most recent to the latest date on top of each page. "Showing pages between "date range".
Answer: There is an other way for "Showing content between date1 and date2" use the Exposed filters  fields for the "Start date" and "End date" with Is between Operator. According to field created in the content type, From this You can easily filter the content according your filled date and set displayed items in pager.
Hope its helpful to you!
Comment: Except the date1 and date2 are the same field. This approach would not print the date range automatically based on a single date field... Let's say I have 100 node items with a NewsDate field. On each page, filter should show the the most recent to the latest date on top of each page. "Showing pages between "date range"...


List dynamically added DNS records

Question: I can't figure out how to list dynamically added DNS records. Lets say I add a record like this:
~$ nsupdate
> update add test.domain.com 3600 A 126.96.36.199
> send

After this I can look up the sub domain test.domain.com with:
~$ dig test.domain.com

And I get the correct info. But this entry doesn't show in the zone-file like the manually added records.
How do I know what records have been added dynamically if I can't see them anywhere?
Using Bind 9.10.3
Answer: My apologies for quoting the manual verbatim, but they are probably better writers than I am https://ftp.isc.org/www/bind/arm95/Bv9ARM.ch04.html
In short: the zone file is not the absolute thruth when allowing dynamic updates.

All changes made to a zone using dynamic update are stored in the zone's journal file. This file is automatically created by the server when the first dynamic update takes place. The name of the journal file is formed by appending the extension .jnl to the name of the corresponding zone file unless specifically overridden. The journal file is in a binary format and should not be edited manually.
The server will also occasionally write ("dump") the complete contents of the updated zone to its zone file. This is not done immediately after each dynamic update, because that would be too slow when a large zone is updated frequently. Instead, the dump is delayed by up to 15 minutes, allowing additional updates to take place.

....

The zone files of dynamic zones cannot normally be edited by hand because they are not guaranteed to contain the most recent dynamic changes — those are only in the journal file. The only way to ensure that the zone file of a dynamic zone is up to date is to run rndc stop.
If you have to make changes to a dynamic zone manually, the following procedure will work: Disable dynamic updates to the zone using rndc freeze zone. This will also remove the zone's .jnl file and update the master file. Edit the zone file. Run rndc thaw zone to reload the changed zone and re-enable dynamic updates.
Comment: Can't believe I missed that. Thank you very much for quoting that!
Answer: Bind needs to be restarted to show up in the zone-file for some reason.
A reload wasn't sufficient.

List dynamically added DNS records


Interpretation of Fixed Interaction Effects in a Linear Mixed Model

Question: I have a linear mixed model for predicting speed of a street crossing by a pedestrian with the factors VS (vehicle speed), GAP (selected time gap size for crossing), the interaction factors VSxGAP and a random intercept.
How can I interpret parameter estimates for the interaction effects?

I only have a random effect of the intercept - is it still correct to interpret the interaction effects as follows?:
a) At the reference VS of 60km/h, pedestrians reduce their speed by 80mm/s with increasing GAP by 1 GAP-unit.
b) Pedestrians reduce their speed by |-80+70|=10mm/s with increasing GAP at VS 30km/h - interaction effect 30km/h x GAP
c) Pedestrians reduce their speed by |-80+10|=70mm/s with increasing GAP at VS 50km/h - interaction effect 50km/h x GAP
And how  can I  interpret the  fixed effects  for VS categories 30km/h and 50km/h? Would it be correct to say:
d) The crossing speed level (mean) or intercept is lowered by 600mm/s for 30km/h
e) The crossing speed level (mean) or intercept is lowered by 60mm/s for 50km/h
And is it correct to imagine the plots for each VS to have different slopes due to the interaction effect!?
The fact that I have not determined any random effects, except for the intercept, confuses me a lot with the interpretation of the estimates - so I would be very thankful for responses.
Answer: Generally, the explanation of fixed effect are the same regardless having or not having random effect in the model.
a), b) and c) are correct. d) and e) need to add the condition that GAP = 0. (delete "or intercept").
You do not need to imagine, you should draw that three straight lines with different slops and intercepts. From this graph, you will understand these thing very clearly.
From your description, I cannot make the judgement that random intercepts should  be included in the model or not.


Get the submitted values of a multistep webform

Question: I need to get the submitted values of a multistep webform. It looks like webform doesn't save values from earlier steps in the usual place: $form_state['values']['submitted'] or $form_state['input']['submitted']. I just need the submitted values of every form component at the last page.
I actually made a custom submit handler to store the values from each form in my own location in $form_state, but I was wondering if there was a better way.
Answer: You will find the multi-page values stored in
$form_state['storage']['submitted']

Note that this array does not contain values from the current page and will be empty if the current page is 1.
And incidentally you can find out which page was just submitted by checking
$form_state['storage']['page_num']

Answer: My first guess would be you, if you haven't already, is to integrate the form with AJAX, so when you Click Submit to continue to the next page, it will also trigger an AJAX event, which still store the field variable information based of your custom Submit Handler function.
Here is a snippet from the Advanced Form Block Module, which provides AJAX for Node creation.
$form['#after_build'][] = 'afb_after_build';
    $rand = rand();
    $form['actions']['submit'] = FALSE;
    $form['actions']['preview'] = FALSE;
    $form['actions']['delete'] = FALSE;
    $form['changed']['#default_value'] = time() + 300;
    $form['#id'] = !empty($form['#node']->form_id) ? $form['#node']->form_id : $form['#id'];
    $form['ajax-submit'] = array(
      '#type' => 'submit',
      '#value' => t('Save Node'),
      '#weight' => 50,
      '#id' => 'ajax-submit-random-' . $rand,
      '#ajax' => array(
        'wrapper' => !empty($form['#node']->form_id) ? $form['#node']->form_id : $form['#id'],
        'callback' => 'afb_ajax_handler',
        'effect' => 'fade',
      ),
      '#submit' =>
      array(
        1 => 'node_form_submit',
      ),
    );

It calls a function to Save the fields, without refreshing the page...
/**
 * Ajax Handler that returns the forms in each individual blocks.
 */
function afb_ajax_handler($form, $form_state) {
  if (isset($form['#node']->nid)) {
    $id = $form['#id'];
    module_load_include('inc', 'node', 'node.pages');
    $node = node_load($form['#node']->nid);
    $form_state['build_info']['args'][0]->form_id = $id;
    $form = drupal_rebuild_form($node->type . '_node_form', $form_state, $form);
    $form['#id'] = $id;
    return $form;
  }
  else {
    $node = $form_state['node'];
    if (!empty($node->nid)) {
      $id = $form['#id'];
      $new_node = (object) array(
        'uid' => $node->uid,
        'name' => $node->name,
        'type' => $node->type,
        'language' => $node->language,
        'ajax_form' => 1,
        'delta' => $node->delta,
        'form_id' => $id,
      );
      $new_form_state = array();
      $new_form_state['build_info']['args'] = array($new_node);
      $new_form_state['values'] = array();
      $new_form_state['method'] = $form_state['method'];
      form_load_include($new_form_state, 'inc', 'node', 'node.pages');

      $form = drupal_rebuild_form($node->type . '_node_form', $new_form_state);
      $form['#id'] = $id;
      return $form;
    }
    else {
      return $form;
    }
  }
}

That being said, that is not a direct answer to your question, because without knowing the fields you are storing I can't really help you write a module, but this should give you a basic example of what "should" be done.
I think you might be able to get away without worrying about a wrapper, because you are storing data, but I could be wrong on this.
Answer: I doubt that this is the correct way to do it but...
I was able to pull values from the previous page using the following,
$_POST['submitted']['FIELD_ID']

where FIELD_ID is the ID of the desired form field.
This seems rather sloppy and I would like to find a better solution.
EDIT: Coleman's solution is the correct solution and should be used instead of this.


How to open the keyboard automatically on UITextField?

Question: I have a very simple table and when tocuh a cell it opens a new view with one UITextfield. All I want is that the keyboard will automatically opens, without the user have to touch the UITextfield.
Its all done in Interface Builder, so I am not sure how I do this. I guess I need to set the focus at some point ?
Thanks
Answer: To cause the keyboard to show up immediately you'll need to set the text field as the first responder using the following line:
[textField becomeFirstResponder];

You may want to place this in the viewDidAppear: method.
Comment: I recommend -viewDidAppear:, since this generates animations. Generating animations in -viewWillAppear can lead to graphic artifacts, since you're not on the screen yet. Since you almost certainly want it every time you come on screen, -viewDidLoad is likely redundant (it happens every time the view is loaded from disk, which is somewhat unpredictable, so isn't a good place for visual effects).
Comment: for swift 3 :
`override func viewDidAppear(_ animated: Bool) {
        textField.becomeFirstResponder()
    }`
Comment: Do you need to import the ```UITextViewDelegate``` delegate when doing this and then connect it to the delegate in IB?
Answer: Swift 3 & 4:
override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)
    textField.becomeFirstResponder()
}

Comment: And to avoid weird side effects, call also `super.viewDidAppear(animated)`
Answer: override func viewDidLoad() {
    super.viewDidLoad()
    textField.becomeFirstResponder()
}

Answer: Prefer adding the first responder on the main thread -
 override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)
    self.textField.becomeFirstResponder()
}

This will come in handy when the view controller view is added as a subview.
Comment: I'm pretty sure DispatchQueue.main.async is unnecessary since viewDidAppear is run on the main thread anyways
Comment: true but in many other cases, you have to remrember to do that!


Add a root element to a XML

Question: I'm quite a noob, since I don't have any previous knowledge of java programming.
Said that, I've managed to arrange some code into a working txt to xml converter.
Please take extreme consideration of the following note:
I have no clue at all about the building of the code, see it as someone who look for each piece from a different page and merge it together with, not a little, but a lot of help. Remind of that prior to report this question. Thanks
Given the following code:
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.OutputStreamWriter;

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;
import com.thoughtworks.xstream.io.xml.XmlFriendlyNameCoder;

public class xml{

static class Bean {
    int id;
    String firstname;
    String lastname;
    String mail;

    public Bean(int id, String firstname, String lastname, String mail) {
        super();
        this.id = id;
        this.firstname = firstname;
        this.lastname = lastname;
        this.mail = mail;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getFirstname() {
        return firstname;
    }

    public void setFirstname(String firstname) {
        this.firstname = firstname;
    }

    public String getLastname() {
        return lastname;
    }

    public void setLastname(String lastname) {
        this.lastname = lastname;
    }

    public String getMail() {
        return mail;
    }

    public void setMail(String mail) {
        this.mail = mail;
    }
}

private XStream xstream = new XStream();

public static void main(String[] args) throws IOException {

    new xml().process();
}

private void process() throws FileNotFoundException, IOException {

    xstream.alias("item", Bean.class);
    BufferedReader br = new BufferedReader(new FileReader("\\test.txt"));
    try {
        String line = br.readLine();
        line = br.readLine();
        while (line != null) {
            String[] split = line.split("\t");
            Bean bean = new Bean(new Integer(split[0]), split[1], split[2], split[3]);
            createBeanFile(bean);
            line = br.readLine();
        }
    } finally {
        br.close();
    }

}

private void createBeanFile(Bean bean) throws IOException {

    BufferedWriter bw = new BufferedWriter
            (new OutputStreamWriter(new FileOutputStream("\\test.xml"),"UTF-8"));
    String str = xstream.toXML(bean);
    bw.write(str);
    bw.close();
    }
}

How and where can I add a root element in order to modify my current ouput from this:
<item>
  <id>56885</id>
  <firstname>LYTF</firstname>
  <lastname>LPRT</lastname>
  <mail>email@example.com</mail>
</item>

To this:
<root>
    <item>
      <id>56885</id>
      <firstname>LYTF</firstname>
      <lastname>LPRT</lastname>
      <mail>email@example.com</mail>
    </item>
</root>

Comment: I know that adding DocumentBuilderFactory along with some Element root will do the trick, but certainly I have no clue whatsoever of where to put it or how to arrange the existing code.
Comment: You can't until you understand what this piece of _Arranged Code_ doing and how
Answer: I would urge you to study how the XStreams library works instead of copying existing (badly implemented code) and try to modify it to your needs.
What you could do is to add a root class, which holds collection of your items.
static class Root{

    List<Item> item = new ArrayList<Item>();

    public List<Item> getitem() {
        return item;
    }

    public void setBeans(List<Item> item) {
        this.item = item;
    }
}

in your process method, you then set the following properties to xStream.
xstream.alias("root", Root.class);
xstream.alias("item", Item.class); //I renamed the bean class to item here.
xstream.addImplicitCollection(Root.class, "item");

and in your while loop, you would then add the items to the root class and write out the XML after the loop.
while (line != null) {
            String[] split = line.split(",");
            Item item = new Item(new Integer(split[0]),split[1]);
            root.getitem().add(item);
            line = br.readLine();
        }

        createBeanFile(root);

Hopefully this will get your started.

Add a root element to a XML


How to detect a room,s floor from an image in android

Question: i am developing an android application and in this application i need to take the photo of a room and to get the size of this room in length and width.I also need to detect the floor of that room.I do not know where to start so provide me some guidance.
Comment: Start with basic image processing with opencv for now. Your question shows that you have a long way to ago. Check out the answer posted by me. Should help you get some push!
Answer: You cannot get the dimensions unless you have a reference measurement. For example, you can take the picture of a 30cm scale from a distance of 30cm and calculate the dimensions in terms of number of pixels. Now take the image of the room with the same 30cm scale placed somewhere (preferably, on the farthest wall). Make sure that the resolution of this image is same as that of the reference image. Now, take the number of pixels occupied by the 30cm scale in the reference picture and compare it with the number of pixels occupied by the same scale in the current picture. That will give you the scaling factor, which you can use to calculate the distance of the camera from the wall. Now, put some more formulae and you can easily get the dimensions of the whole wall.


Solve $\int\ 3x\cos(2x)dx$ with integration by parts

Question: I have this problem here that is asking for me to use Integration by Parts.
I solved it out but it seems as if it can be an ongoing function. I was told you can work with it if the second time you integrate by parts it will be similar to the original integral but I don't see how to get it.

My answer after doing integration by parts twice was:
$$\int\ 3x\cos(2x)dx=\frac{3x}{2}\sin(2x)+\frac{3}{4}\cos(2x)-\int\frac{-1}{2}\cos(2x)dx$$
Any help on figuring out what to do from here would be very grateful thank you.
Comment: Simply integrate $\int -1/2\cos(2x)dx=-1/4\sin(2x)$ But i think you only have to do integration by parts one time.
Answer: Only one application is necessary; letting $u = 3x$ and $dv = \cos 2x dx$, so that $du = 3 dx$ and $v = \frac 1 2 \sin 2x$, we find that
$$\int 3x \cos(2x) dx = \frac{3x}{2} \sin 2x - \frac 3 2 \int \sin 2x dx$$
Now can you find the antiderivative of $\sin 2x$?
Comment: I forgot to take the 3/2 out of the second integral... Silly mistake. Got it! Thanks!
Answer: Based on what you obtained,
$$-\int\frac{-1}{2}cos(2x)dx=\int\frac{1}{2}cos(2x)dx=\int\frac{1}{4}cos(2x)d(2x)=\frac{1}{4}\sin(2x)+C$$


XGBoost (Extreme Gradient Boosting) or Elastic Net More Robust to Outliers

Question: I have recently been doing work with predictive models for a continuous response. I am doing a comparison between Elastic Net (glmnet) package in R and XGBoost (xgboost) package in R. Originally, I built the model using Elastic Net for its ability to perform feature selection and also for its ability to shrink the coefficeints of correlated variables.
I am exploring XGBoost because of its predictive capabilities, the summary of feature importance it provides, its ability to capture non-linear interactions and also because I believe that it might be more robust in the presence of outliers.
My questions are:

Is XGBoost or gradient boosted trees in general better at finding non-linear interactions than a generalized linear model?
Is my assumption about XGBoost or gradient boosted trees in general being robust to outliers a fair assumption?

Here is my model set up and finding:
For model validation I have a training and testing set. I $log$ transform the response variables before model fitting. I make predictions on the testing set and then exponentiate the results to return to the original scale. I make predicted vs. observed plots for each model.
XGBoost Predicted Vs. Observed Plot

The exponentiated predicted values have some outliers but the fit in general is good.
Elastic Net Predicted Vs. Observed Plot

With the elastic net model when I convert back to original scale there is an extreme predicted value. I am interpreting this as that the GLM NET has a few cases that it is not quite sure how to predict (outliers).
I would love to hear opinions! Thank you in advance for any help or comments!
Answer:
1 Yes boosted trees would more easily fit unknown non-linear effects or interactions than regularized linear regression. However, as soon as you are aware of some specific non-linearity you could simply transform data to linearity and continue to use a linaer learner.
2 That depends on how you train the models. If you're new to boosted trees, check out some tutorials on how to avoid overfitting. I cannot see from your plots what kind of cross-validation was used. Use a thorough outer cross-validation and perhaps compare the results to a random forest model. RF models are much easier to handle, and default settings are often near optimal. A crude thumb rule; if your RF performs better than boosted trees(measured by outer cross validation), you either have chosen sub optimal training paramters for your boosted trees model or your data is quite noisy.


SSL,IIS: One website for multiple sub-domains and one website for the top-level domain (with or without www.))

Question: I have multiple sub domains that should point to the same website and the top-level domain should point to another website. All of these are under SSL. For example:

abc.mydomain.com ---> Website A,
def.mydomain.com ---> Website A,
ghi.mydomain.com ---> Website A,
jkl.mydomain.com ---> Website A

mydomain.com ---> Website B,
www.mydomain.com ---> Website B

I have already purchased a wildcard ssl certificate and a dedicated IP. Can both websites share the same IP or should each one have its own IP?
I don't need wildcard host headers or wildcard DNS mapping. Every time, for each new sub-domain I am able to add a new DNS record and a new host header for the Website A.
Answer: In this case you would need separate ports if they were on the same IP, or separate IPs if you wanted them on the same standard SSL port (443). IIS doesn't support reading host headers and redirecting using SSL. You can use the same wildcard certificate without any issue, but you would need something inbetween IIS and the client (like Microsoft Forefront Threat Management Gateway) in order to do routing by hostname over SSL. (I hope that makes sense)
The reason this happens is because the connection is encrypted and the certificate is validated before the HTTP header is actually sent, so at that time IIS has to know what site it's using beforehand. Now, Firefox does send the hostname in with the initial encryption request but I'm not sure if IIS supports that (or if any other browsers do).
The First Few Milliseconds of a HTTPS Connection has an incredibly in depth description on how HTTPS generally works (through a special debug build of Firefox). As you can see a few paragraphs in TLS supports a server name extension, but as far as I know IIS does not support that extension.
Answer: All you need to do is set up SSL Host Headers: http://www.sslshopper.com/article-how-to-configure-ssl-host-headers-in-iis-6.html
You can then secure them all on the same IP address/port.


How to start/stop Quartz scheduler from database JDBCJobStore

Question: I tried to stop my Scheduler as follows
UPDATE QRTZ_TRIGGERS SET TRIGGER_STATE = 'PAUSED' where TRIGGER_NAME='triggerName'

but the scheduler is not stopped and gets triggered at the time specified in the crone expression.
so how do i start or stop the quartz from the database ??
thanks.
Answer: I was able to do it in two ways. I am not sure whether its a good practice.
1) By deleting the row related to the job from QRTZ_CRON_TRIGGERS (child table) and from QRTZ_TRIGGERS tables respectively, the job will not execute again. I think we should also delete the row from QRTZ_JOB_DETAILS table as well. But it worked for me even without doing it.
2) In QRTZ_TRIGGERS table, there is a column named END_TIME. If you update it with some specific time (You can use https://www.epochconverter.com/ to get epoch time), quartz is automatically deleting rows from all the 3 tables mentioned above when the time comes.
This solution is for Quartz1. I think it should work in Quartz2 as well.
Answer: I don't think this is a good practice, never use a JobStore directly in youyr code; the results may be unespected.
It is explicitly stated in the documentation:

Never use a JobStore instance directly in your code. For some reason many people attempt to do this. The JobStore is for behind-the-scenes use of Quartz itself. You have to tell Quartz (through configuration) which JobStore to use, but then you should only work with the Scheduler interface in your code.


dynamic allocation in shared memory in opencl on Nvidia

Question: I'm following the example here to create a variable-length local memory array.
The kernel signature is something like this:
__kernel void foo(__global float4* ex_buffer,
                 int ex_int,
                 __local void *local_var)

Then I call clSetKernelArg for the local memory kernel argument as follows:
clSetKernelArg(*kern, 2, sizeof(char) * MaxSharedMem, NULL)

Where MaxSharedMem is set from querying CL_DEVICE_LOCAL_MEM_SIZE.
Then inside the kernel I split up the allocated local memory into several arrays and other data structures and use them as I see fit. All of this works fine with AMD (gpu and cpu) and Intel devices. However, on Nvidia, I get the error CL_INVALID_COMMAND_QUEUE when I enqueue this kernel and then run clFinish on the queue.
This is a simple kernel that generates the mentioned error (local work size is 32):
__kernel
void s_Kernel(const unsigned int N, __local void *shared_mem_block )
{
    const ushort thread_id = get_local_id(0);
    __local double *foo = shared_mem_block;
    __local ushort *bar = (__local ushort *) &(foo[1000]);

    foo[thread_id] = 0.;
    bar[thread_id] = 0;
}

The kernel runs fine if I allocate the same arrays and data structures in local memory statically. Could somebody provide an explanation for this behavior, and/or workarounds?
Comment: What is the actual value of `MaxSharedMem` that you are using/getting? What happens if you reduce the `MaxSharedMem` variable to some smaller value, say 1000?
Comment: Host is not C# space is it? sizeof(char) 2
Comment: Host is c++. `MaxSharedMem` is 48000 for the card I'm testing on, which is quadro K1000M. I tried setting it to a smaller value, but this had no effect. The only thing that allowed me to avoid the `CL_INVALID_COMMAND_QUEUE` error was statically allocating all my data structures in local mem, which is hardly workable for my kernel.
Comment: Apologies, card is quadro 1000M, not K1000M
Comment: Perhaps you should show a short complete example that is not working.  [Here](http://pastebin.com/XN6xmRCV) is my sample, modified slightly from the vector add sample [here](https://www.olcf.ornl.gov/tutorials/opencl-vector-addition/) which seems to run correctly on an NVIDIA K40c.
Comment: added a simple kernel that demonstrates the error (on my gpu).
Comment: I was asking for a complete example, like the working example I provided.  Not just the kernel.
Comment: @robert host code + kernel [here](http://pastebin.com/AaRSavQ1)
Comment: If I change `__local void *shared_mem_block` in your kernel definition to `__local double *shared_mem_block` your code runs without error for me.
Answer: For those interested, I finally received an explanation from Nvidia. When the chunk of shared memory is passed in via a void pointer, the actual alignment does not match the expected alignment for a pointer to double (8-byte aligned). The GPU device throws an exception due to the misalignment.
As one of the comments pointed out, a way to circumvent the problem is to have the kernel parameter be a pointer to something that the compiler would properly align to at least 8 bytes (double, ulong, etc).
Ideally, the compiler would take responsibility for any alignment issues specific to the device, but because there is an implicit pointer cast in the little kernel featured in my question, I think it gets confused.
Once the memory is 8-byte aligned, a cast to a pointer type that assumes a shorter alignment (e.g. ushort) works without issues. So, if you're chaining the memory allocation like I'm doing, and the pointers are to different types, make sure to have the pointer to the largest type in the kernel signature.
Comment: Good on you for coming back and sharing details to help others.
Comment: thank you, had the same issue, glad you posted the solution here. very helpful. https://devtalk.nvidia.com/default/topic/1057646/cuda-programming-and-performance/cl_invalid_command_queue-error-due-to-local-memory-byte-alignment/?offset=2#5363027


PHPUnit :: get message: OK, but incomplete or skipped tests! without any information where is happen

Question: Get message:
OK, but incomplete or skipped tests!
without any information where is happen.
Only the: ..I........
How can i find where is the problem?
Thanks
Answer: The output indicates that your third test case is incomplete. Try running phpunit with the --verbose flag to output more information.
Comment: thanks, there was a problem with the setting and --verbose helped me fix it!
Comment: Thanks for a dynamic solution! It also helps me to fix the issue.
Answer: i had an echo call in a test that passed without any assertions. The test passed, after removing the echo. (didn't get any info upon passing --verbose to the test runner)
Answer: My one test had this:
<code>$this->markTestSkipped();
</code>
Hence it was skipped.


$f(x)=\begin{cases}x^3\text{ if } x\in \mathbb{\mathbb{R}\setminus Q}\\ \sin x\text{ if } x\in \mathbb{Q} \end{cases}$ is Riemann Integrable?

Question: I would like to ask if this piecewise function $f(x)=\begin{cases}x^3\text{ if } x\in \mathbb{\mathbb{R}\setminus Q}\\ \sin x\text{ if } x\in \mathbb{Q} \end{cases}$ is Riemann Integrable?
I thought it was at first since both $x^3$ and $\sin x$ are Riemann integrable, because it had similarities to the modified Dirichlet's function, which is Riemann Integrable. But curiously the (unmodified) Dirichlet function is not Riemann Integrable. I was wondering why one is integrable but one is not, and if this can help me see if my function is integrable or not. Thanks.
Comment: Look at lower Riemann sums and upper Riemann sums over an interval $[a,b]$: can they ever converge?
Comment: As a spoiler for what is yet to come in your studies, although the function is not Reimann integrable, it *is* Lebesgue integrable (since $m(\mathbb{Q})=0$).
Answer: Since $\sin(x)$ is bounded by one, when x is greater than one, the upper sum will take values corresponding to $x^3$, but the lower sum will take values of $\sin(x)$. And because a function is Riemann integrable if and only if the lower sum ($s(f)$) and the upper sum  (S(f)) satisfy  $|S(f)-s(f)|<\varepsilon$. this function won't be Riemann integrable
Answer: Here is another explanation, that connects with some more sophisticated concepts.
A function is Riemann integrable iff it is continuous almost everywhere, with respect to the Lebesgue measure. Even if you haven't heard of Lebesgue measure, you can make sense of this statement!
Let's look at the points of continuity of $f(x)$. When $x^3\not=\sin x$, the function will have different limits as you approach $x$, depending on if you use rationals or irrationals. Thus the points of continuity of $f(x)$ are precisely the solutions of $x^3=\sin x$. There are only 3 solutions: $x\in \{0,\pm .929\}$. So for almost every value of $x$, the function is discontinuous at $x$.
Lebesgue measure makes the phrase "almost every" formal, because the measure of any finite set is 0. Thus the function is not Riemann integrable.
But as pointed out before, it is Lebesgue integrable, simply because it agrees almost everywhere with the nice function $x^3$.


How to calculate balance along opening balance in SQL

Question: Can anybody help me writing a SQL query to find the balance with opening balance on top as well?
Desired output:

It currently does not show "Opening Balance" but I want it as well.
Here is the sample data:
create database test

use test

CREATE TABLE [dbo].[tbl_Ledger]
(
    [Ledg_ID] [int] Primary Key IDENTITY(1,1) NOT NULL,
    [Ledg_p_ID] [int] NULL,
    [Ledg_Pay_ID] [int] NULL,
    [Ledg_FarmerID] [int] NOT NULL,
    [Ledg_Date] [date] NOT NULL,
    [Ledg_Desc] [varchar](255) NULL,
    [Ledg_Debit] [money] NOT NULL,
    [Ledg_Credit] [money] NOT NULL,
    [Ledg_Remarks] [varchar](255) NULL
)

INSERT INTO [dbo].[tbl_Ledger] ([Ledg_p_ID], [Ledg_Pay_ID], [Ledg_FarmerID],[Ledg_Date],
                                [Ledg_Desc], [Ledg_Debit], [Ledg_Credit],[Ledg_Remarks])
VALUES (1, NULL, 2, '2021-05-06',
        'Purchase', 500, 0.00, ''),
       (NULL, 2, 2, '2021-05-07',
        'Payment', 0.00, 300, ''),
       (NULL, 3, 2, '2021-05-08',
        'Payment', 0.00, 200, '')

Comment: What does "opening balance on top" mean?  It seems to have nothing to do with your desired results.
Comment: Opening Balance means,  Balance of previous date from starting date.
Suppost, I have requested 10-05-2021 to 15-05-2021, then Balance of 09-05-2021 will be my opening balance
Answer: This might depend on the vendor of DB that you are using, but many support the OVER clause.
see explanation here:
using OVER you can create a cumulative sum of a column.
so your query will look something like this:
SELECT ID, p_ID, FarmerID, Datee, Description, Debit, Credit,
SUM (Debit - Credit) OVER (ORDER BY Datee) AS Balance
FROM tbl_Ledger

Comment: Imbar, You are right but if we have more than 1 entry on the same date. then it's creating problem while calculating balance
Comment: @M.HamzaSajjad - You must have some way to distinguish between, and sequence, multiple entries on the same day, correct? Whatever those columns are, they should be included in the (ORDER BY) clause. (If you have no way of sequencing multiple entries on the same day, then the data model is insufficient to establish a starting or ending balance on each transaction because, by definition, you would not know the order of those transactions. I'm assuming this is not the case.)
Answer: If you want the "opening" balance on each row, just subtract out what happens on the row:
SELECT l.*,
       SUM(Debit - Credit) OVER (ORDER BY Datee) AS Balance
       SUM(Debit - Credit) OVER (ORDER BY Datee) - (Debit - Credit) AS Opening_Balance
FROM tbl_Ledger l


Is there any way we can write in a Dockerfile the -v command used on docker cli?

Question: Say, I have a local dir structure of /var/lib/jenkins and on the resultant container i have the same dir stucture. Now, i need that the jenkins user created through Dockerfile should be able to access the /var/lib/jenkins/.m2/repository existing on local machine. I have mapped the container jenkins userid to the jenkins userid on local using usermod and groupmod in Dockefile. However, I need that /var/lib/jenkins/.m2/repository on local should be accessible inside the container for all processes on it, in a way that local machines's repository maps to container path
Effectively, i need to achieve below cmd inside the dockerfile
docker run -it  --name my_container -v /var/lib/jenkins/.m2/repository:/var/lib/jenkins/.m2/repository my_image

Any guidance on this will be helpful.
Thanks!
Answer: Yes, it is, you can use VOLUME directive, in your example line will looks like
VOLUME /var/lib/jenkins/.m2/repository
detailed description in  documentation
Comment: Thanks,  @Quantim for responding. Yes. I had tried this instruction earlier too, it only creates an empty directory  in the container. It still needs to use 'docker run -it -v ' to be able to access the host path. This is confirmed in another post here (see accepted answer: https://stackoverflow.com/questions/27735706/docker-add-vs-volume)
Answer: You cannot define a volume source in a Dockerfile, because images may be run on different environments where the source would change. So while you can tell Docker the image has a volume at /var/lib/jenkins/.m2/repository, you cannot tell the image to map that volume to the host directory /var/lib/jenkins/.m2/repository. To specify runtime configurations, you can specify this in a docker-compose.yml file with a volume section like:
version: '3'
services:
  svcname:
    image: my_image
    volumes:
    - /var/lib/jenkins/.m2/repository:/var/lib/jenkins/.m2/repository

I personally recommend against defining a volume inside the Dockerfile. It will generate anonymous volumes if you don't also specify a volume source at runtime. And if you want to make changes to this directory with a RUN command in your Dockerfile after the volume is defined, those changes will not be saved to your image and will be lost when the RUN line completes.
Comment: Thanks, @BMitch, for explaining so well. Cleared all doubts. I also do not favor defining volume inside Dockerfiles as it defeats the purpose of Docker portability. However, I was trying to use the mvn repos already downloaded on host to use in the container......But yes, docker compose is the right way to go for this usecase so far.
Comment: I could only accept your answer @BMitch. I am unable to upvote due to StackExchange reputation criteria.
Comment: @ValenciaSerrao if you're looking for the option to have a cache directory on the build host, that functionality is coming with buildkit: https://github.com/moby/moby/issues/32507#issuecomment-409092581


Find the value of K for which the given matrix has rank 2

Question:
I think I've got the right intuition here. Row reduce and then by the knowlege that the matrix has a rank of 2, I know the third row will be one of zeros. Therefore, for the third entry in that third row, I will likely have some constant added or subtracted from K, which can be set equal to zero.
I've row reduced down but I'm essentially at a point where I can't get a rational number for K. Hopefully this is purely a computational error but please let me know if I'm going wrong elsewhere.
Comment: The bottom-right hand corner should be $-24+5k$.
Answer: In my opinion, the easy way to do this is to use the fact that if a $n×n$ matrix has a rank less than $n$, then the determinant is $0$. Thus, if a $3×3$ matrix has a rank of $2$, then the determinant is $0$. Therefore, we can just find the determinant in terms of $k$, set it to $0$ and solve.
$$169-13k=0 \implies k=13$$

However, your way is perfectly valid, but you had a computational error in your last step, so it should really be:
$$\begin{bmatrix}-5 & -6 & 4 \\ 0 & 13 & 13 \\ 0 & 41 & -24+5k\end{bmatrix}$$
Now, in order to eliminate the $41$ in the second component of the third row, multiply the second row by $41$, the third row by $-13$, and put in the third row:
$$\begin{bmatrix}-5 & -6 & 4 \\ 0 & 13 & 13 \\ 0 & 0 & 845-65k\end{bmatrix}$$
In order for this matrix to have a rank of $2$, the last row must be all zeroes, so:
$$845-65k=0 \implies k=13$$
Answer: Your approach is good, but you didn't finish doing row reduction. we can still go:
$\begin{pmatrix}
1 & \frac{6}{5} & -\frac{4}{5}\\
0 &1 & 1\\
0 & 0 & -65+5k\\\end{pmatrix}\\$
and then
$\begin{pmatrix}
1 & 0 & \frac{2}{5}\\
0 &1 & 1\\
0 & 0 & -65+5k\\\end{pmatrix}$.
Clearly the first two columns are linearly independent, so the rank is $2$ if and only if the last column is generated by the first two, which clearly happens if and only if $-65+k=0$
Comment: No, it should be $-65+5k=0$.
Comment: Oh yeah, right thanks.
Answer: Hint

$$\begin{vmatrix} A \end{vmatrix}=0$$
Answer: The above given problem can be solved using 2 methods :
1.By echelon form
2.By using determinant
process of solving
process of solving
Comment: Welcome to math SE. Have a look at [mathjax](https://math.meta.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference) for your mathematical expressions.
Answer: Since A is a 3 by 3 matrix of rank 2, all 3 by 3 minors, if any, must be of zero. Here the only 3 by 3 minor is det(A), so that det(A)= 0 will give -13k+169 = 0. Hence k = 13.
Comment: Welcome to MSE. For some basic information about writing mathematics at this site see, *e.g.*, [basic help on mathjax notation](/help/notation), [mathjax tutorial and quick reference](//math.meta.stackexchange.com/q/5020), [main meta site math tutorial](//meta.stackexchange.com/a/70559) and [equation editing how-to](//math.meta.stackexchange.com/q/1773).


Java solution (framework / library / API) for real crossplatform applications / apps

Question: I dont know but it seems there are several solutoins for Java (Java SE, ME ...) for different platforms so you have to write different versions of the same application for all devices (iOS, Android, Windows, Linux ...).
(Is it even possible to use Java ME on devices running Android and iOS?)
Is there a solution for Java to create just one application which runs seamless on all devices? Or do we have to rewrite the application for different devices?
Comment: Why is IOS tagged? You can't run Java applications on it.
Comment: sure, you can http://www.zdnet.com/oracle-puts-java-apps-on-ipads-and-iphones-7000006209/
Comment: ADF datasheet is confusing? The most that I can take away from it is that *possibly* they have embedded a JVM within their framework (doubtful)? You can't include any such framework in an app you intend to sell through the app store as it violates Apples TOS. Looks to me more like a PhoneGap inspired framework that converts Java into native code.
Comment: Selling through the app store is not planned at all. The customer gets the app diectly from us. It seems they have a "light" JVM included, are there any experiences with ADF?
Answer: I know only one solution that allows to use Java on Android/iOs - codenameone. Unfortunatly I haven't tryed it in practice yet but I had read several articals and got a very good impression of it.
Answer: I guess, the future of cross portable apps is HTM5, CSS3 and Javascript. Java (or DART) can be used as high level language to generate the Javascript.
I suggest you to have a look at phonegap and mobilegwt for the mobile, and for the desktop Adobe Air.
You can write a mobile/desktop application in Java using mobilegwt. Then you cross compile the application for the different browsers (iphone, ipad, android, blackberry, desktop), and package the javascript+html+css+images inside a native app for all the platforms.
Your application can run from a web server (downloading html, and everything) or be a javascript application running completely from the device; or being a mixture of the two things: a javascript application deployed into the native app and running from the device, doing AJAX calls to a server.
Those application are frequently called hybrid applications.
Eventually you can skip the java part and develop an html5+css3 app and package with phonegap for the different platforms. But I find mobilegwt being able to produce hybrid apps who look like native apps (with "look and feel" and animation very well implemented). And GWT helps in bringing the scalability of the Java language (reusable components, tools, and OO) to Javascript.
For the desktop you can package an html5 app with Adobe Air.
For videogames, I think playn deserve some attention, being able to cross compile games for Desktop Java, HTML5 Browsers, Android, iOS, Flash (and more), and producing impressive results like Angry Birds for Chrome (cross compiled from Java to Javascript).
Comment: I dont like Adobe at all also dont like Adobe air. I think we will keep building the mainapp with normal JavaSE for desktop clients and second custom build with less features for mobile devices using phonegap
Comment: @DanielRuf with PhoneGap you can create native plugins (or "drivers") to expose native APIs to be used from JavaScript. So, it's not really posing restrictions, you need to implement some "drivers" to use particular features of the devices, if they aren't already available.
Answer: Java code is compiled to byte code that is guaranteed to be cross platform, i.e. can be executed on any JVM.
Different environments can provide different platform dependent APIs and require additional requirements. For example Java EE provides service of container and requires writing container managemed components (EJB, Servlets etc). But code itself remains cross platform.
Although J2ME died it dictates writing MIDlets. It is indeed special: it does not provide regular JDK, so let's avoid to discuss it.
iOS running on "big" Mac computers can run regular java. The same java that is running on windows or linux. So, the code remains cross platform.
Comment: Thats what we already know, but what about iPhone, iPad, Android tablets ...?
Comment: iPhone,iPad and Android tablets don't really run normal java programs.
Comment: @AlexR - you cannot run Java on an iOS device (unless its unlocked and installed ofc).
Comment: Oracle is confusing me with their ADF and their "lite" JVM.


How to parse csv file with camel bindy, when some columns have quotes and some not?

Question: I try to use Camel bindy to process my csv file. Rows of the file look like this:
1111;"2016-06-21";"12:15";"Test1";"1";
2222;"2016-06-21";"12:16";"Test2";"2";

My model file is:
@CsvRecord(separator = ";")
public class CsvBean implements Serializable {

    @DataField(pos = 1)
    private Integer key;

    @DataField(pos = 2, pattern = "yyyy-MM-dd")
    private Date date;

    @DataField(pos = 3, pattern = "hh-mm")
    private Date time;

    @DataField(pos = 4)
    private String title;

    @DataField(pos = 5)
    private int status;
}

and I use unmarshall(bindy) method. The exception I got is:
java.lang.IllegalArgumentException: Parsing error detected for field defined at the position: 3, line: 1
    at org.apache.camel.dataformat.bindy.BindyCsvFactory.bind(BindyCsvFactory.java:207)

I suppose that the problem is that first "id" value is without quotes and the rest of columns have. How can I solve it?
Answer: Your pattern for pos 3 is wrong . Try the below code
 @DataField(pos = 3, pattern = "hh:mm")

Comment: Oh yes. Thank you very much!


Classifying abelian groups or prime exponent without using the classification of finite abelian groups

Question: Let p be a prime. Without using the classification of finite abelian groups, classify (up to isomorphism) all finite abelian groups with every non-identity element having order p. (Note that when p=2 this gives a classification of all finite groups with every non-identity element having order 2, since every such group is automatically abelian.)
One theorem I suspect can be helpful is the following:
Every group of order $p^2$, where p is prime, is isomorphic to $Z_{p^2}$ or $Z_p \oplus Z_p$
This has a corollary that states:
If G is a group of order $p^2$, where p is a prime, then G is abelian
I think those could both be helpful but I'm still quite fuzzy on how to classify groups. I don't really understand that concept
Comment: The first is potentially relevant, if looking at the proof might help you generlaize. The second is useless, since you are being asked to describe **abelian** groups, you may assume your group is abelian to begin with. A theorem that tells you a group must be abelian just tells you what you are already assuming.
Answer: Hints.

First, prove that an Abelian group with each non-identity element of order $p$
can be considered as a vector space over a field of $p$ elements $\mathbb{Z}_p$.

Then use the theorem from linear algebra that
two vector spaces are isomorphic if and only if they have the same dimension.
Comment: I feel like this is just a teeny bit more complicated than necessary. If you prove $1$ then you have that every finite abelian group satisfying the aforementioned property is isomorphic to $\mathbb{Z}_p^n$ for some $n$. Then you're done.


Change of Domain result in Lost Emails?

Question: Recently we've had quite a few requests where clients are changing their domain
names and want to keep the same email addresses and have the new domain
be the main site. The old domain will then forward to the new one.
What I'm wondering is, what is the best way to approach this? We changed the
name of the site in the various locations of the hosting account to the new name (www.newname.com)
and it changed all appropriate names in the zone file to the new name and seems to
work fine. The old email accounts are now under newname.com.  How do we
set up the zone files(s) so that the oldname.com email goes to the newname.com email?
Telling the domain to forward in domain management doesn't forward the email, just the
website.
Answer: What mail system? In an example with Exchange, you can have as many domains as you like pointed to your Exchange server. You setup the recipient policy for each domain, and simply add the desired email address to each users AD profile.
Answer: That depends a lot on what you're using for a mail system. So long as they still own the old domain, that is. Most mailers can be configured to redirect mail. firstname.lastname@example.com is quietly internally redirected to email@example.com. The exact methods of this are mailer dependent. It can't be done in DNS that I know of.
Answer: Apparently the correct way to do this is simply use a DOMAIN ALIAS
Answer: I do this in sendmail by configuring multiple domains to be handled by the relay.
Edit
/etc/mail/local-hosts-names

and add the domains you wish to handle. For example:
# local-host-names - include all aliases for your machine here.
domain.com
otherdomain.com
yetmore.net

After making your changes, and presuming DNS is setup properly, restart sendmail.
Note: this means that user@domain is equivalent to user@otherdomain, because /etc/passwd and /etc/aliases is hit for both for user verification.

Change of Domain result in Lost Emails?


Set custom timer for Slick slideshow based on field value

Question: I have a Slick slideshow. My nodes have a Timer field. Right now, I am setting the time of the slick slide like so:
Drupal.behaviors.mrpeanut = {
  attach: function (context, settings) {
    var $slider = $("#slick-views-slideshow-page-1-slider");
    $slider.once('mrpeanut').on("afterChange", function(event, slick, currentSlide) {
            slideTime = $('div.slide--' + slick.currentSlide + ' div.field--name-field-timer').text();
            $slider.slick("setOption", "autoplaySpeed", slideTime);
        });
  }
}

However, I had some feedback that I may be better off to preprocess the field then attach a JS settings array with all the timer values. This is what I started piecing together based on some discussion in Slack (thanks, @nikathone).
In mrpeanut.module:
function mrpeanut_preprocess_node(&$variables) {
    $variables['#attached']['library'][] = 'mrpeanut/mrpeanut';
    $node = $variables['node'];
    $slideTime = $node->hasField('field_timer') ? $node->get('field_timer')->value : 20000;
    $slideTime = $slideTime * 1000; // Convert milliseconds to seconds
    $variables['#attached']['drupalSettings']['slideTime'][$node->id()] = $slideTime;
}

In mrpeanut.js:
(function($, Drupal, drupalSettings) {
    Drupal.behaviors.mrpeanut = {
        attach: function(context, settings) {
            var $slider = $("#slick-views-slideshow-page-1-slider");
            var slideTime = drupalSettings.slideTime;

            // Get Node ID from the article
            var nodeAbout = $('.slide').find('article').attr('about');
            var nodeID = nodeAbout.substring(6, $('.slide').find('article').attr('about').length);

            $slider.once('mrpeanut').on("afterChange", function(event, slick, currentSlide) {
                $slider.slick("setOption", "autoplaySpeed", slideTime);
            });
        }
    }
})(jQuery, Drupal, drupalSettings);

However, it's not actually setting the correct timer values. One issue I'm having is that I need to capture all Node IDs from the view (whereas now I am only getting the first). Second, I'm setting the time slide on the afterChange instead of initially all-at-once.
Comment: I have test your code, I think this not gonna work because `['#attached']` should added to `render array` if you try it in `hook_form_alter` for example `$form['#attached']['drupalSettings']['slideTime'] = $slideTime;`  it works.
Comment: It's part of a view. Would it work if I somehow put my code in the view?
Comment: View, which hook ?or maybe you can move your code to the `hook_page_attachments(array &$page)`  to attach library to entire page: something like ```$page['#attached']['library'][] = 'mrpeanut/mrpeanut';```  you will need the `field_timer` value ;( !
Comment: The library is getting attached properly... I think the issue is that the field_timer value is getting added to a new array with each node load (from `preprocess_node`) instead of to the same array (but I could be wrong).
Answer: Here's my final mrpeanut.js:
(function($, Drupal, drupalSettings) {
    Drupal.behaviors.mrpeanut = {
        attach: function(context, settings) {
            var slider = $("#slick-views-slideshow-page-1-slider");
            var slideTime = drupalSettings.slideTime;
            var nodeIdArray = []
            $('article').each(function(i){
                var nodeAbout = $(this).attr('about');
                var nodeID = nodeAbout.substring(6, $(this).attr('about').length);
                nodeIdArray.push(nodeID);
            });

            slider.once('mrpeanut').on("afterChange", function(event, slick, currentSlide) {
                slider.slick('slickSetOption', 'autoplaySpeed', slideTime[nodeIdArray[currentSlide]], true);
            });
        }
    }
})(jQuery, Drupal, drupalSettings);


Fazer condição dentro do render

Question: Estou apredendo Ruby e estou com um dúvida de como fazer um if dentro do render para exibir o param somente se ele existir...
Ex:
if params[:field]
  puts 'field'  =>  params[:field],
end

Como resolvo isso nesse código?
render :json => {
    'request'=>{
        'negotiation'   =>  params[:negotiation],
        'state' =>  params[:state],
        'city'  =>  params[:city],
     },
    'response'=>lista,
}

abs!
Answer: Monte antes o hash:
res = {
    'request'=>{ },
    'response'=>lista
}

Adicione os parâmetros assim:
res['request']['negotiation'] = params[:negotiation] if params[:negotiation]

res['request']['state'] = params[:state] if params[:state]

E faça o render
render json: res

Comment: Sabe me dizer, porque eu não consigo popular esse hash antes de instancia-lo?
Comment: Não entendi sua dúvida.
Comment: Porque eu não posso começar adicionando "res['request']['negotiation'] = x". Porque eu preciso criar primeiro o hash vazio?
Comment: Vc pode, nada impede de criar um hash res = {} e ir adicionando as chaves necessárias.
Comment: Isso, mas porque eu devo criar ele zerado primeiro? No PHP por exemplo eu não preciso criar um $array = array(), posso começar diretamente pelo $array['chave'] = valor.
Comment: Vc pode, mas no seu caso como vc quer fazer if pra saber que campos vão ou não existir, nao funcionaria. Mas nada impede de declarar um hash assim: h = { 'chave' : valor }.
Comment: Entendi sua pergunta. Não é possível inicializar como no php, no ruby hashes e arrays tem que ser declarados antes de poder ser utilizados.

Fazer condição dentro do render


How to adjust result to equal mode values in R

Question: The code below is generating the mode value considering the columns Method1, Method2, Method3 and Method4. However, notice that for alternative 10 and 12 it has the same mode value, that is, it has a value of 2. However, I would like my Mode column to have different values, as if it were a rank. Therefore, the alternative that had Mode=1 is the best, but I have no way of knowing the second best alternative, because it has two numbers 2 in the Mode column. Do you have suggestions on what approach I can take?
database<-structure(list(Alternatives = c(3, 4, 5, 6, 7, 8, 9, 10, 11, 12),
    Method1 = c(1L, 10L, 7L, 8L, 9L, 6L, 5L, 3L, 4L, 2L), Method2 = c(1L,
    8L, 6L, 7L, 10L, 9L, 4L, 2L, 3L, 5L), Method3 = c(1L,
    10L, 7L, 8L, 9L, 6L, 4L, 2L, 3L, 5L), Method4 = c(1L,
    9L, 6L, 7L, 10L, 8L, 5L, 3L, 4L, 2L)), class = "data.frame", row.names = c(NA,
10L))

 ModeFunc <- function(Vec) {
    tmp <- sort(table(Vec),decreasing = TRUE)
    Nms <- names(tmp)
    if(max(tmp) > 1) {
      as.numeric(Nms[1])
    } else NA}

output <- database |> rowwise() |>
mutate(Mode = ModeFunc(c_across(Method1:Method4))) %>%
data.frame()

> output
   Alternatives Method1 Method2 Method3 Method4 Mode
1             3       1       1       1       1    1
2             4      10       8      10       9   10
3             5       7       6       7       6    6
4             6       8       7       8       7    7
5             7       9      10       9      10    9
6             8       6       9       6       8    6
7             9       5       4       4       5    4
8            10       3       2       2       3    2
9            11       4       3       3       4    3
10           12       2       5       5       2    2

CHECK
   output$Rank <- (nrow(output) + 1) - rank(-output$Mode, ties.method = "last")
   output|>
   arrange(Mode)

   Alternatives Method1 Method2 Method3 Method4 Mode Rank
1             3       1       1       1       1    1    1
2            10       3       2       2       3    2    2
3            12       2       5       5       2    2    3
4            11       4       3       3       4    3    4
5             9       5       4       4       5    4    5
6             5       7       6       7       6    6    6
7             8       6       9       6       8    6    7
8             6       8       7       8       7    7    8
9             7       9      10       9      10    9    9
10            4      10       8      10       9   10   10

Comment: No. Your ranking produces ties. You haven't defined how to break a tie. We might suggest ways of doing so, but we can't know which way is most useful without context. You could, for example, use the second most frequent value to break a tie. Or the smallest value lower than the mode, or the smallest value greater than the mode. Or any other option you like. You know your data. You're best placed to know what's most appropriate.
Comment: Thanks @Limey! You're right, without context, it's hard to say something. I think that when you have the same `mode`, choose the `alternative` that has the lowest value. That is, in the case of `alternative` 10 and 12 it has the same mode value, that is, it has a value of 2, choose `alternative` 10, as the second in the ranking, you know? How could I do something like this in the code?
Answer: OK.  Based on OP's comment above, Here's a solution that picks the row with the lowest value of Alternatives in case of ties.  You can generalise to any other tie break with an appropriate modification of the second mutate.
output |>
  arrange(Mode) |>       # Sort by mode
  group_by(Mode) |>      # Assign intial ranks
  mutate(Rank=cur_group_id()) |>
  arrange(Rank, Alternatives) |> # Sort and assign tie break
  mutate(TieBreak=row_number()) |>
  ungroup()
# A tibble: 10 × 8
   Alternatives Method1 Method2 Method3 Method4  Mode  Rank TieBreak
          <dbl>   <int>   <int>   <int>   <int> <dbl> <int>    <int>
 1            3       1       1       1       1     1     1        1
 2           10       3       2       2       3     2     2        1
 3           12       2       5       5       2     2     2        2
 4           11       4       3       3       4     3     3        1
 5            9       5       4       4       5     4     4        1
 6            5       7       6       7       6     6     5        1
 7            8       6       9       6       8     6     5        2
 8            6       8       7       8       7     7     6        1
 9            7       9      10       9      10     9     7        1
10            4      10       8      10       9    10     8        1

Note that cur_group_id() required dplyr v1.0.0 or later and that row_number() takes account of groups when a data frame is grouped.
Comment: Thanks @Limey! Just one question, your reply is similar using `rank` function that I inserted in the question now? I saw that `ties.method = last` generates rank with different values.


How do I change the views ajax URL?

Question: I build a view page and have exposed filter, when I change any filters I use ajax to fetch data and re-build the content area. The ajax URL looks like

views/ajax

I want to change the above URL to some external middleware something like below

http://www.example.com/getData

with the existing post data. Is it possible?
Answer: You can try changing the settings data on the ajaxSend event.
$(document).ajaxSend(function(event, request, settings) {
  settings.url = '/views/ajax';
});

How do I change the views ajax URL?


Google sheets: Working code for get IDs but result should be align on the filename row

Question:
The IDs should be aligned like the sample on the left side. But as you can see on the right side, everything is working fine until row 11. Can someone help me with this one?
Here's the code that I'm using. I got it from here.
function myFunction() {
  const ss = SpreadsheetApp.getActive();

  var SSID =  ss.getId();
  var spreadsheetFile =  DriveApp.getFileById(SSID); //get file by id
  //var folderId = spreadsheetFile.getParents().next().getId();
  var folderId = "1vn5n00iCpKUWe_JsTFAesQsSmBsXu36i";

  const sh = ss.getSheetByName('Sheet4'); // change that to the name of your sheet
  const filenames = sh.getRange('B3:B').getValues().flat().filter(r=>r!='');
  const Folder = DriveApp.getFolderById(folderId);

  // 1. Retrieve the file list of all files in `folderId`.
  const getFileList = (f, folders = [], fileList = {}) => {
  const fs = f.getFiles();
  while (fs.hasNext()) {
    const file = fs.next()
    fileList[file.getName()] = file.getId();
  }
  const fols = f.getFolders();
  const folderObjs = [];
  while (fols.hasNext()) folderObjs.push(fols.next());
  if (folderObjs.length > 0) {
    folders.push(folderObjs);
    folderObjs.forEach(fol => getFileList(fol, folders, fileList));
  }
  return fileList;
};
const fileList = getFileList(Folder);

// 2. Create an array for putting values to Spreadsheet.
const IDs = filenames.map(fn => [fileList[fn] || ""]);

  sh.getRange(3,3,IDs.length,1).setValues(IDs);
}

Comment: It seems like I just need to put something in `B10` for it to work.
Answer: I think that the reason of your current issue might be due to by const filenames = sh.getRange('B3:B').getValues().flat().filter(r=>r!='');. So how about modifying this as follows?
From:
const filenames = sh.getRange('B3:B').getValues().flat().filter(r=>r!='');

To:
const filenames = sh.getRange('B3:B' + sh.getLastRow()).getValues();


Receber ID do POST e jogar para Location via GET

Question: estou preciando pegar a ID da entidade que acabou de ser cadastrada. Só que ela será jogado para outra tela, para ser cadastrado outras informações. Gostaria de saber como posso pegar a ID da entidade ao salvar o formulário.
Esse é o HTML

<form action="set.php" method="post">

   *Nome
   <input type="text" id="nome" name="nome" class="form-control" placeholder="">

   Sobrenome
   <input type="text" id="sobrenome" name="sobrenome" class="form-control" placeholder="">

E esse é o PHP

<?php

$nome                = $_POST ["nome"];
$sobrenome           = $_POST ["sobrenome"];

$sql = mysql_query ("INSERT INTO gr_entidade (nome, sobrenome ) VALUES ('$nome', '$sobrenome')");

header("Location: usuario?id=id");
?>

header("Location: usuario?id=id");

Podem me dar uma ajuda ?
Comment: mysql_insert_id - Obtém o ID gerado pela operação INSERT anterior http://php.net/manual/pt_BR/function.mysql-insert-id.php
Comment: LAST_INSERT_ID - só funciona se você fez a última inserção na mesma conexão. Se a última inserção acrescentou 3 registros no DB, esta função retorna o primeiro deles, e não o último. https://pt.stackoverflow.com/questions/127456/forma-otimizada-recuperar-ultimo-id-mysql
Comment: Faça `header("Location: outrapagina.php?id=" . mysql_insert_id());` e na outra pagina receba assim ``
Answer: Para capturar o último ID adicionado, basta executar a query sql.
mysql_query("SELECT LAST_INSERT_ID()");

Ou você pode usar a função mysql_insert_id
Comment: Obrigado. Usei a função  mysql_insert_id e deu certo
Answer: Conforme documentação do PHP:
Use: mysql_insert_id().
Ex.:
<?php

$nome                = $_POST ["nome"];
$sobrenome           = $_POST ["sobrenome"];

$sql = mysql_query ("INSERT INTO gr_entidade (nome, sobrenome ) VALUES ('$nome', '$sobrenome')");

$last_id = mysql_insert_id();

header("Location: usuario?id=$last_id");
?>

Vale ressaltar que a extensão mysql está obsoleta, conforme a mesma documentação:

Aviso Esta extensão está obsoleta desde o PHP 5.5.0 e foi removida no
  PHP 7.0.0. Utilize MySQLi ou PDO_MySQL alternativamente. Veja também
  MySQL: escolhendo uma API e FAQs relacionadas para mais informações.
  Alternativas a essa função incluem:
mysqli_insert_id()
PDO::lastInsertId()

É recomendável migrar para as extensões mysqli ou PDO.
Comment: Funcionou muito bem!


type variable T with upper bounds LineChart,View

Question: I have the following class:
public class LineChart extends AppCompatActivity{
private LineChart mChart;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_line_chart);

    mChart = findViewById(R.id.linechart);
  }
}

And an XML:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
          android:layout_height="match_parent"
          android:layout_width="match_parent"
          android:id="@+id/relativeLayout">

<com.github.mikephil.charting.charts.LineChart
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/linechart">

</com.github.mikephil.charting.charts.LineChart>

My problem now is that when i try to get the Line Chart with findViewById(R.id.linechart) i get the error:

Error:(42, 24) error: incompatible types: no unique maximal instance exists for type variable T with upper bounds LineChart,View
  where T is a type-variable:
  T extends View declared in method findViewById(int)

If you look in the MPAndroidChart Wiki you will see that i did nothing wrong (i hope). Can someone tell me please where my mistake is. Thanks in advance
Answer: You should give your Activity a different name.
You have a conflict with the name LineChart so when you do the findViewById(...) lookup it thinks you want to use your LineChart instead of the one from the library you are using.
This is what is causing the incompatible types message since your LineChart does not extend View.


Setar variável com SELECT e WITH no SQL Server

Question: Estou tentando setar a variável com uma consulta, O select só dá certo dessa maneira utilizando o WITH, porém ele está dando erro quando eu vou atribuir o valor na variável.
O código que estou tentando:
  DECLARE @contador INT, @empresas INT, @id_empresa INT
  SET @contador = 1
  SET @empresas = (SELECT COUNT(ID_Pessoa) FROM Empresa)

  WHILE (@contador <= @empresas)
  BEGIN

  SET @id_empresa = with CTE_R as
  (SELECT e.ID_Pessoa, ROW_NUMBER() OVER(ORDER BY ID_Pessoa) as RowNum FROM                         Empresa e (NOLOCK))
  select ID_Pessoa from CTE_R where RowNum = 1

  INSERT INTO Produto_Lista_Empresa (ID_Produto_Lista, ID_Empresa)
  SELECT ID, @id_empresa FROM Produto_Lista

  SET @contador = @contador + 1
  CONTINUE;
  END

Ele está dando erro na hora de atribuir o valor da variavel @id_empresa
Comment: Onde está dando o erro e qual erro que aparece?
Comment: está dando erro na hora de atribuir valor a variável @id_empresa, o erro é: "Incorrect syntax near the keyword 'with'."
Answer: WITH CTE_R AS (
  SELECT e.ID_Pessoa,
         ROW_NUMBER() OVER(ORDER BY ID_Pessoa) AS RowNum
    FROM Empresa e WITH(NOLOCK)
)
SELECT @id_empresa = ID_Pessoa
  FROM CTE_R
 WHERE RowNum = 1

Mas na realidade você tem outra forma de conseguir esse valor:
SELECT TOP 1 @id_empresa = e.ID_Pessoa
  FROM Empresa e WITH(NOLOCK)
 ORDER BY ID_Pessoa

Observação: Sua lógica parece um tanto equivocada. A melhor forma de fazer essa inserção não seria um LOOP. Você pode conseguir o mesmo resultado com o seguinte INSERT:
INSERT INTO produto_lista_empresa(id_produto_lista,
                                  id_empresa)
SELECT pl.id,
       e.id_pessoa
  FROM empresa e
 CROSS JOIN produto_lista pl


How do I render same component depending on the page the user is currently on?

Question: I have a component called a Card. I render it twice on page 1 and page 2 and it displays somewhat different content depending on the page. Here is my initial approach.
const Card = () => {
const [cardState, setCardState] = useState("firstpage");
  const firstPageProducts = productArray.slice(0, 4);
  const secondPageProducts = productArray.slice(5, productArray.length);
  const [shownImages, setshownImages] = useState([]);

  useEffect(() => {
    const shownImages = firstPageProducts.slice(0, 2);
    setshownImages(shownImages);
  }, []);

if (cardState === "firstpage") {
    return (

        some first page stuff

    );
  } else if (cardState === "secondpage") {
    return (

        some second page stuff

    );
  }
};

I want it to have a way for it to be stateless in a way that I can define from the page in which I'm rendering the card state. I also want it to persist in that if I go back to page 1 it loads correctly page 1 stuff.
right now if I pass down the card state as a prop to the app it sometimes throws an error claiming that the component has not been rendered at all or if it does it changes both the first-page component and the second-page component.  I'm fairly new to react and I've heard of stateless components. I was thinking this has the potential to be one of them.
How can I achieve this?
Comment: Props is absolutely the way to do this, show the props code you tried, including the relevant JSX from the parent component.
Answer: I think what you want is prop. Prop is something passed to child component in your case Card from parent component like a Deck component or something. Idk if that exist in your app.
eg
const Deck = () => {
    return (

            <Card cardContent='I am first' productList={[1, 2, 3]} />
            <Card cardContent='I am second' productList={[4, 5, 6]} />

    );
};

const Card = ({ cardContent, productList }) => {
    return

{cardContent}

        {productList.map((product) => {
            return
{product}

        })}

;
};


Erro em anotação da lib Parceler

Question: Estou implementando uma classe que implementa Parcelable e estou utilizando a lib Parceler, mas quando vou rodar o aplicativo aparece o seguinte erro:

Error:Execution failed for task ':app:javaPreCompileDebug'. Annotation processors must be explicitly declared now.  The following dependencies on the compile classpath are found to contain annotation processor.  Please add them to the annotationProcessor configuration.
      - parceler-1.0.3.jar (org.parceler:parceler:1.0.3)
    Alternatively, set android.defaultConfig.javaCompileOptions.annotationProcessorOptions.includeCompileClasspath = true to continue with previous behavior.  Note that this option is deprecated and will be removed in the future.
    See https://developer.android.com/r/tools/annotation-processor-error-message.html for more details.

Como o erro está mostrando é um problema na anotação que fiz na classe, mas não consigo entender o que está errado.
 @org.parceler.Parcel

public class Carro
{
   //Atributos da classe
   private static final long serialVersionUID = 6601006766832473959L;
   public long id;
   public String tipo;
   public String nome;
   public String desc;
   public String urlFoto;
   public String urlInfo;
   public String urlVideo;
   public String urlLatitude;
   public String urlLongitude;

   @Override
   public String toString() {
      return "Carro{" + "nome-'" + nome + "/" + "}";
   }

}
E no build.gradle :
implementation 'org.parceler:parceler:1.0.3'
implementation 'org.parceler:parceler-api:1.0.3'

Se alguém puder me ajudar agradeço :)
Answer: De acordo com o Github do Parceler, para usar o Parceler você tem de usar essas 2 linhas no gradle:
implementation 'org.parceler:parceler-api:1.1.9'
annotationProcessor 'org.parceler:parceler:1.1.9'

Erro em anotação da lib Parceler


"strlen()" funciona com literal mas não com variável do tipo string

Question: Tenho este código:
#include <iostream>
#include <string.h>
using namespace std;

int main() {
   int len = strlen("Teste");
   cout << len << endl;

   return 0;
}

Que gera a saída:

5

No código acima, eu estava usando a função strlen() no C++ para contar o número de caracteres na string "Teste". Até aí tudo bem, mas quando eu crio uma variável do tipo string:
#include <iostream>
#include <string.h>
using namespace std;

int main() {
   string nome = "Teste";
   int len = strlen(nome);

   cout << len << endl;

   return 0;
}

O programa dá erro. Por quê? A função strlen() não aceita variáveis? Então eu fui lá e tentei de outra maneira, mudei o tipo da variável para tipo char, então o código ficou assim:
#include <iostream>
#include <string.h>
using namespace std;

int main() {
   char nome[10] = "Teste";
   int len = strlen(nome);

   cout << len << endl;

   return 0;
}

E dessa vez deu certo, ele retornou o número de caracteres da palavra, mas eu pergunto, char nome[10] = "Teste"; não é a mesma coisa que string nome = "Teste";? Por que ele não funcionou com a variável do tipo string?
Comment: A resposta resolveu sua dúvida? Acha que pode aceitá-la? Veja o [tour] se não souber como faz. Isso ajudaria muito indicar que a solução foi útil para você. Também pode votar em qualquer pergunta ou resposta que achar útil no site todo.
Answer: "Teste" por padrão é um tipo char *, não é um tipo string. Ou seja, é a forma de C de criar uma string, não é a forma de C++. E se vai usar a forma de C então o strlen(), que é uma uma função de C (existe em C++ por compatibilidade, por usar, mas geralmente não é o mais adequado), funciona. strlen() espera um char *, não um string.
A terceira forma é esse mesmo tipo, só que alocando na pilha como um array.
Se declarar algo como sendo string então deve usar o que este tipo oferece, e o correto que é o length() no próprio objeto.
Então se você diz que o o tipo é string tem que pedir o tamanho, o que é inclusive absurdamente mais eficiente que a forma de C. Corretamente:
#include <iostream>
#include <string>
using namespace std;

int main(){
   string nome = "Teste";
   cout << nome.length() << endl;
}

Veja funcionando no ideone. E no repl.it. Também coloquei no GitHub para referência futura.
Comment: Sim, isso é algo que faz o `strlen()` uma bomba ambulante.
Comment: @LuizFelipe https://pt.stackoverflow.com/q/167528/112052 | https://www.joelonsoftware.com/2001/12/11/back-to-basics/
Comment: Só por curiosidade (e para manter registrado), ao contrário da função `strlen`, que é linear, o método `length` é constante?