Display + Ordering Issues w/ Inventory at Two Warehouses

Question: I am building out an e-commerce site for a screen printing ink manufacturer.  They have around 300 SKUs and warehouses in two locations - one on the east coast, one on the west.
Generally when customers order, there is a time sensitivity.  Additionally, the product can be heavy and incur large shipping costs.  For these two reasons, it is important for customers to know what stock is available at which warehouse location and to order accordingly.  Ideally, they are able to see what is available at the 'other' warehouse, as well - in case they are less time sensitive and are ok with inventory coming from this location.
I think there are a few different options as to how to approach this.  I'd be curious to hear if others have faced such a situation (surely) and how they handled it.
Comment: Hi Peter, welcome to UX. If you want to respond to someone it helps if you include `@` in your comment. That user will then receive a notification of your message. Post (question and answer alike) owners are always notified of comments to their posts. That's why you were notified of this comment even though I didn't include the notification signal.
Comment: Hi Peter, welcome to UX.se! Can you provide your solutions to the problem via. mockups or screenshots?
Comment: Hi RK!  Yes - I'll mock up a couple potential solutions and post them by tomorrow.  Thanks for the input.
Answer: Do you collect their data before they order? You could potentially use some of it to make it easier to give them directions. If they look for a product, you could show them how many are available in the warehouse closest to their address, with a secondary box showing how many in the other one if they really need it (or if the primary one is out - only show the secondary).
As Laurian Vega said, I'd give tips too. If they order 4 ink cartridges from one warehouse, but the other one is closer and has them in stock, let them know! Give them a little courtesy message at the top of the page saying "You can save money by ordering from the secondary warehouse", where they can either dismiss it or click on it and get more details.
The other alternative is you mash the two warehouse stocks together, and automatically send the ink from the closest warehouse to their address, and if that one doesn't have enough, from the secondary one too. You could run a calculation in the background to figure out the shipping cost for it, doing something like:
<code>(stock from warehouse 1 being sent * price per item to be shipped) + (stock from warehouse 2 being sent * price per item to be shipped)
</code>
The customer would most likely be more satisfied with the first option though, since you tell them straight out what they can save, what warehouse it's coming from, and all of that. They can also wait for it to become available in the warehouse closest to them since they know exactly how many it has on-hand.
Comment: Hmm, just noticed the date of OP. Not sure why it came up in my newest questions.
Answer: Hum. If I were approaching this problem I would figure out what are the most important factors. These might be like shipping time or cost - like you have outlined. I would then use a badge approach (I like newegg.com) to display the necessary characteristics for browsing.
If it is worth telling the user once it is useful telling them many times. So I would tell them on a badge, on the webpage for each listing in your store, in a header I would have the little cart with images under it with anticipated shipping+shipping cost, and I would definitely have it displayed prominently on the checkout page. You might also want to think through a recommendation engine - like, "This color blue is 4k metric tons, but this blue is 4lb, and can get to you in half the time."
Overall it sounds like you have the need to weigh some hefty issues (pun intended). Start with the page that the users are going to look at most - like browsing or search results. Then figure out what is relevant fo reach page.
Like someone said, mock-ups would be great.
Answer: I would allow them to filter based on what matters to them and ignore the actual location:

download bmml source – Wireframes created with Balsamiq Mockups
Answer: What about using a simple prompt to get the basic information from the user before they start?

Only three points for data entry (whether you enter the number of days or the date, the other is automatically calculated) and you'll likely have enough info from the customer to give them the information that they need. I'd then display the results in a table, arranged by warehouse, with both lead time and cost. Filters are available for a more granular search.


Mozilla XPCOM is not registered

Question: I'm trying to build an extension for Firefox. This extension uses an XPCOM component (a C++ dll). I'm compiling the DLL, compilation is OK.
The next step would be to use the component in Javascript from my extension. I added the code to register my component from my c++ file :
static const mozilla::Module::CategoryEntry kSampleCategories[] = {
    { JAVASCRIPT_GLOBAL_PROPERTY_CATEGORY, "greenfox", NS_SAMPLE_CONTRACTID },
};

In my manifest, I declare the XPCOM :
component {03A6D0B4-22B9-11DF-B844-20D556D89593} components/GreenCodeLabFox.dll

The problem is, when I try to use the component in JS, it seems it is not registered :
    try {
        greenfox;
        return true;
    } catch( e ) {
        alert( e );
        return false;
    }

This gives me the alert error:
ReferenceError: greenfox is not defined

In error console, I have no message.
How would I debug this if I have no error message ? By the way, my javascript.options.showInConsole is set to true.
Thanks !
Answer: Per https://developer.mozilla.org/en/XPCOM/XPCOM_changes_in_Gecko_2.0 you must use a binary-component directive to register a binary component.
That page also links to an example; you only posted a part of the code required for registration.
If the component still doesn't work, I'd try to get it via Components.classes[contract id] from the Error Console - that will show if the problem is with the component registration or just with the global property part.
https://developer.mozilla.org/en/Troubleshooting_XPCOM_components_registration might be useful for troubleshooting, although it's a bit dated.
Comment: Thanks Nickolay, it was indeed the problem.
Answer: Perhaps an Update, since Firefox 41 using binary-component for extensions is no longer supported in release builds, but may be available for custom builds using MOZ_BINARY_EXTENSIONS
https://blog.mozilla.org/addons/2015/05/04/dropping-support-for-binary-components/
https://github.com/mozilla/gecko-dev/blob/master/xpcom/components/ManifestParser.cpp
You may see errors like
[JavaScript Warning: "Only application manifests may use the 'binary-component' directive." {file: "..." line: ..}]
Comment: This is a new "feature". The original question is about much older version.
Comment: True that question originally asked on earlier version, however question was still relevant up to FF40, and came up while searching trying to identify issue with FF41.

Mozilla XPCOM is not registered


Manually migrate from evolution to thunderbird

Question: After installing 11.10, evolution stayed the default mail client on my system. I guess that is because I (a) already had thunderbird installed for a test-drive a while ago and/or (b) I had evolution configured quite extensively.
I prefer to remain with Ubuntu's choice and would like to setup thunderbird as my default client.
Can I:

Set Thunderbird as default client trough  a script or command? Or do I need to edit some config files?
Migrate my mailaccounts and their settings (login, smtp etc)? Is it possible to manuall run the migration path that other upgrading users would get?
Migrate my calendar settings to lightning?
Migrate my mailfilters?
Migrate my addressbook?
Comment: possible duplicate -> http://askubuntu.com/questions/27410/migrating-from-evolution-to-thunderbird/27413#27413
Comment: Probably not. Other question is about migrating from the *default* evolution to the none-default *thunderbird*. Things have very much changed now that thunderbird became the default mailclient.
Answer: Firstly there is this migration walk-through:
http://nucleussystems.com/blog/migrate-evolution-to-thunderbird
In regards to changing the default mail client, that is possible via "System Info" in oneiric(11.10). There is a section called "Default Applications" in which you can set the default mail client.


Can't exec "/bin/sh": Argument list too long at perl

Question: Below command in perl script is failing if there are many file in @file_to_tar, but it is working fine if we have less files in the array (@file_to_tar).
my $tar_command = "cd $ProcVars->{dropbox_dir}; tar -cvzf SmartMiles.$ProcVars->{batch_nb}.tar.gz -P @file_to_tar --remove-files";
Can some one please help me to fix the issue.
Answer: The best way is pass a very long list of files to tar is using the --from-file option:
tar -czf myarchive.tar.gz -P --from-file=$filelist --remove-files

You can also make it read the list of files from standard input by using --from-file=-
See https://www.gnu.org/software/tar/manual/html_node/files.html for more information.
Comment: Thank you very much Bill for your suggestion. I did below and it is working now
my $file_location = "$ProcVars->{dropbox_dir}/Archive_Files.csv"; open(DATA, ">$file_location") or die $!; foreach $a (@file_to_tar) { print DATA "$a\n"; } close DATA;

my $tar_command = "cd $ProcVars->{\dropbox_dir};tar -czf ABC.$ProcVars->{batch_nb}.tar.gz -P --files-from $file_location --remove-files";
Answer: You might consider, rather than calling a shell command, using the Archive::Tar Perl module instead. In particular, the "create_archive" method. This also would sidestep any potential problems arising from special characters or whitespace in the file names being interpreted by the shell your Perl code is invoking.
Comment: Hi Michael, Thanks for the reply. Archive::Tar is not available in our Perl-core common. So i used --from-file=$filelist  and it is working fine.
Answer: it is working now.
my $file_location = "$ProcVars->{dropbox_dir}/Archive_Files.csv"; open(DATA, ">$file_location") or die $!; foreach $a (@file_to_tar) { print DATA "$a\n"; } close DATA;
my $tar_command = "cd $ProcVars->{\dropbox_dir};tar -czf ABC.$ProcVars->{batch_nb}.tar.gz -P --files-from $file_location --remove-files";


Prove that the legrende $(\frac{\frac{p-1}{2}}{p})=(-1)^{\frac{(p+5)(p-1)}{8}}$

Question: Let $p>2$, where $p$ is prime . $$\text{Prove:} \ \ (\frac{\frac{p-1}{2}}{p})=(-1)^{\frac{(p+5)(p-1)}{8}}$$
$$\ \ (\frac{\frac{p-1}{2}}{p})(\frac{2}{p})=(\frac{p-1}{p})=(\frac{-1}{p})$$
So we have
$$\ \ (\frac{\frac{p-1}{2}}{p}) \times(-1)^\frac{p^2-1}{8}=(-1)^\frac{p-1}{2}$$
$$\ \ (\frac{\frac{p-1}{2}}{p})=(-1)^\frac{(4-p)(p-3)}{8}$$
Answer: HINT:
From Legendre Symbol identity from prime $p$, $$\left(\frac{ab}p\right)=\left(\frac  ap\right)\left(\frac bp\right)$$
Here $\displaystyle a=2,b=\frac{p-1}2\implies ab=p-1\equiv-1\pmod p$
Check when $-1,2$ are Quadratic Residues of prime $p$
Comment: @UsernameUnknown,  $$(-1)^\frac{p-1}2/(-1)^\frac{p^2-1}8$$  $$=(-1)^{\frac{p-1}2-\frac{p^2-1}8}=(-1)^{-\frac{p^2-4p+3}8}$$

Now, $$-(p^2-4p+3)+(p+5)(p-1)=8(p-1)$$  $$\implies-\frac{p^2-4p+3}8+\frac{(p+5)(p-1)}8=p-1$$ which is even

$$\implies-\frac{p^2-4p+3}8, -\frac{(p+5)(p-1)}8$$ have same parity

So, $$(-1)^{-\frac{p^2-4p+3}8}, (-1)^{-\frac{(p+5)(p-1)}8}$$ are same
Comment: I am working out the problem and I am getting the exponent $\frac{(4-p)(p-3)}{8}$. What am I doing wrong? I am showing my work above?
Answer: Hint:
$$\frac{p-1}{2}\equiv2^{-1}(p-1)\mod{p} $$


In which file Joomla 3.x generating the "edit article" links for authors Front End?

Question: If you are allowed to edit the articles in Joomla, near the each article in the list, an "edit" button is present. How can I find, how that "edit" button generated? I just want to add some parameters. (I'm using a Front End for edit.)
Answer: It's in components/com_content/views/article/tmpl/default.php
<code>        <?php if ($canEdit) : ?>
        <li class="edit-icon"> <?php echo JHtml::_('icon.edit', $this->item, $params); ?> </li>
        <?php endif; ?>
</code>
You can override this in your template's html folder.
This script calls a function under components/com_content/helpers/icon.php to generate the icon.
You should not override this helper file.  If you need to change what that function is doing, filter the content it generates after it has been run, whether via a plug-in or the default.php file.


Thinkpad X61 (4965agn) wireless not working

Question: So I have had ubuntu for a while now and I have tried literally every solution online, but to no avail, there just seems to be no way to solve this problem: the wifi signal on my x61 is not strong (2 bars out of 3) and the speed is really low, so obviously there is a driver problem, and I know a lot of machines with the intel 4965 wireless card have the same problem. I know x61 is an old machine and ubuntu used to support it, I just don't know if ubuntu stopped including drivers for older machines in the kernel after a certain version, and if this is just the way they do things around here??
Answer: Have you tried  How do I get my Lenovo T61 to connect to a wireless network?    ?
After I did this, my connection is stable and 54Mb/s
EPA


The intersection of two theories is a theory.

Question: How to prove that the intersection of two theories is a theory ?
Let the theories be $T_1, T_2$
The only thing i know about a theory is that for all $A$ such that $T \vDash A$ $\to$ $A \in T$
So i tried . Let $B $ be a first order formula. Such that $T_1, T_2 \vDash B$
We know that because $T_1$ is a theory $B \in T1$ . Similiarly $B\in T_2$ So $B\in T_1 \cap T_2 $
Is my proof correcct ? Any suggestions ?
Comment: I believe that you should use the symbol for derivability $\vdash$, $T\vdash A$ instead of $T\models A$.
Comment: It is interesting that this theorem can be generalized. First, from two theories to any set of theories. Second, from the derivability relation to an abstract consequence relation. For example, theories can be replaced with algebraic substructures. An algebraic substructure is a subset of an underlying set of an algebraic structure closed with respect to algebraic operations.
Answer: Two comments:

"Such that $T_1, T_2\models B$" should be "such that $T_1\cap T_2\models B$" - to show that $T_1\cap T_2$ is a theory, you start with a sentence it proves (and then show that that sentence is in it).
You implicitly use the fact that ince $T_1\cap T_2\models A$, $T_1\models A$ (before "we know that because").  Given that this is an exercise in establishing the basics, it's probably a good idea to say why this is true.

Other than that, looks good!
Comment: Should i say because $T_1 \cap T_2  \subseteq T_1$ and that the set of consequences of $T_1 \cap T_2 \subseteq$ the set of consequences of $T_1$ ? Or is there an easier way to show why ?
Comment: @asddf That's exactly it.


Replace text is not working in c# which is read from .chtml file

Question: string resumeTemplate = System.IO.File.ReadAllText(@"D:\Html\Html\Views\Home\ResumeTemplate.cshtml"); // saple screen path
            DataTable dataTable = new DataTable();
            using (SqlConnection con = new SqlConnection(connection))
            {
                con.Open();

                SqlCommand com = new SqlCommand();
                com.Connection = con;
                com.CommandText = "SP_RESUMEGET";
                com.CommandType = CommandType.StoredProcedure;
                com.Parameters.Add(new SqlParameter("@USER_ID", userID));
                SqlDataAdapter ada = new SqlDataAdapter(com);
                ada.Fill(dataTable);

            }
            string firstName = Convert.ToString(dataTable.Rows[0]["FIRST_NAME"]);

            resumeTemplate.Replace("{{FirstName}}", firstName);

Here i'm reading the content from cshtml page where html content is there with placeholders and i want to replace that.
But it is not replacing.
Where I did the mistake?
Contents of ResumeTemplate.cshtml

      {{FirstName}}

Comment: What are the contents of ResumeTemplate.cshtml file ?
Comment: apart from answer com.Connection = con; line seemed redundant to me
Answer: String.Replace() returns a new string, rather than acting on the object it's called from, so you need to assign the result of the method to the string, like so:
resumeTemplate = resumeTemplate.Replace("{{FirstName}}", firstName);

More information can be found in the Microsoft documentation
Answer: This has nothing to do with the file. String.Replace returns a new String. (Reference https://learn.microsoft.com/en-us/dotnet/api/system.string.replace?view=netframework-4.8)
You need to apply the return value of Replace to a string. Something like
resumeTemplate = resumeTemplate.Replace("{{FirstName}}", firstName);


Can Table Layout have both horizontal and vertical scroll view

Question: Hi i created a Table Layout with normal Scroll view, I want it to scroll both vertical and horizontal. In XML is it possible or if there is any other solution to solve as my text is going out of table once it exceeds the length and it makes the table layout bigger and moves oout of the device.
<ScrollView android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@+id/linearImag">

    <LinearLayout
        android:id="@+id/relativelayout"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical" >

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content" >

        </LinearLayout>

        <TableLayout
            android:id="@+id/lead_table"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:layout_marginLeft="10dp"
            android:layout_marginRight="10dp"
            android:layout_marginTop="20dp"
            android:gravity="center"
            android:stretchColumns="*" >

            <TableRow
                android:id="@+id/tableRow1"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content" >

                <Button
                    android:id="@+id/textView2"
                    android:layout_width="wrap_content"
                    android:layout_height="25dp"
                    android:background="@drawable/bgbtn"
                    android:text="Lead ID"
                    android:textAppearance="?android:attr/textAppearanceMedium"
                    android:textSize="20sp" />
        </TableLayout>

        <Button
            android:id="@+id/btn_add"
            android:layout_width="50dp"
            android:layout_height="50dp"
            android:layout_marginLeft="25dp"
            android:layout_marginTop="20dp"
            android:background="@drawable/add" />

        <TextView
            android:id="@+id/tv_data"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />

    </LinearLayout>
    </ScrollView>

Answer: Instead of normal scroll view , use horizontal scroll view like
<Layout>
 <HorizontalScrollView
        android:id="@+id/horizontalView"
        android:layout_height="wrap_content"
        android:scrollbars="horizontal|vertical"
        android:layout_width="wrap_content"
        android:layout_marginTop="5dip">
<TableLayout>
    // child views...
</TableLayout>
</HorizontalScrollView>
</Layout>

Hope this will solve your problem :-)


Wordpress pagination link rel start prev next

Question: I'm developing a lightweight feature-rich custom blogging system which generates exactly the same results as wordpress, but with only one table on one database and few php files. until now everything goes well and I'm about to finish it. the problem is that when I took a look at the source code of some well known blogs using wordpress I discovered the following:
1 - the main and its following pages (2,3,4...) only declare rel="index"
2 - the category and its following pages (2,3,4...) only declare rel="index"
3 - the article page and its following pages (2,3,4...) declare rel="index", rel="start", rel="prev" and rel="next" (depending of the article position)
so, only the main articles are linked together by link rel meta tags to form a series.
Now, why there isn't a meta linking between the listing pages (the index and its following pages)?
For my project, I already done this, the index and its following pages are meta linked together to form a series like mysite.com, mysite.com/page/2/ mysite.com/page/3/
and the pages within the same category are also in a series like mysite.com/cat-1/, mysite.com/cat-1/page/2/, mysite.com/cat-1/page/3/
and the articles of the whole blog are also in a series beginning from the first article to the last one.
SO WHY THIS IS NOT THE CASE FOR WORDPRESS? IS THIS A BAD PRACTICE? OR THEY JUST CAN'T DO IT WITH WORDPRESS??????
Please help!
Thanks!
Answer: It can be done with Wordpress, not sure why it's not a default header hook but some themes do implement it. If they don't, this plugin will set the right rel links for the paginated pages http://wordpress.org/extend/plugins/pagination-rel-links/


Find overlapping ranges in a dataframe and assign them values

Question: A simpler version of the original question which I asked but nobody answered it yet.
I have a huge input file (a representative sample of which is shown below as input):
> input
           CT1           CT2           CT3
1 chr1:200-400  chr1:250-450  chr1:400-800
2 chr1:800-970  chr2:200-500  chr1:700-870
3 chr2:300-700 chr2:600-1000 chr2:700-1400

I want to process it by following a rule (described below) so that I get an output like:
 > output
              CT1 CT2 CT3
chr1:200-400    1   1   0
chr1:800-970    1   0   1
chr2:300-700    1   1   0
chr1:250-450    1   1   1
chr2:200-500    1   1   0
chr2:600-1000   1   1   1
chr1:400-800    0   1   1
chr1:700-870    1   0   1
chr2:700-1400   0   1   1

Rule:
Take every index (the first in this case is chr1:200-400) of the dataframe, see if it overlaps with any other value in the dataframe. If yes, write 1 below that column in which it exists, if not write 0.
For example, if we take 1st index of the input input[1,1] which is chr1:200-400. As it exists in column 1 we will write 1 below it. Now we will check if this range overlap with any other range which exists in any of the other columns in the input. This value overlaps only with the first value (chr1:250-450) of the second column (CT2), therefore, we write 1 below that as well. As there is no overlap with any of the values in CT3, we write 0 below CT3 in the output dataframe.
Here are the dput of input and output:
> dput(input)
structure(list(CT1 = structure(1:3, .Label = c("chr1:200-400",
"chr1:800-970", "chr2:300-700"), class = "factor"), CT2 = structure(1:3, .Label = c("chr1:250-450",
"chr2:200-500", "chr2:600-1000"), class = "factor"), CT3 = structure(1:3, .Label = c("chr1:400-800",
"chr1:700-870", "chr2:700-1400"), class = "factor")), .Names = c("CT1",
"CT2", "CT3"), class = "data.frame", row.names = c(NA, -3L))
> dput(output)
structure(list(CT1 = c(1L, 1L, 1L, 1L, 1L, 0L, 0L, 0L, 0L), CT2 = c(1L,
0L, 1L, 1L, 1L, 1L, 0L, 1L, 1L), CT3 = c(0L, 0L, 0L, 0L, 0L,
1L, 1L, 1L, 1L)), .Names = c("CT1", "CT2", "CT3"), class = "data.frame", row.names = c("chr1:200-400",
"chr1:800-970", "chr2:300-700", "chr1:250-450", "chr2:200-500",
"chr2:600-1000", "chr1:400-800", "chr1:700-870", "chr2:700-1400"
))

Comment: So this is the exact copy of your other question?
Comment: Not the exact copy, there the rule was bit complicated, where I want `1` for only those overlaps which are more than 50% of the total range. Here I am asking only for the overlaps. If there is any overlap, assign 1.
Comment: 1. convert wide-to-long, 2. parse the strings into 3 columns "chr, start, end". 3.   split on CTs, 4. merge on overlap, [example1](https://stackoverflow.com/questions/23084322), [example2](https://stackoverflow.com/questions/24480031/roll-join-with-start-end-window) etc
Comment: you would need to define 'overlap' because I cannot understand the allocation of zeros and ones in your output - I would expect something else
Comment: @RolandASc Overlap between `input[1,1]` (200-400) and `input[1,2]` (250-400) is 150. Additinoally `chr` should be same, which is `chr1` in this case. And there is no overlap of `input[1,1]` region with any of the `input[,3]` regions as for chr1 they start from 400. Does it make sense now?
Comment: shouldn't row 2 CT3 be 1 then? or maybe this is the output table from your referenced first question with the 50% hurdle?
Comment: @RolandASc Yes, you are right. I have made the output compatible to this question.
Answer: A possible solution using the data.table-package:
# load the 'data.table'-package and convert 'input' to a data.table with 'setDT'
library(data.table)
setDT(input)

# reshape 'input' to long format and split the strings in 3 columns
DT <- melt(input, measure.vars = 1:3)[, c('chr','low','high') := tstrsplit(value, split = ':|-', type.convert = TRUE)
                                      , by = variable][]

# create aggregation function; needed in the ast reshape step
f <- function(x) as.integer(length(x) > 0)

# cartesian self join & reshape result back to wide format with aggregation function
DT[DT, on = .(chr, low < high, high > low), allow.cartesian = TRUE
   ][, dcast(.SD, value ~ i.variable, fun = f)]

which gives:

           value CT1 CT2 CT3
1:  chr1:200-400   1   1   0
2:  chr1:250-450   1   1   1
3:  chr1:400-800   0   1   1
4:  chr1:700-870   1   0   1
5:  chr1:800-970   1   0   1
6:  chr2:200-500   1   1   0
7:  chr2:300-700   1   1   0
8: chr2:600-1000   1   1   1
9: chr2:700-1400   0   1   1

Comment: Thanks a lot for suggesting a detailed solution. I think there is a problem here, for region `chr2:200-500`, it overlaps with `chr2:300-700` of `CT1` but the value in output is 0 for this.
Comment: @Newbie I thought the check for overlap should be done row. If I understand you correctly that isn't necessary. See the update. HTH
Comment: Now it is working fine. I think you removed the `rn` part in the update. Can you please suggest me how can I put one more condition for selecting the overlap. i.e. Assign 1 only when any one of the two ranges being compared is overlapping with more than 50% of its entire range. For example overlap between 200-400 & 300-450 will be considered one (actual overlap is 100 which is more than 50% of the entire 2nd range which is 150) but overlap between 200-400 & 350-550 will be considered 0.
Comment: @Newbie will try to look at it tonight
Comment: There is a problem with this code when I apply it on actual data of dimension (66186*23) which also contains NA. I get the results for first three columns only. I have checked the class of my actual input data and it is the same (`"data.table" "data.frame"`) as the input sample provided here. Can you please guide me what is going wrong here. Thank you.
Comment: I fixed it by changing `measure.vars = 1:23` and then deleting the NA values by `DT <- na.omit(DT)`
Comment: @Newbie It is probably better to use the `na.rm = TRUE` parameter inside `melt` than `na.omit` afterwards. [See also this answer for an example](https://stackoverflow.com/a/25856135/2204410).
Comment: @Newbie I haven't found the time to look at your other problem. Will do that tomorrow (or maybe this evening). I will definitely have time then.
Comment: I've got one answer for my that question (it is mentioned as an original question in the first line of this post). It works on given input sample but due to hard-coded variable names I couldn't apply it on actual data. Maybe its better to just look at that solution and suggest an edit to make it generalized, so that it can be directly applied to the input dataframe. Thanks.


Line graph in d3 rendering but not displaying

Question: I'm trying to build a line graph using D3 (in a React app built with webpack and react-faux-dom) and have everything except the line(s) displaying. Checking the dev tools there is a path rendering, but it seems to be off screen to the right (hovering the path pops path.line 141523000000 x 742.33 up, right correct height for data and what appears to be UTC milliseconds for the width) and I'm not sure why.
The x-axis is a time scale
const x = d3.scaleTime().range([0, width]);
const xAxis = d3.axisBottom(x).ticks(10).tickFormat(d3.timeFormat('%b %d, %Y'));

using
const parseTime = d3.timeParse('%Y-%m-%d');

for both the data
data.stocks.forEach((d) => {
  d.date = parseTime(d.date);
  d['GOOG'] = +d['GOOG'];
});

and the domain of the axis
x.domain(d3.extent(data.stocks, (d) => parseTime(d.date)));

If the x-axis is being set for a domain with numbers much smaller than the UTC milliseconds times I could the line being too far to the right to see on the chart, but they all convert with parseTime()  and the examples I've looked only use d3.timeFormat() so I haven't found the problem. Using a bunch of console logs it appears the data is getting through properly with
const valueline = d3.line()
  .x((d) => d.date)
  .y((d) => d['GOOG']);

svg.append('path')
  .data([data.stocks])
  .attr('class', 'line')
  .attr('d', valueline);

but I can't seem to change anything to get the lines on the chart. Anyone familiar with this and/or far more experienced with D3 to spot what's going on?
In case it's not glaringly obvious in the above, the full component is
import React from 'react';
import ReactFauxDOM from 'react-faux-dom';
import * as d3 from 'd3';

export default class StockChart extends React.Component {
  render() {
    const div = new ReactFauxDOM.Element('div');
    let stockMax;
    const rawData = this.props.data; // see below if needed
    const smallestDataSetSize = d3.min(rawData.map((stock) => stock.closingValues.length));
    const restrictingDataSet = rawData.filter((stock) => stock.closingValues.length === smallestDataSetSize)[0];
    const parseTime = d3.timeParse('%Y-%m-%d');
    const margin = {top: 20, right: 40, bottom: 70, left: 40}
    const width = window.innerWidth - margin.left - margin.right;
    const height = window.innerHeight - margin.top - margin.bottom - 75*2;
    const x = d3.scaleTime().range([0, width]);
    const y = d3.scaleLinear().range([height, 0]);
    const xAxis = d3.axisBottom(x).ticks(10).tickFormat(d3.timeFormat('%b %d, %Y'));
    const yAxis = d3.axisLeft(y).ticks(5);

    // Get prelimiary data to set up chart
    stockMaximums = rawData.map((stock) => d3.max(stock.closingValues.map((d) => parseInt(d.price))));
    stockMax = d3.max(stockMaximums);

    // Fromat data into a JSON format that can be used with D3
    const data = { stocks: []};
    for (let i = smallestDataSetSize - 1; i > -1; i--) {
      const date = restrictingDataSet.closingValues[i].date;
      data.stocks.push({
        'date': date
      });
      rawData.map((stock) => {
        const stockData = stock.closingValues.filter((stockData) => stockData.date === date);
        data.stocks[data.stocks.length - 1][stock.name] = parseFloat(stockData[0].price);
      });
    }

    // Draw the plot
    let svg = d3.select(div).append('svg')
      .attr('width', width + margin.left + margin.right)
      .attr('height', height + margin.bottom + margin.top)
      .append('g')
      .attr('transform', `translate(${margin.left}, ${margin.top})`);

    x.domain(d3.extent(data.stocks, (d) => parseTime(d.date)));
    y.domain([0, stockMax*11/10]);

    svg.append('g')
      .attr('transform', `translate(0, ${height})`)
      .call(xAxis)
      .selectAll('text')
        .style('text-anchor', 'end')
        .attr('dx', '-1rem')
        .attr('dy', '-.2rem')
        .attr('transform', 'rotate(-65)');

    svg.append('g')
      .call(yAxis);

    // Just trying one line right now while debugging
    const valueline = d3.line()
      .x((d) => d.date)
      .y((d) => d['GOOG']);

    data.stocks.forEach((d) => {
      d.date = parseTime(d.date);
      d['GOOG'] = +d['GOOG'];
    });

    svg.append('path')
      .data([data.stocks])
      .attr('class', 'line')
      .attr('d', valueline);

    return div.toReact();
  }
}

and the only CSS at the moment
.line {
    fill: none;
    stroke: steelblue;
    stroke-width: 2;
}

with sample data
const rawData = {
    closingValues: [
        { date: "2018-09-28", price: "1193.4700" },
        { date: "2018-09-21", price: "1166.0900" },
        { date: "2018-09-14", price: "1172.5300" },
        { date: "2018-09-07", price: "1164.8300" },
        { date: "2018-08-31", price: "1218.1900" },
        { date: "2018-08-24", price: "1220.6500" },
        { date: "2018-08-17", price: "1200.9600" },
        { date: "2018-08-10", price: "1237.6100" },
        { date: "2018-08-03", price: "1223.7100" },
        { date: "2018-07-27", price: "1238.5000" },
        { date: "2018-07-20", price: "1184.9100" },
        { date: "2018-07-13", price: "1188.8200" },
        { date: "2018-07-06", price: "1140.1700" },
        { date: "2018-06-29", price: "1115.6500" },
        { date: "2018-06-22", price: "1155.4800" },
        { date: "2018-06-15", price: "1152.2600" },
        { date: "2018-06-08", price: "1120.8700" },
        { date: "2018-06-01", price: "1119.5000" },
        { date: "2018-05-25", price: "1075.6600" },
        { date: "2018-05-18", price: "1066.3600" },
        { date: "2018-05-11", price: "1098.2600" },
        { date: "2018-05-04", price: "1048.2100" },
        { date: "2018-04-27", price: "1030.0500" },
        { date: "2018-04-20", price: "1072.9600" },
        { date: "2018-04-13", price: "1029.2700" },
        { date: "2018-04-06", price: "1007.0400" },
        { date: "2018-03-29", price: "1031.7900" },
        { date: "2018-03-23", price: "1021.5700" },
        { date: "2018-03-16", price: "1135.7300" },
        { date: "2018-03-09", price: "1160.0400" },
        { date: "2018-03-02", price: "1078.9200" },
        { date: "2018-02-23", price: "1126.7900" },
        { date: "2018-02-16", price: "1094.8000" },
        { date: "2018-02-09", price: "1037.7800" },
        { date: "2018-02-02", price: "1111.9000" },
        { date: "2018-01-26", price: "1175.8400" },
        { date: "2018-01-19", price: "1137.5100" },
        { date: "2018-01-12", price: "1122.2600" },
        { date: "2018-01-05", price: "1102.2300" },
        { date: "2017-12-29", price: "1046.4000" },
        { date: "2017-12-22", price: "1060.1200" },
        { date: "2017-12-15", price: "1064.1900" },
        { date: "2017-12-08", price: "1037.0500" },
        { date: "2017-12-01", price: "1010.1700" },
        { date: "2017-11-24", price: "1040.6100" },
        { date: "2017-11-17", price: "1019.0900" },
        { date: "2017-11-10", price: "1028.0700" },
        { date: "2017-11-03", price: "1032.4800" },
        { date: "2017-10-27", price: "1019.2700" },
        { date: "2017-10-20", price: "988.2000" },
        { date: "2017-10-13", price: "989.6800" },
        { date: "2017-10-06", price: "978.8900" },
        { date: "2017-09-29", price: "959.1100" },
        { date: "2017-09-22", price: "928.5300" },
        { date: "2017-09-15", price: "920.2900" },
        { date: "2017-09-08", price: "926.5000" },
        { date: "2017-09-01", price: "937.3400" },
        { date: "2017-08-25", price: "915.8900" },
        { date: "2017-08-18", price: "910.6700" },
        { date: "2017-08-11", price: "914.3900" },
        { date: "2017-08-04", price: "927.9600" },
        { date: "2017-07-28", price: "941.5300" },
        { date: "2017-07-21", price: "972.9200" },
        { date: "2017-07-14", price: "955.9900" },
        { date: "2017-07-07", price: "918.5900" },
        { date: "2017-06-30", price: "908.7300" },
        { date: "2017-06-23", price: "965.5900" },
        { date: "2017-06-16", price: "939.7800" },
        { date: "2017-06-09", price: "949.8300" },
        { date: "2017-06-02", price: "975.6000" },
        { date: "2017-05-26", price: "971.4700" },
        { date: "2017-05-19", price: "934.0100" },
        { date: "2017-05-12", price: "932.2200" },
        { date: "2017-05-05", price: "927.1300" },
        { date: "2017-04-28", price: "905.9600" },
        { date: "2017-04-21", price: "843.1900" },
        { date: "2017-04-13", price: "823.5600" },
        { date: "2017-04-07", price: "824.6700" },
        { date: "2017-03-31", price: "829.5600" },
        { date: "2017-03-24", price: "814.4300" },
        { date: "2017-03-17", price: "852.1200" },
        { date: "2017-03-10", price: "843.2500" },
        { date: "2017-03-03", price: "829.0800" },
        { date: "2017-02-24", price: "828.6400" },
        { date: "2017-02-17", price: "828.0700" },
        { date: "2017-02-10", price: "813.6700" },
        { date: "2017-02-03", price: "801.4900" },
        { date: "2017-01-27", price: "823.3100" },
        { date: "2017-01-20", price: "805.0200" },
        { date: "2017-01-13", price: "807.8800" },
        { date: "2017-01-06", price: "806.1500" },
        { date: "2016-12-30", price: "771.8200" },
        { date: "2016-12-23", price: "789.9100" },
        { date: "2016-12-16", price: "790.8000" },
        { date: "2016-12-09", price: "789.2900" },
        { date: "2016-12-02", price: "750.5000" },
        { date: "2016-11-25", price: "761.6800" },
        { date: "2016-11-18", price: "760.5400" },
        { date: "2016-11-11", price: "754.0200" },
        { date: "2016-11-04", price: "762.0200" }
    ],
    id: "-LNgk1Gxv0RFmJbiYgnx",
    lastUpdated: "2018-09-28",
    name: "GOOG"
};

Comment: instead of `.data` use `.datum` or just `.attr('d', valueline(data.stocks))`
Comment: @rioV8 Both different approaches seem to render the same way unfortunately
Answer: the problem with the code is the use of the scales and the parsing of the data.

best to do the parsing as soon as possible so you only have to do it once.
apply the x and y scales in the calculation of the line
const valueline = d3.line()
  .x((d) => x(d.date))
  .y((d) => y(d['GOOG']));

the whole code is (only the inner part because I used an HTML file to debug)
const smallestDataSetSize = d3.min(rawData.map((stock) => stock.closingValues.length));
const restrictingDataSet = rawData.filter((stock) => stock.closingValues.length === smallestDataSetSize)[0];
const parseTime = d3.timeParse('%Y-%m-%d');
let svgWidth = window.innerWidth;
let svgHeight = window.innerHeight - 75*2;
const margin = {top: 20, right: 40, bottom: 70, left: 40}
const width = svgWidth - margin.left - margin.right;
const height = svgHeight - margin.top - margin.bottom;
const x = d3.scaleTime().range([0, width]);
const y = d3.scaleLinear().range([height, 0]);
const xAxis = d3.axisBottom(x).ticks(10).tickFormat(d3.timeFormat('%b %d, %Y'));
const yAxis = d3.axisLeft(y).ticks(5);

// Get prelimiary data to set up chart
var stockMaximums = rawData.map((stock) => d3.max(stock.closingValues.map((d) => parseInt(d.price))));
var stockMax = d3.max(stockMaximums);

// Fromat data into a JSON format that can be used with D3
const data = { stocks: []};
for (let i = smallestDataSetSize - 1; i > -1; i--) {
  const date = restrictingDataSet.closingValues[i].date;
  data.stocks.push({
    'date': date
  });
  rawData.map((stock) => {
    const stockData = stock.closingValues.filter((stockData) => stockData.date === date);
    data.stocks[data.stocks.length - 1][stock.name] = parseFloat(stockData[0].price);
  });
}

data.stocks.forEach((d) => {
  d.date = parseTime(d.date);
  d['GOOG'] = +d['GOOG'];
});

// Draw the plot
let svg = d3.select(div).append('svg')
  .attr('width', svgWidth)
  .attr('height', svgHeight)
  .append('g')
  .attr('transform', `translate(${margin.left}, ${margin.top})`);

// x.domain(d3.extent(data.stocks, (d) => parseTime(d.date)));
x.domain(d3.extent(data.stocks, (d) => d.date));
y.domain([0, stockMax*11/10]);

svg.append('g')
  .attr('class', 'x axis')
  .attr('transform', `translate(0, ${height})`)
  .call(xAxis)
  .selectAll('text')
    .style('text-anchor', 'end')
    .attr('dx', '-1rem')
    .attr('dy', '-.2rem')
    .attr('transform', 'rotate(-65)');

svg.append('g')
  .attr('class', 'y axis')
  .call(yAxis);

// Just trying one line right now while debugging
const valueline = d3.line()
  .x((d) => x(d.date))
  .y((d) => y(d['GOOG']));

svg.append('path')
  .attr('class', 'line')
  .attr('d', valueline(data.stocks));

Comment: @Alex you are walking the array from end till start because the date is going backwards (??), the line does not mind if the `x` is descending
Comment: @Alex why don't you sort the `restrictingDataSet.closingValues` based on `date` and then simply apply a `.map()` to convert to the data records with the 'GOOG' field
Comment: The data is always sorted when I fetch it, so with the full plot (with any number of lines) I have a forEach loop over rawData to create each line with a `.map()` over the data. I'm guessing this is the idea you have, but I wrote the single (debugging) example following another example online hoping that starting with something that did work would help me find what I had missing.
Comment: Oh, fair enough, the point is a point regardless of the order they are in. I was going backwards because the data is always fetched in reverse chronological order (and wanted it in chronological order, though as you mention that's not important). It's not end to start though, as not all of the stocks have the same amount of data, so I use the `smallestDataSetSize`, so the loop picks only the data where all the stocks have a closing price.


Is it worth it to replace hollow-core interior doors with solid core doors?

Question: I bought a house built in 1970 which still has the original interior doors.  They are hollow-core, boring, brown doors.  I am debating whether to simply paint them white or replace them with new pre-hung 6-panel doors.
So I am wondering if more value would be added by going with solid-core doors instead of hollow-core (enough to justify the added expense).  To my untrained eye, I can't tell the difference by simply looking at a door whether it's hollow or solid.
Secondly, I know that solid-core doors do have some sound-dampening attributes that can be useful between rooms, but does it make any sense to replace a hallway closet door with a solid-core?
Comment: I'd like to know the answer to that too.
Comment: I'm surprised no answers have graphs or data. I'd love me some data!
Answer: The differences between the types of doors is pretty obvious in use:
SOLID CORE DOORS

Mimics the appearance and feel of a solid wood door
Muffles sound better
Heavier and slams better

HOLLOW CORE DOORS

Lighter and easier to handle than a real wood door
Cheaper?

Jeld-wen says:

Hollow core doors are a good choice for areas where sound transmission is less important, like a closet or pantry.
Solid Core doors are heavier and more resistant to normal wear. Solid core doors are commonly used in areas where more privacy is preferred. If interior noise reduction is a priority, consider the JELD-WEN® ProCore The Quiet Door®, which reduces sound transmission by up to 50 percent when compared to a hollow flush door.
Answer: The other answers talk about the direct benefits.  The question seems to imply an additional interest in the effect on resale value, so I'll try to focus on that.  There are several aspects to resale value.
One is things that are recognized by appraisers and tax officials as directly affecting the baseline market value.  This is stuff like square footage, number of rooms of different kinds, type of construction, age, relative valuations of similar houses nearby, etc.  The type of doors doesn't matter there.  On appraisals, there is often an adjustment for things like quality of finishes and materials, and general condition, but it is in the aggregate.  Door type won't really help or hurt there, either.
Another effect on resale value is "saleability".  These are qualities that make the house seem desirable to a buyer, perhaps influencing whether you get an offer, or how many offers you get.  These might even tip the scale a little on what a buyer is willing to pay.
There are big influencers and little influencers, and the little influencers don't matter unless you get past the big ones.  The big ones are things like location, curb appeal, how move-in ready it is, and how well cared for it appears.
The little influencers are things like cool features and the quality of workmanship and materials; is everything bottom-of-the-line builder's grade or something better?  Potential buyers will notice decent doors because they feel more substantial.  The doors will add to the sense of quality.
But a caveat--they need to be generally consistent with the grade and quality of other things in order to matter for resale value.  You can't take a simple and plain, inexpensive, cookie cutter house, just stick elaborate crown molding in the living room, and expect that molding to affect the price.  The quality of materials, finishes, and workmanship are assessed in the aggregate.  One item that is inconsistent with everything else stands out like a flag.  A high-end item that's out of place with everything else can even call attention to everything else looking cheap.
So, like many improvements, good doors might affect resale value positively if they are consistent with the quality of other things in the house or part of a general upgrade program.  Don't do it as an "investment", expecting them to return their cost at resale.  Base a replacement decision on whatever benefits and satisfaction they will provide to you while you live there and consider any effect on resale just gravy.
Answer: You have hollow core doors, solid wood doors, and solid core doors. Solid core doors are heavier than solid wood doors so are the best choice for sound reduction for an inside door. Simple soundproofing rule is more mass (dense weight per sq. foot) = more sound blocked. They are also cheaper than solid wood doors but not cheaper than hollow doors but if sound reduction is what you're after solid core doors are worth the money.
Answer: Check with your home owners insurance... I'm fairly sure solid core get a lower rate due to being better/safer during fires...with discount on insurance they may be cheaper than you think
The value of the home should go up also.
And if you want more sound reducing... You know the expanding spray foam-dont get it at a big store...get it from a dollar store...often its same type and brand-
Find wall studs drill very small hole just enough for tub & fill the walls. Better soundproofing,lower heating and cooling costs.
Comment: +1 for mentioning the major difference - fire performance.
Answer: Trust me, solid doors are much more valuable. You will know the difference the first time you close one!  Short answer, no more need be said.


custom fields and post types for Ghost

Question: Does an equivalent of Wordpress "post types" and the Advanced Custom Fields plugin exist for Ghost?
As one example, I built a travel site that has multiple Trips (a custom post type), and each trip has various serialized itinerary destinations, tour guides, etc. Another example would be designer portfolios, where they might have a Projects post type, which contains serialized images, each with its own description and perhaps a date stamp or client or whatever.
Answer: Not supported and probably never will be. Seems like this doesn't have high priority in their team.
See: https://forum.ghost.org/t/custom-fields-for-posts/1124/46 and https://github.com/TryGhost/Ghost/issues/9020

custom fields and post types for Ghost


How to get device ip - Expo React Native

Question: How can I get the ip of the device using React Native and Expo,
I'm trying this and all I see on the alert is [object promise].
I'm running the app on an emulator and on the browser..
import * as Network from 'expo-network';
alert(Network.getIpAddressAsync());

Answer: Network.getIpAddressAsync() returns a Promise, so you need to resolve it first.
import * as Network from 'expo-network';

const ipAlert = async () => {
  const ip = await Network.getIpAddressAsync()
  alert(ip);
};

ipAlert();

Answer: As it is written in the documentation, the method Network.getIpAddressAsync() returns a Promise that resolves to a String of the current IP address of the device's main network interface.
Due to this fact, you need to wait for the promise to finish as it is asynchronous.
You can do so by either attaching the await keyword before it, like this:
await Network.getIpAddressAsync();

or by chaining a then function afterwards, like so:
Network.getIpAddressAsync().then(function(address) {
//Your logic here
 });


Plasterboard on roof rafters. Is this okay?

Question: I am looking to convert the eaves of my loft into storage space. I plan to lay chipboard floor panels over the joists below, but not sure how to best cover the exposed sloping rafters above. I was thinking I could just screw plasterboard across the rafters and screw them on with plasterboard screws. Would there be any issues in doing this? I don't plan to put any insulation between the rafters.
Thanks.
Comment: Not covering them at all is pretty standard in uninsulated attic storage.
Comment: Okay but it's pretty dusty up there and want to make it nicer for storing stuff in the eves.
Comment: Is there insulation between the ceiling joists? (I understand you're not going to add insulation between the roof joists.)
Answer: There is nothing wrong with installing drywall on the rafters. You mentioned it's pretty dusty up there, keep in mind the that dust is coming from the soffit vents and will continue to do so after the drywall is installed. You don't want to block off the soffit vents. Not sure where you live but if it's in a hot climate, do yourself a favor and wait until October to do the work. Good luck.


trigonometric representation of a complex number.

Question: Let $z=e^{it}+1$ where $0\leq t\leq \pi$, Find the trigonometric representation of $z^2+z+1$.
(The trigonometric representation should be in the form of : $r(\cos \theta +i \sin \theta)$, where $r,\theta \in \mathbb{R}$ and $r>0$.

What I have done : $$z^2+z+1=e^{2it}+3z=(\cos (t)+i \sin (t)) (-2 i \sin (t)+4 \cos (t)+3).$$
The problem is that the expression in the right bracket is not real always.
Comment: Why would you expect the right expression to be real?
Comment: No of course, just $r,\theta$ should be real.
Answer: The complex number $a+bi$ can be written in trigonometric form as
$$a+bi=\sqrt{a^{2}+b^{2}}(\cos \theta +i\sin \theta ),\qquad\text{with } \tan \theta =\frac{b}{a}.$$
For $z=e^{it}+1=(\cos t+1)+i\sin t$  we have
\begin{eqnarray*}
z^{2}+z+1 &=&\left( e^{it}+1\right) ^{2}+(e^{it}+1)+1= (e^{i2t}+2e^{it}+1)+(e^{it}+1)+1 \\
&=&e^{2it}+3e^{it}+3 \\
&=&((\cos 2t+1)+i\sin 2t)+3\left( (\cos t+1)+i\sin t\right) +3 \\
&=&(\cos 2t+3\cos t+3)+i\left( \sin 2t+3\sin t\right)  \\
&=&u+iv,\qquad u=\cos 2t+3\cos t+3,v=\sin 2t+3\sin t \\
&=&r\left( \cos \theta +i\sin \theta \right) ,
\end{eqnarray*}
where
\begin{eqnarray*}
r &=&\sqrt{u^{2}+v^{2}}=\sqrt{(\cos 2t+3\cos t+3)^{2}+\left( \sin 2t+3\sin
t\right) ^{2}} \\
\tan \theta  &=&\frac{v}{u}.
\end{eqnarray*}
For $0\leq t\leq \pi ,v=\sin 2t+3\sin t\geq 0$ and $u=\cos 2t+3\cos t+3\geq 0
$. So
$$
\begin{equation*}
\theta =\arctan  \frac{v}{u} =\arctan \left( \frac{\sin
2t+3\sin t}{\cos 2t+3\cos t+3}\right) \geq 0,
\end{equation*}
$$
because $w=z^2+z+1=u+iv=\operatorname{Re}(w)+i\operatorname{Im}(w)$ is in the first quadrant.
Plots of $u,v$:

$$u=\cos 2t+3\cos t+3 \text{ (blue) },\quad v=\sin 2t+3\sin t \text{ (red) },\quad 0\leq t\leq \pi.$$
Answer: Another approach, perhaps a little more elementary:
$$a^3-b^3=(a-b)(a^2+ab+b^2)\implies a^2+ab+b^2=\frac{a^3-b^3}{a-b}$$
Well, now just put $\,a=z\;,\;b=1\,$ above , and get
$$z^2+z+1=\frac{z^3-1}{z-1}$$
and since $\,z=e^{it}+1\,$ , we get
$$z^2+z+1=\frac{(e^{it}+1)^3-1}{e^{it}}=e^{2it}+3e^{it}+3=$$
$$=(\cos 2t+3\cos t+3)+(\sin 2t+3\sin t)i$$


What's a really good pattern to extract logic from models and have the results persisted to the db?

Question: I've been experimenting with different ways of structuring my app, and particularly with ActiveRecord-based models, looking into the notion of having a separate class whose results are saved as a single field. Now composition might have worked, but there's been a lot of discussion on whether its staying or not, so I was wondering what alternatives you might have.
Example:
class Gadget < ActiveRecord::Base

  attr_accessor: lights

end

Now, I would like the lights property to be 'managed' by a completely separate class:
class Lights

  def doSomething
  end

  def doSomethingElse
  end

end

What's a good way of, say, proxying or delegating this logic out of the ActiveRecord model and into the Lights class in order to transparently store the results?
e.g. using an instance of the Lights class as the lights property - but that won't work, since there's no association, right?
e.g. use method_missing to push all requests out to the lights instance - but that won't work either, because it won't be persisted to the database.
Maybe it's not possible, but I'm interested in ways of persisting the results of logical operations. All suggestions welcome.
Answer: What about something like:
class Gadget < ActiveRecord::Base

  def lights
    @lights ||= Lights.new(self)
  end

end

class Lights
  attr_reader :root
  delegate :save, :save!, to: :root

  def initialize(root)
    @root = root
  end

  def doSomething
  end

  def doSomethingElse
  end

  def method_missing(method_name, *args, &block)
    #delegate all setters to root
    if method_name =~ /.*=$/
      root.send(method_name, *args, &block)
    else
      super
    end
  end
end

Thus you can do:
gadget = Gadget.new
#say gagdet has a name column
gadget.lights.name = 'foo'
gadget.lights.save
gadget.name #=> 'foo'

Still unsure why you need it but it should work
Comment: This looks quite neat, will run it shortly. The idea was that the property of the object could become an object in its own right outside of an active record association, and so on create/update, the property could simply deal with its own processing and save its state in the parent's model. There's a number of reasons for it outside of my own interest, which are around being able to swap out the logic transparently for the Light class - which could be doing all sorts of things - e.g. blinking, flashing, strobing - and saving its state in the parent without the parent having to care too much.
Comment: This works quite well - after a minor fix above. It'd be good to see if we can make this pattern work without having to stick too many delegates in (in this instance we have to delegate :save and :save! and this could get unwieldy.


How to reverse integers using while or for loop

Question: Sorry, I am new to java. I want to create a program that displays reversed integers using any kind of loop. For example I would ask user to enter a positive integer and then I would return reversed input to the user. So far this is the closest I got, but I get the count of the string in reverse and not the values that were captured.
String number;

for (int c = number.length(); c >= 0; c--) {
    System.out.print(c);
}

Comment: Please post an example input, and the desired output.
Comment: @Berger - Why?  It's clear from the question.  If the input is 1234, the output should be 4321.
Comment: @Jared - do you know about the `charAt` method of the `String` class?
Comment: @David Wallace Okay, the "reversed integer" part puzzled me :)
Answer: String number;

for (int c = number.length() - 1; c >= 0; c--){
    System.out.print(number.charAt(c));
}

This should do the trick. c is the position in your string, use it to print the char at that position.
(Also, remember it's String, not string. Same for System)
Edit: Oops, forgot to add the "-1" in number.length()
Answer: You can try something likewise(either of way),
public static void main(String[] args) {
        String number = "hello";

        for (int c = number.length()-1; c >= 0; c--)
        {
            System.out.print(number.charAt(c));
        }
        // At the end output is : olleh

        System.out.println();
        // Or another way is, using StringBuffer
        StringBuffer sb = new StringBuffer("Hello String");
        System.out.println(sb.reverse()); //Output :- gnirtS olleH

    }

Comment: The gif is completely unnecessary!
Comment: @weston Why is it unnecessary? Does it decrease value of the whole answer? It even weighs ~300 kB so it will work good with poor internet connection.
Comment: "Why is it unnecessary?" Because it shows you running the code!
Comment: "Does it decrease value of the whole answer?" Yes, because it is a repeat of the code, and seeing it run adds nothing. I think anything that adds nothing, can only take away. Best answers are **succinct**.
Comment: It could be worse.  There could be sound effects.
Comment: @DavidWallace what you mean ? may i know better than this which will hone my skill up ?thanks


jquerymobile how to bind and unbind a link?

Question: In my mobilejquery project, I need to unbind the links (hrefs), and bind them a point, for that, I use this code:
<code>$(document).bind('pageinit', function () {

    $('a[href="#"], a.disabled').bind('click',function (e) {
        e.preventDefault();    //sets all dynamic href to prevents wrong url
    } )
});
</code>
but not at all works... anything wrong with my code?
Additional question..
I don't want to show the url path in the navigator.. is there any way to make the url path not to show?
Answer: did you try using the unbind() method?
<code>$('a[href="#"], a.disabled').unbind("click").bind('click',function (e) {
   e.preventDefault();    //sets all dynamic href to prevents wrong url
} )
</code>


Flutter: how to hide Cursor's "belly" on textfield

Question: Whenever the user clicks on textfield in order to change it, the cursor appears and so it's so-called "belly" (I don't what's it called actually, see picture below - red arrow). I want to enable interactive selection (i.e. enabling to move the cursor alongside the text field), and to show the blinking cursor on edit, but I want that so-called cursor's to not appear.

here is my code:
TextField(
    enableInteractiveSelection: true,
    showCursor: true,
    autofocus: false,
    decoration: InputDecoration(
        isDense: true,
        enabledBorder: OutlineInputBorder(
            borderSide: BorderSide(color: Colors.grey),
            borderRadius: BorderRadius.all(Radius.circular(30))
        ),
        focusedBorder: OutlineInputBorder(
            borderSide: BorderSide(color: Colors.grey),
            borderRadius: BorderRadius.all(Radius.circular(30))
        ),
    ),
    onChanged: (text) => {},
    textAlign: TextAlign.center,
    controller: _firstNameChanged
       ? (_firstNameController..text = _newFirstName)
       : (_firstNameController..text = userRep.firstName),
    inputFormatters: [
       FilteringTextInputFormatter.allow(RegExp('[a-zA-Z]'))
    ],
    focusNode: _firstNameInputFocusNode,
    onSubmitted: (text) {
       if(text.isNotEmpty) {
          setState(() {
            _newFirstName = text;
            _firstNameChanged = true;
          });
       }
    },
    style: GoogleFonts.lato(
       fontSize: 16.0,
       color: Colors.black,
    )
)

Any ideas, please?
Comment: https://stackoverflow.com/questions/65247744/how-to-remove-text-field-cursor-bubble-in-flutter/65248206#65248206
Answer: Thanks to @Dude comment, I was finally able to solve this according to this answer.
full code:
@override
Widget build(BuildContext context) {
  return MaterialApp(
    title: 'Flutter Demo',
    theme: ThemeData(
      textSelectionHandleColor: Colors.transparent, /// <- Added
      cursorColor: Colors.lightGreen[800],
      primaryColor: Colors.green,
      accentColor: Colors.lightGreen[800],
      fontFamily: 'NewRomanTimes',
      textTheme: TextTheme(
        headline1: TextStyle(fontSize: 72.0, fontWeight: FontWeight.bold),
        headline6: TextStyle(fontSize: 36.0, fontStyle: FontStyle.italic),
      )
    ),
    home: MyHomePage()
  );
}

Answer: The accepted answer is probably outdated, as of 2022 this is how you change color to the handle and selection (you can use Colors.transparent to hide it alltogether) :
ThemeData().copyWith(
              textSelectionTheme:
TextSelectionThemeData(
   selectionColor: Colors.yellow[900],
   selectionHandleColor: Colors.yellow[900])
)


Show that the function is an eigenfunction of the equation

Question: I'm not sure how to use the bbcode so I've taken a screenshot instead:

Came up on a past exam paper that I'm working towards and I'm not sure how to answer it.
I assumed that EQN . EIGENFUNCTION = EIGENVECTOR . EIGENFUNCTION
(from ef definition)
But it doesn't cancel out to a constant for eigenvector value.
Appreciate any help!
Endnote: The question continues:

And I'm not 100% sure about that either.
Again, thank you!
Comment: Here is [a related problem](http://math.stackexchange.com/questions/247730/consider-the-following-sturm-liouville-problem/247836#247836).
Answer: $$(\sin\lambda_nx)'=\lambda_n\cos\lambda_nx$$
$$(\sin\lambda_nx)'=-\lambda_n^2\sin\lambda_nx$$
So putting $\,\psi(x):=\sin\lambda_nx\,$ , we easily find the above are solutions to the given differential equation, and in order to have $\,\psi(1)=0\,$ we must choose $\,\lambda_n=k_n\pi\,\,,\,\,k_n\in\Bbb Z\,$
Comment: That happens to us all now and then. Don't worry.
Comment: Thank you! I was making a mountain out of a molehill.
Answer: The eigenfunctions result from the boundary conditions.  The generic solution to the differential equation is
$$ \psi(x) = A \cos{\lambda x} + B \sin{\lambda x} $$
We then apply the boundary condition $\psi(0) = 0$ and get
$$A \cos{0} + B \sin{0} = A = 0$$
The boundary condition $\psi(1) = 0$ implies that
$$B \sin{\lambda} = 0$$
We assume that $B \ne 0$.  This latter equation puts a condition on the values of $\lambda$:
$$\sin{\lambda} = 0 \implies \lambda = n \pi \; \forall n \in \mathbb{Z}$$
We then may define $\lambda_n = n \pi$ as an eigenvalue of the differential operator defined above (the equation plus the boundary conditions).  The general solution to this equation is a linear combination of eigenfunctions, that is, $\psi_n(x) = \cos{\lambda_n x}$.
By the way, maybe I am missing something, but (c) makes no sense to me, as $1-x$ does not satisfy the boundary conditions satisfied by the eigenfunctions $\psi_n(x)$.
Comment: Already fixed it, but thanks anyway.
Comment: I think you should have $\psi(1)=B\sin\lambda$, where you have $\cos$.
Comment: @iampearce: Does my concern about (c) make sense to you?  Not sure how one expands $1-x$ over $[0,1]$ using those eigenfunctions to make any sensible approximation.
Comment: It does, but unfortunately I can't get hold of the tutor who set the exam in order to query it. I will ask as soon as I can, though - thank you again for your help.


Action Button showing up but not overflow menu in Android actionbar

Question: I am a new developer and trying to show action buttons and overflow menu. 4/6 buttons show in actionBar but i cant see overflow menu with other buttons. Following is the code
res/menu/menu/menu_activity_action.xml
<code><menu  xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:myapp="http://schemas.android.com/apk/res-auto" >
    <item
        android:id="@+id/phone"
        android:title="@string/phone"
        android:icon="@drawable/phone"
        and
        myapp:showAsAction="ifRoom|withText"
    />

    <item
        android:id="@+id/computer"
        android:title="@string/computer"
        android:icon="@drawable/computer"
        myapp:showAsAction="ifRoom|withText"
    />

    <item
        android:id="@+id/gamepad"
        android:title="@string/gamepad"
        android:icon="@drawable/gamepad"
        myapp:showAsAction="ifRoom|withText"
    />

    <item
        android:id="@+id/camera"
        android:title="@string/camera"
        android:icon="@drawable/camera"
        myapp:showAsAction="ifRoom|withText"
    />

    <item
        android:id="@+id/video"
        android:title="@string/video"
        android:icon="@drawable/video"
        myapp:showAsAction="ifRoom|withText"
    />

    <item
        android:id="@+id/email"
        android:title="@string/email"
        android:icon="@drawable/email"
        myapp:showAsAction="ifRoom|withText"
    />
</menu>
</code>
mainActivity :
<code>@Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu items for use in the action bar
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.menu_activity_action,menu);
        return super.onCreateOptionsMenu(menu);
    }
</code>
Any idea ??
Answer: Try changing to:
<code>@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.menu_activity_action, menu);

    return true;
}
</code>
Answer: <code>@Override
public boolean onCreateOptionsMenu(Menu menu)
{
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.menu_activity_action, menu);
    return true;
}
</code>


Is there a better more readable way to coalese columns in pandas

Question: I often need a new column that is the best I can achieve from other columns and I have a specific list of preference priorities.  I am willing to take the first non null value.
def coalesce(values):
    not_none = (el for el in values if el is not None)
    return next(not_none, None)

df = pd.DataFrame([{'third':'B','first':'A','second':'C'},
                   {'third':'B','first':None,'second':'C'},
                   {'third':'B','first':None,'second':None},
                   {'third':None,'first':None,'second':None},
                   {'third':'B','first':'A','second':None}])

df['combo1'] = df.apply(coalesce, axis=1)
df['combo2'] = df[['second','third','first']].apply(coalesce, axis=1)
print df

Results
  first second third combo1 combo2
0     A      C     B      A      C
1  None      C     B      C      C
2  None   None     B      B      B
3  None   None  None   None   None
4     A   None     B      A      B

this code works (and the result are what I want) but it is not very fast.
I get to pick my priorities if I need to [['second','third','first']]
Coalesce somewhat like the function of the same name from tsql.
I suspect that I may have overlooked an easy way to achieve it with good performance on large DataFrames (+400,000 rows)
I know there are lots of ways to fill in missing data which I often use on axis=0
this is what makes me think I may have missed an easy option for axis=1
Can you suggest something nicer/faster...  or confirm that this is as good as it gets.
Answer: The Pandas equivalent to COALESCE is the method fillna():
result = column_a.fillna(column_b)

The result is a column where each value is taken from column_a if that column provides a non-null value, otherwise the value is taken from column_b. So your combo1 can be produced with:
df['first'].fillna(df['second']).fillna(df['third'])

giving:
0       A
1       C
2       B
3    None
4       A

And your combo2 can be produced with:
(df['second']).fillna(df['third']).fillna(df['first'])

which returns the new column:
0       C
1       C
2       B
3    None
4       B

If you wanted an efficient operation called coalesce, it could simply combine columns with fillna() from left to right and then return the result:
def coalesce(df, column_names):
    i = iter(column_names)
    column_name = next(i)
    answer = df[column_name]
    for column_name in i:
        answer = answer.fillna(df[column_name])
    return answer

print coalesce(df, ['first', 'second', 'third'])
print coalesce(df, ['second', 'third', 'first'])

which gives:
0       A
1       C
2       B
3    None
4       A

0       C
1       C
2       B
3    None
4       B

Comment: great answer .   .
Answer: You could use pd.isnull to find the null -- in this case None -- values:
In [169]: pd.isnull(df)
Out[169]:
   first second  third
0  False  False  False
1   True  False  False
2   True   True  False
3   True   True   True
4  False   True  False

and then use np.argmin to find the index of the first non-null value. If all the values are null, np.argmin returns 0:
In [186]: np.argmin(pd.isnull(df).values, axis=1)
Out[186]: array([0, 1, 2, 0, 0])

Then you could select the desired values from df using NumPy integer-indexing:
In [193]: df.values[np.arange(len(df)), np.argmin(pd.isnull(df).values, axis=1)]
Out[193]: array(['A', 'C', 'B', None, 'A'], dtype=object)

For example,
import pandas as pd
df = pd.DataFrame([{'third':'B','first':'A','second':'C'},
                   {'third':'B','first':None,'second':'C'},
                   {'third':'B','first':None,'second':None},
                   {'third':None,'first':None,'second':None},
                   {'third':'B','first':'A','second':None}])

mask = pd.isnull(df).values
df['combo1'] = df.values[np.arange(len(df)), np.argmin(mask, axis=1)]
order = np.array([1,2,0])
mask = mask[:, order]
df['combo2'] = df.values[np.arange(len(df)), order[np.argmin(mask, axis=1)]]

yields
  first second third combo1 combo2
0     A      C     B      A      C
1  None      C     B      C      C
2  None   None     B      B      B
3  None   None  None   None   None
4     A   None     B      A      B

Using argmin instead of df3.apply(coalesce, ...) is significantly quicker if the DataFrame has a lot of rows:
df2 = pd.concat([df]*1000)

In [230]: %timeit mask = pd.isnull(df2).values; df2.values[np.arange(len(df2)), np.argmin(mask, axis=1)]
1000 loops, best of 3: 617 µs per loop

In [231]: %timeit df2.apply(coalesce, axis=1)
10 loops, best of 3: 84.1 ms per loop

Answer: df1 = pd.DataFrame([{'third':'B','first':'A','second':'C'},
                   {'third':'B','first':None,'second':'C'},
                   {'third':'B','first':None,'second':None},
                   {'third':None,'first':None,'second':None},
                   {'third':'B','first':'A','second':None}])

df1['combo'] = df1[['second','third','first']].bfill(axis ='columns')["second"]
print(df1)

Results
  third first second combo
0     B     A      C     C
1     B  None      C     C
2     B  None   None     B
3  None  None   None  None
4     B     A   None     B


Python XML parse error : SyntaxError: invalid predicate

Question: I want to find the value of 'MS' value using 'company' value.
my code is :
import xml.etree.ElementTree as ET

data = '''<?xml version='1.0' encoding='UTF-8'?>
<results preview='0'>
<meta>
<fieldOrder>
<field>category</field>
<field>data</field>
</fieldOrder>
</meta>
    <result offset='0'>
        <field k='category'>
            <value><text>company</text></value>
        </field>
        <field k='data'>
            <value><text>MS</text></value>
        </field>
    </result>
    <result offset='1'>
        <field k='category'>
            <value><text>type</text></value>
        </field>
    </result>
    <result offset='2'>
        <field k='category'>
            <value><text>locate</text></value>
        </field>
    </result>
    <result offset='3'>
        <field k='category'>
            <value><text>action</text></value>
        </field>
    </result>
</results>'''

root = ET.fromstring(data)

result = root.find(".//result[field[@k='category'][value/text()='source']]/field[@k='data']/value/text()")

#query_result = root.find(".//result[field[@k='category' and value/text()='author']]")
#result = query_result.find("./field[@k='data']/value/text").text

print(result)

but This error occurs.
Traceback (most recent call last): File "C:\Program Files\Python310\lib\xml\etree\ElementPath.py", line 370, in iterfind selector = _cache[cache_key] KeyError: (".//result[field[@k='category'][value/text()='source']]/field[@k='data']/value/text()",)

During handling of the above exception, another exception occurred:

Traceback (most recent call last): File "C:\Users\Tester\Desktop\py_code\test.py", line 41, in <module> result = root.find(".//result[field[@k='category'][value/text()='source']]/field[@k='data']/value/text()") File "C:\Program Files\Python310\lib\xml\etree\ElementPath.py", line 405, in find return next(iterfind(elem, path, namespaces), None) File "C:\Program Files\Python310\lib\xml\etree\ElementPath.py", line 384, in iterfind selector.append(ops[token[0]](next, token)) File "C:\Program Files\Python310\lib\xml\etree\ElementPath.py", line 337, in prepare_predicate raise SyntaxError("invalid predicate") SyntaxError: invalid predicate

What's wrong with the xpath syntax?
I tried the annotation syntax in another way, but the same error is occurring.
Answer: If you want full XPath 1.0 support use lxml not the built-in package of ElementTree; for its (restricted) XPath support see  https://docs.python.org/3/library/xml.etree.elementtree.html#supported-xpath-syntax which, I think, suggests one culprit is using e.g. [value/text()='source'] instead of simple [value='source'].
Comment: Fortunately, there was a way to print XML data in a different form, so we solved the problem.
If the same issue occurs, we will try to use the lxml module.
Thank you for the good information.
Answer: I believe ElementTree's XPath implementation has some missing features related to text nodes. I think it doesn't return text nodes (only elements) and I'm not even sure it supports the text() node test (if so, that would explain your error message).
Thankfully, you don't need to use the text() node test at all, and you are actually using it in error. Throughout your XPath expression you are referring to text node children of the value elements (using text()), when you should instead be referring to child nodes which are elements (named text). NB none of the value elements have text node children; they all contain nothing but a child element named text.
Also you can omit the .// at the start of your XPath expression because you know that your result elements are all direct children of the root.
Lastly, you say you want to look up the text 'company' and retrieve 'MS', but your XPath expression is actually trying to look up the text 'source'.
Try this:
result[field[@k='category'][value/text='company']]/field[@k='data']/value/text

Because the value elements have no text node children, their text value is the same as the text value of their text child element, so you could replace value/text with just value:
result[field[@k='category'][value='company']]/field[@k='data']/value

Comment: I tried, but I get the same error.
Fortunately, there is a way to print the xml data in a different form, so we solved it with that method.
Thanks for your help.


Scope of setlocale function?

Question: I want to sort an array in php which contains german 'umlaute'. This does not seem to be an easy task for php. I found the following example on the web:
<code>$oldLocale=setlocale(LC_COLLATE, "0");
setlocale(LC_COLLATE, 'de_DE.utf8');
usort($countrys, 'strcoll');
setlocale(LC_COLLATE, $oldLocale);
</code>
This is working as expected. My question now is, what is the scope of setlocale? Is it limited to the current function I am in, is it limited to my thread, my session or is it global?
I am afraid of creating race conditions, but I cannot find any other information on this than:

The setlocale() function sets locale information.
Answer: It will be a global setting, it keeps set the last value while the script is running. It's not related to sessions, it's scope is the php process itself.
http://php.net/manual/en/function.setlocale.php
Comment: Yes, the exact note from php.net is: "The locale information is maintained per process, not per thread. If you are running PHP on a multithreaded server API like IIS, HHVM or Apache on Windows, you may experience sudden changes in locale settings while a script is running, though the script itself never called setlocale(). This happens due to other scripts running in different threads of the same process at the same time, changing the process-wide locale using setlocale()."
Comment: So the solution I posted can and will interfere with other scripts, if my client will use a multithreaded server? That would be bad news, thank you!

Scope of setlocale function?


Python script to manipulate text is writing [ ]+ to text file instead of [ \t]+

Question: I have made a python script to read lines from a file called input.txt and output them to output.txt with some changes in formating.
Here is the code here:
with open("input.txt") as f:
    lines = [line.rstrip() for line in f]
towrite = open("output.txt", "a")
for term in lines:
    for char in term:
        towrite.write(char+"[ \t]+")
    towrite.write("|")
towrite.close()

If input.txt just has a single line with the characters "ab", output.txt should have "a[ \t]+b[ \t]+|" but instead has "a[  ]+b[    ]+|". I think it is replacing \t with a tab, how do I fix this?
Answer: Ok I fixed it, turned out I just needed to fix this line:
Change towrite.write(char+"[ \t]+")
To towrite.write(char+"[ \\t]+")


Exit animation on NextJS 14 Framer Motion

Question: I'm attempting to add page transition animations to a Next js 14 app using Framer Motion.
I have PageTransitionLayout.tsx which looks like this
'use client';

import { motion, AnimatePresence } from "framer-motion";
import { ReactNode, FC } from "react";

import { usePathname } from "next/navigation";

interface ILayoutProps {
  children: ReactNode;
}

const PageTransitionLayout: FC<ILayoutProps> = ({ children }) => {
  const pathname = usePathname()

  return (
      <AnimatePresence mode={'wait'}>
        <motion.div
         key={`${pathname}1`}
         className="absolute top-0 left-0 w-full h-screen bg-green-400 origin-middle"
         initial={{ scaleY: 1 }}
         animate={{ scaleY: 0.5 }}
         exit={{ scaleY: 0}}
         transition={{ duration: 1, ease: [0.22, 1, 0.36, 1] }}
       />
       {children}
      </AnimatePresence>
  );
}

export default PageTransitionLayout;

and use it in app/contact/pages.tsx like so
"use client";

import PageTransitionLayout from "../ui/PageTransitionLayout";

export default function Contact() {
    return (
    <PageTransitionLayout>

Contact

    </PageTransitionLayout>
    )
}

but the exit animation of the motion div doesn't fire when navigating to a different page. What may be the issue?
Comment: Can you edit your question to have a [Minimal Reproducible Example](https://stackoverflow.com/help/minimal-reproducible-example)?
Comment: ok, I've made the edit
Comment: This is currently a shortcoming of the app directory, as it is so fast it doesn't provide the time to the framer library to show an exit transition, to work around this you must wrap your layout.js content in a HOC that will slow it down..Though this breaks using loading.js in your project as it will no longer properly communicate with the Suspense boundaries introduced by using the loading.js file.
Comment: hi @Apezdr, is there any change this happen when framer motion init? I am having trouble when navigating to the page with framer motion. But somehow when I reload the page, it always works. I added and check isClient but won't render anything on first load, this is not recommended in next js I think
Answer: You'll have to wrap your page in a HOC to slow down the app router in NextJS 13/14. The solution presented below will introduce more issues to work through though such as:

Suspense Boundaries from using loading.js file in app directory will fail to properly load in the children in effect making it so that you can't use loading.js

The solution will cause the page to re-render more but will effectively provide the exit transitions you're looking for.

Page will be 'frozen' after it's loaded in, this puts strain on the app router in its current state.

layout.js
/src/app/layout.js || /app/layout.js
import { Inter } from 'next/font/google'
import './globals.css'
import PageAnimatePresence from '@components/HOC/PageAnimatePresence'

const inter = Inter({ subsets: ['latin'] })

export const metadata = {
  title: 'Your Website Title',
  description: 'Website metadata description.',
}

export default function RootLayout({ children }) {
  return (

      <body
        className={inter.className + ` bg-blue-500 transition-colors duration-1000`}
        id="page-container"
      >
        <PageAnimatePresence>{children}</PageAnimatePresence>

  )
}

PageAnimatePresence.js
/src/app/components/HOC/PageAnimatePresence.js || /app/components/HOC/PageAnimatePresence.js
'use client'

import { usePathname } from 'next/navigation'
import { AnimatePresence, motion } from 'framer-motion'
import FrozenRoute from './FrozenRoute'

const PageAnimatePresence = ({ children }) => {
  const pathname = usePathname()

  return (
    <AnimatePresence mode="wait">
      {/**
       * We use `motion.div` as the first child of `<AnimatePresence />` Component so we can specify page animations at the page level.
       * The `motion.div` Component gets re-evaluated when the `key` prop updates, triggering the animation's lifecycles.
       * During this re-evaluation, the `<FrozenRoute />` Component also gets updated with the new route components.
       */}
      <motion.div key={pathname}>
        <FrozenRoute>{children}</FrozenRoute>
      </motion.div>
    </AnimatePresence>
  )
}

export default PageAnimatePresence

FrozenRoute.js
/src/app/components/HOC/FrozenRoute.js || /app/components/HOC/FrozenRoute.js
'use client'

import { useContext, useRef } from 'react'
import { LayoutRouterContext } from 'next/dist/shared/lib/app-router-context.shared-runtime'

const FrozenRoute = ({ children }) => {
  const context = useContext(LayoutRouterContext)
  const frozen = useRef(context).current

  return <LayoutRouterContext.Provider value={frozen}>{children}</LayoutRouterContext.Provider>
}

export default FrozenRoute

template.js
/src/app/template.js || /app/template.js
'use client'
import { motion } from 'framer-motion'

const variants = {
  hidden: { opacity: 0, x: 0, y: 0 },
  enter: { opacity: 1, x: 0, y: 0 },
}

export default function Template({ children }) {
  return (
    <motion.main
      variants={variants}
      initial="hidden"
      exit="hidden"
      animate="enter"
      transition={{ type: 'linear', duration: 0.25 }}
      key="LandingPage"
    >
      {children}
    </motion.main>
  )
}

Comment: Thank you for your thorough answer. The exit animation is working now.
Comment: Sorry, i can't cast a vote because my reputation is low


How can i get a select list in MVC without hardcoding properties

Question: The following works as it should. The problem is that i do not want to hardcode the AvailabilityID and the AvailabilityName
public ActionResult Create()
{
  SelectList AvailabilityList = new SelectList(db.Availabilities, "AvailabilityID", "AvailabilityName");
  ViewBag.AvailabilityList = AvailabilityList;
  return View();
}

and here comes the view
 @Html.DropDownListFor(model => model.Availability, (SelectList)ViewBag.AvailabilityList, new
                                {
                                    @class = "red",
                                    data_placeholder = "please choose"
                                })

How should i modify the code above?
I am 99% sure with a lambda expression, so i can also add an order by clause... but what about the other 1% ?
Thank you
Comment: `db.Availabilities.OrderBy(...).Select(x => new SelectListItem() { Value = x.AvailabilityID.ToString(), Text = x.AvailabilityName };`
Comment: You have to hard code it (the `SelectList` constructor takes `string` as the 2nd and 3rd arguments. Why not use `IEnumerable`?
Comment: @StephenMuecke Actually i want to remove the 2nd and 3rd arguments, but if i do this, the "whole objext" is displayed in the view. I will try the IEnumerable thing
Answer: A little extension (in a static class) like this could do the trick
public static IEnumerable<SelectListItem> ToSelectListItem<T, TValue, TText>(
            this IEnumerable<T> enumerable,
            Func<T, TText> text,
            Func<T, TValue> value,
            )
        {
            return enumerable.Select(item => new SelectListItem
            {
                Text = text(item).ToString(),
                Value = value(item).ToString(),
            }).AsEnumerable();

usage :
//you can add an OrderBy if needed
var AvailabilityList = db.Availabilities.ToList().ToSelectListItem(m => m.AvailabilityName, m => m.AvailabilityId);

of course, it's an IEnumerable<SelectListItem> now, not a SelectList, but both can be used with a DropDownListFor
Comment: Just change in your view : `(SelectList)ViewBag.AvailabilityList` to `(IEnumerable)ViewBag.AvailabilityList`
Comment: Thank you sir.  I now get the following error in the view Unable to cast object of type 'WhereSelectListIterator`2[...Availability,System.Web.Mvc.SelectListItem]' to type 'System.Web.Mvc.SelectList'. What am i doing terribly wrong here?
Comment: is'nt that we are still hardcoding? difference is they are not string now


How to assign a dynamic property in a model via a SQL query in Laravel 5

Question: I'm using Laravel 5.3 to build an API and I have an model for products. Whenever I retrieve a product, I want to retrieve the product's rating and it's recommended rate. I also have a model for reviews and products have many reviews.
$product = Product::where('slug', $slug)->with('reviews')->first()->toArray();

Rating is computed by looping through $product->reviews in the controller, adding up the score of each review, then dividing it by the total number of reviews.
if (count($product['reviews']) > 0) {
    $i = 0;
    $totalScore = 0;
    foreach ($product['reviews'] as $review) {
        $totalScore = $totalScore + $review['Rating'];
        $i++;
    }
    $product['averageReviewRating'] = $totalScore / $i;
} else {
    $product['averageReviewRating'] = null;
}

Recommended rate is computed with a SQL query.
$product['recommendedRate'] = round(DB::select("
    select ( count ( if (Recommend = 1,1,NULL) ) / count(*)) * 100 as rate
    from Review where PrintProduct_idPrintProduct = " . $product['idPrintProduct']
)[0]->rate);

This leaves me with $product['averageReviewRating'] and $product['recommendedRate'] with the data I want but seems very sloppy. I would like to just be able to do something similar to this below and have those two values assigned to each object of a collection, than access them via $product->averageReviewRating and $product->recommendedRate or even not include them in with and have those values eagerly assigned.
$product = Product::where('slug', $slug)->with(['Reviews', 'RecommendedRate', 'AverageReviewRating'])->first();

Anyone know a way to do this with ORM? I've looked high and low and have not found anything.
Comment: Im on my phone or would leave an example but generally that sort of logic should be on the model. Then you can do a custom attribute on the product model and loop your review records in there. To further improve on that that you could just query the reviews directly using the product model id as the select criteria and perform the average calculation in mysql
Comment: How you are calculating Recommended rate. if you can explain i can give the clean answer using ORM
Comment: @Vikash the query is right in the question. An answer can be agnostic to how I'm doing it though. I just want to run a query and assign the value it returns to a dynamic property every time I call the model.
Answer: You can do this way
protected $appends = [
 'reviews',
 'recommendedRate',
 'averageReviewRating'
];

public function getReviewsAttribute() {
 return $this->reviews()->get();
}

public function getRecommendedRateAttribute() {
 if (count($this->reviews) > 0) {
    $i = 0;
    $totalScore = 0;
    foreach ($this->reviews as $review) {
        $totalScore = $totalScore + $review->Rating;
        $i++;
    }
    return $totalScore / $i;
  } else {
    return null;
  }
}

public function getAverageReviewRatingAttribute() {
 return round(DB::select("
    select ( count ( if (Recommend = 1,1,NULL) ) / count(*)) * 100 as rate
    from Review where PrintProduct_idPrintProduct = " . $this->idPrintProduct
)[0]->rate);
}

then simply call Product::where('slug', $slug)->first()->toArray();
P.S. This is just the way you can do, I might miss part of logic or names..
Comment: This is working for now but the only issue is those methods only run when you access the properties so if you call the property in the view technically you're running SQL while rendering the view.
Comment: when you are adding `protected $appends = [
 'reviews',
 'recommendedRate',
 'averageReviewRating'
];` it is appending without accessing to properties
Answer: The way to get the sum in Laravel Eloquent is using the Aggregate sum and for average avg
https://laravel.com/docs/5.4/queries#aggregates
If you want to add a custom property to your model for that, you can use
class Product {
    function __construct() {
         $this->{'sum'} = DB::table('product')->sum();
         $this->{'avg'} = DB::table('product')->avg();
    }

}

edit: to set the attributes, you can use the built in function https://github.com/illuminate/database/blob/v4.2.17/Eloquent/Model.php#L2551
Comment: Product is a model so you cannot dynamically declare properties in the constructor like that.
Comment: @wwwroth why not? I know pretty sure you can


Determining the clock speed

Question: I mean to determine the clock speed.
I am posting below the output of the various commands listed here.
For the max freq, I see 4 different sources, with 2 different values:

CPU max MHz: 3300,0000 from lscpu.
capacity: 3300MHz from lshw.
capacity: 3800MHz from sudo lshw.
Max Speed: 3800 MHz from dmidecode.

For the current freq, I see 4 different sources, with roughly 3 different values:

CPU MHz: 2100.000 from lscpu.
cpu MHz : 1691 (averaged by me) from cat /proc/cpuinfo.
Current Speed: 2600 MHz from dmidecode.
Detected 2594.332 MHz processor from cat /var/log/dmesg.

My observations:

There was a wide variation in the output obtained, for both the max freq and current freq. How to make sense of this?
For instance, lshw gives different results with or without sudo. Is this expected? Which should be considered more reliable, and why?
The clock speed was even different among the 4 processors. Is such a wide variation expected?

Note:
As appropriately asked by @hobbs, this OP was motivated by the need for understanding the relation between "Clock speed" (whichever variant corresponds), CPU freq spec, and memory speed spec (here there is also possibly more than one value, see e.g. dmidecode showing Memory Module Voltage: 3.3 V for DDR3 RAM).

Output:
$ lscpu | grep "MHz"
CPU MHz:                         2100.000
CPU max MHz:                     3300,0000
CPU min MHz:                     1200,0000

$ cat /proc/cpuinfo | grep "MHz"
cpu MHz         : 1753.417
cpu MHz         : 1200.000
cpu MHz         : 2212.235
cpu MHz         : 1600.000

$ lshw -c cpu | grep capacity
WARNING: you should run this program as super-user.
       capacity: 3300MHz
$ sudo lshw -c cpu | grep capacity
       capacity: 3800MHz

$ sudo dmidecode -t processor | grep "Speed"
        Max Speed: 3800 MHz
        Current Speed: 2600 MHz

$ cat /var/log/dmesg | grep "MHz processor"
[    0.000000] kernel: tsc: Detected 2594.332 MHz processor

$ cat /var/log/kern.log | grep "MHz processor"

Comment: All of them are true in some way, and it depends on what you really want to know. "The clock speed" isn't really one thing. There's A) the available speed steppings, B) the active speed stepping for each core at a certain instant, C) the highest speed stepping available to a single core with the other cores idle and average-power constraints satisfied, D) the highest speed stepping available to all cores sustained, E) the actual number of clocks run by a core over some recent period of time, F) doubtless some other things... So what do you want to decide based on "the clock speed"?
Comment: @hobbs - I meant to understand the relation between "Clock speed" (whichever variant corresponds), CPU spec, and memory speed spec (here there is also possibly more than one value, see e.g. https://askubuntu.com/questions/1400050/dmidecode-showing-memory-module-voltage-3-3-v-for-ddr3-ram).
Answer: The following deductions are done entirely based on my own experiments and extrapolations. Also, part of the deduction is comparing the numbers with the official clock speeds reported by the CPU manufacturer.
This command shows the current clock for each processor core: (all subsequent commands run on Intel Atom C3558 CPU)
$ cat /proc/cpuinfo | grep "MHz"
cpu MHz         : 1260.714
cpu MHz         : 1070.646
cpu MHz         : 1124.995
cpu MHz         : 1234.689

This command shows the current "average" (as observed by myself, purely based on trial) clock between cores (CPU MHz), and the max normal clock (CPU max MHZ).
$ lscpu | grep "MHz"
CPU MHz:                         1181.650
CPU max MHz:                     2200.0000
CPU min MHz:                     800.0000

Note that the current clock speed (both average and for each core) varies greatly over time (and possibly many times per second), as the system normally continuously throttles the CPU clock for powersaving (down to CPU min MHZ). I believe it is normal that this varies among CPU cores as well.
This command also shows the max normal clock (capacity - should be the same as CPU max MHz above).
$ lshw -c cpu | grep capacity
WARNING: you should run this program as super-user.
       capacity: 2200MHz

However, for my Intel Atom CPU this is only correctly reported without sudo (2200 MHz). With sudo, it reports a higher number (in this case also 3800 - this may be the max boosted clock, but I'm not sure in the case of an Atom CPU):
$ sudo lshw -c cpu | grep capacity
       capacity: 3800MHz

For a Broadcom ARM CPU (on a Raspberry Pi 4), the value is the same both with and without sudo (1500 MHZ). I would guess this is because the Pi Arm CPU does not have boost/turbo mode.
Comment: Thanks for the detail. I have rewritten the question, with a more precise elaboration of the data.
I am not sure what you posted answers the questions, nor if it is supported by the output:
1) The "average" of the cpu freq for the 4 processors does not match the other figures.
2) Max cpu freq "is only correctly reported without sudo"... do you have any source to support this?
Comment: I elaborated my answer to make it clear that it is based on my own observations, and not based on any official sources. I also tried to make it clear what I believe are reliable numbers, again based on my observations. If someone can chime in with official reports it would be handy indeed.
Comment: Thanks Doug. However, in this case, even on my 2,2 GHz Atom CPU, doing `sudo su`, and then followed by `lshw -c cpu | grep capacity` still gets me 3800 MHz, which is clearly not correct.
Comment: Agreed, it is incorrect. I deleted my comment.
Answer: Updated the answer at Any way to check the clock speed of my processor?
But in summary:
All the commands above will also give you the CURRENT cpu Hertz, meaning, if you expect to see the same one on lscpu and when doing the cat /proc/cpuinfo it will be near impossible. you CAN compare the maximum because that should show the same for any of the ways you can analyze the CPU, but the current will always be literally "the current CPU hertz" at the moment you execute it.
Lastly do note that dmidecode reads information from the ACPI tables which is not always the same as the real time ones done by the other tools.
So you got a couple of ways of getting the REAL current CPU and then you also have methods of getting what the ACPI Table registers (which in my case is super wrong).
This is why if you run lscpu multiple times, the current speed will always change, same for the /proc/cpuinfo. But for dmidecode it will stay (on many cases) with the same value, even if the value is a false positive.

Determining the clock speed


Helvetia LBChange

Question: What is the LBChange used for in Helvetia? I see that in every language box there is one #change: which returns a new LBChange.
Answer: The language change is used to encapsulate a local grammar adaption applied to the grammar of the host language. In our case a language extension is defined as a grammar fragment and a specification of how this fragment is composed with the grammar of the host language.
For a detailled explanation see "Chapter 5.2.1 Language Change" in my PhD Thesis.

Helvetia LBChange


How to really use multitouch gestures now

Question: So i have a touchscreen now, Ubuntu 10.10, made the gesturetest which works with up to two fingers - but now i have one simple question: how do i enable multitouch so that GNOME understands the gestures - at least two finger scrolling should be possible now - right?
Comment: check this answer http://askubuntu.com/a/142934/29470
Answer: Goto System > Preferences > Mouse. Click on the Touchpad tab and select two finger scrolling. Click Close and it should now work.
Comment: Sorry, but there is no touchpad tab.
Answer: There's actually no support currently for two-finger scroll on touch screens.  The current support for two-finger scroll is implemented in the synaptics X driver, which is tailored for touch pad use, and probably won't behave properly with a touch screen.
So, although you've got two-finger multitouch happening there's not currently any support for turning a two-finger drag gesture into a scroll event.  This needs toolkit (GTK+, Qt, etc) support.  I'd expect the Canonical DX touch team, who are working on the multitouch stack, will implement this support in the next couple of releases.
Since the multitouch protocol stuff is almost available in an upstream X server there should soon be more people able to work on this, too; not just people working on Ubuntu.
At the moment (Ubuntu 11.10), this is a missing feature.
Comment: What about Ginn? https://wiki.ubuntu.com/Multitouch/Ginn Can it be used to add two-finger support?
Comment: It's 2016, anyone got an update on this?


A console to play them all

Question: I have a list of some gaming titles, some old others a bit newer (some being PlayStation exclusives) that I'd love to get my hands on. Can any if not all or at least half of these be played on the ps4 pro? Or would it be better to just get a regular ps4? Which of the 2 can play the majority of these?
Here's the list.
Journey https://www.playstation.com/en-us/games/journey-ps4/
Bloodborne all DLC included
Rachet and clank https://www.playstation.com/en-us/games/ratchet-and-clank-ps4/
Marvel ultimate alliance 2 all DLC included. Where to find the DLC would also be greatly appreciated!
Thanks in advance!
Answer: Every version of the PS4 can play all PS4 games. The PS4 Pro is a more powerful version of the console and can play many games at a more stable frame rate, with added graphical effects or at a higher resolution. However, all past and future PS4 games are still normally playable on the regular PS4.

A console to play them all