Subtotal calculates from original product price, disregards applied per product discounts

Question: This seems like a known issue but I actually didn't find a solution for this anywhere.
In commerce, if I apply a discount/pricing rule to a certain product, add it to cart, and go to checkout, table would say eg
<code>Product - 120$ (discounted from original 200$)
Subtotal - 200$
</code>
The subtotal is taken from the original product price and doesn't include the applied discount. It would be a lesser problem if that was just display issue. But the tax is then actually calculated from the subtotal, making the order total wrong
Is there a solution for that?
Answer: Since this question is now almost 2 years old, I assume this "discount" that they were dealing with was an older version of commerce_discount. The newest version doesn't have any kind of subtotaling problems because it affectively utilizes the price calculation system for discounting.
Comment: Still the subtotal shows the original price, not the discounted price, where as the line item shows the discounted price. So the subtotal is simply wrong.


Increase the intensity of certain part of frame using opencv

Question: Suppose there is a frame with some image.I want to display only those parts which have pixel intensity above 120 or 130. How can I do that with OpenCv ? Is there any commands to do so?
Then i need to set those parts to some intensity of 190.
Answer: You could try the cvThreshold function.  For the second part, cvFloodFill might be what you need.
Answer: As mentioned by astay13, you can use the threshold function like this:
<code>Mat image = imread("someimage.jpg", 0); // flag == 0 means read as grayscale
Mat mask;

// this tells you where locations >= 120 pixel intensity are
threshold(image, mask, 120.0, 255.0, THRESH_BINARY);

// this sets those locations to 190 based on the mask you just created
image.setTo(Scalar(190, 0, 0), mask);
imshow("image", image);
</code>
Hope that is helpful!


Why is there such a thing as a 6 chord when it is just an inverted minor 7?

Question: Is there ever a time when a six chord is something other than an inverted minor 7 chord? Why do my songbooks have these chords notated this way when they are just inverted minor 7 chords?
Comment: …because the bassist would play the wrong note ;)
Comment: @Tetsujin As my guitar teacher used to say: " the good thing in playing the bass is that, of you make a mistake, it would sound like the guitar did something wrong..."
Comment: @Tetsujin In his short tutorial on walking bass Adam Neely says 6th can be treated as a chord tone. This makes the question even more interesting. Not sure why it received downvotes.
https://www.youtube.com/watch?v=ruTfC5v9Z2Y (0:12)
Comment: @Tetsujin an inversion by definition means that the bassist IS playing a note other than the root as the bass so not sure what you mean
Comment: There may well *not* be a bass playing. It could well be just a piano or guitar chord.I think at that time, the chord would be named with regard to its lowest note.
Comment: In classical music analysis, I imagine CMaj6 would be viewed as having tonic function, while Amin6—even Amin6/C—would be viewed as having predominant function.  As indicated in Laurence Payne's answer, this has a lot to do with what the musical context is: Are we in tonic prolongation, or leading up to a dominant, or what?
Answer: Am7 has ACEG, whilst C6 has CEGA. All the same notes, but not in the same order.
Now, does that matter in a chord? Not particularly, except the lowest note - in root poition/voicing - gives any chord its name (assuming it's not a slash chord - obviously!). So, with an A as the lowest note, it gets called Am7. If there's a C as the lowest, it gets called C6.
Ah, but what if the E or G is the lowest? It's still one of those - they both contain a root, third, fifth and another note, and that's how we define chord names, simply speaking. And why shouldn't that chord (whatever it is) have E or G as the lowest note. When playing bass, I may well use A, or C, but could, on a whim, or considering the next chord, throw in E or G instead or as well. So, it may depend on the technicality of what preceded and what follows. Again, either could be 'correct'. And following what the bassist 'ought' to play is probably the defining point.
Comment: The lowest note and the root are not the same thing. The root of the chord is the note that functions as the tonal center of the chord -- the pitch that sounds most stable within the chord. Am7 and C6, though they have the same pitches in them, are functionally different, because of whether, in context, they operate fundamentally as an A (minor) chord or a C (major) chord. As an example: a song is more likely to end G7 C6 than G7 Am7. On the other hand, the progression Am7 D7 GM7 in a bebop jazz tune is more likely that C6 D7 GM7. In practice, however, they're often written interchangeably.
Comment: @Tim If the  Am7 chord is in first inversion then wouldnt the bass player play C? else it is not an inverted chord is it? So not sure how what the bass plays has anything to do with it.
Comment: @armani - read my last comment. The same question will apply to an m6 chord and its (almost) twin - m7b5. E.g. Fm6 - Dm7b5.
Answer: Yes.  When playing a song in C major, there's a world of difference between the notes C, E, G, A (with C in the bass) as a final tonic chord and the same notes (with A in the bass) as part of a I, vi7, ii7, V7 progression.
Not that a guitarist, with a bass player, might not choose the same shape for each.   But they're harmonically quite different.  Listen...

What really distinguishes them is the harmonic context - what they DO in that piece of music.   As stand-alone chords they are indeed ambiguous.  But, in a piece in C major, as a final chord it's very likely to be the tonic, C6.    Whereas in the sequence C, *, Dm7 (or F), G7 it's going to be a lot more useful to call it Am7.
What it IS is the pitch set C, E, G, A.   What it DOES can tell us if it's more useful to think of it as C6 or Am7.
Comment: I'm thinking the same. But what harmonic context makes something C6 or Am7? Because that would be the answer for the question asked here.
Comment: Thank you for the example. But the answer seems incomplete to me. Is the bass note the only thing that distinguishes Am7 from C6? What if in the first measure the bass plays other chord tones, E or G?
Comment: What really distinguishes them is the harmonic context - what they DO in that piece of music.   As stand-alone chords they are indeed ambiguous.
Comment: @user1079505: Perhaps my 2020-07-13 comment on Tim's answer gives the harmonic context you're looking for.


Quick question on why two measures have equal total mass.

Question: I am following Probability with Martingales by Williams

I am having troubles with why the two measures $H \rightarrow P(I \cap H)$ and $H \rightarrow P(I)P(H)$ have the same total mass $P(I)$.
Is the total mass the $ \sum_i P(I \cap H_i)$ where $H_i$ are all the disjoint elements of $\mathcal{H}$?
Answer: A measure space is always a triple $(\Omega, \mathcal{F}, \mu)$, where the set $\Omega$ is the set with respect to which $\mathcal{F}$ is a sigma-algebra. The value of $\mu(\Omega)$ is called total mass of $\mu$. The measure $\mu$ is a probability measure iff its total mass is $1$.
Now observe that $P(I \cap \Omega) = P(I) = P(I) \cdot P(\Omega)$, so both measures have the same total mass $P(I)$.


Is the closure of a set contained in the convex hull?

Question: Let $A\subseteq\mathbb{R}^d$. Do we have $\bar A\subseteq \text{conv}(A)$?Counterexample?
Answer: No.  If $A$ is open and convex, then $\textbf{conv}(A) = A$.
For a specific example, suppose $A$ is the open unit ball.
Then $\textbf{conv}(A) = A \nsupseteq \bar{A}$.


MANOVA (SPSS) test - determine control variables in moderation analysis

Question: I am examining the moderating effect of IV1 in the relationship between IV2 and DV using hierarchical regression analysis. The study has 2 demographic variables: gender and age. To determine if it is necessary to control these demographic variables, can I conduct MANOVA tests with IV1, IV2, and DV as dependent variables?
Comment: Controlling or not controlling for a variable is a topic squarely within the area of the New Causal Revolution. See this answer: https://stats.stackexchange.com/questions/590984/when-is-there-enough-or-too-much-balancing-in-observational-causal-studies/591001#591001.
Answer: Your choice of control variables should be informed by the underlying causal model between the variables (as suggested in the comments). To specify such a causal model and read off what you need to adjust for, you can use tools such as the dagitty website/package.
For an introduction to causal models and how they can help in building the right sets of control variables, have a look at this introduction to directed acyclic graphs.


Piano finger numbers for the attached measure

Question: I was wondering if anyone could add finger numbers above each note on the measure below. I can't really seem to find a way to play the whole thing and still manage play it in legato (notice the slurs above notes).

complete music sheet
Comment: You know you have to use the pedal to be able to play this, don't you?
Comment: @TimH legato means playing notes in such a way that they slightly overlap each other so it becomes rather continuous and smooth. and the key to such a way is puzzling out right fingering. for more information you can check this link out.(look at what user15493's wrriten) https://music.stackexchange.com/questions/4504/what-does-an-arc-mean-above-the-notes-in-a-piano-sheet-music-how-do-i-play-it
Answer: My fingering would be the same regardless of key signature for this.
RH: 421, 421, 51, 51, 421, 532, 15, 15
LH: (51)21, 521, 51, 51, 521, 521, 51, 51
The trick in the RH is changing the pattern on the last F chord so you can get down to the E.
The trick in the LH to get that low note is to cross over the 2nd finger to get up the octave.


If $x^2+bx+c=0$ and $bx^2+cx+1=0$ share a root, then either $b + c + 1 = 0$ or $b^2 + c^2 + 1 =bc + b + c$

Question:
If the quadratic equations $x^2+bx+c=0$ and $bx^2+cx+1=0$ have a
common root then prove that either $b + c + 1 = 0$ or $b^2 + c^2 + 1 =bc + b + c$

Till yet,
I had figured the common root of the given two quadratic equation. i.e.
Multiplying first equation by $b$ and eliminating the term $bx^2$ from the equation I get the common root ($\alpha$ say),
$$\alpha=\frac{1 - cb}{b^2 - c}$$
Further putting this value in either of the equation didn't benefited me much.What it gave me was an odd, unfriendly equation. Can anyone help me in this?
Thanks in advance.
Answer: Let $y$ be the common root then, consider $y^2+by+c=0$ and $by^2+cy+1=0.$ Clearly $y\not=0.$ Therefore $$y^3+by^2+cy=0$$
$$y^3-1=0$$
$$(y-1)(y^2+y+1)=0.$$

If $y=1,$ then clearly $b+c+1=0.$

If $y^2+y+1=0,$ then note that $by+c=y+1$ and $cy+1=b(y+1).$
Note that $b=c=1$ is also a possibility. Otherwise, $$-y=\dfrac{c-1}{b-1}=\dfrac{b-1}{b-c}$$ which simplifies exactly to what you need.
Comment: @Alpha: you are welcome.
Answer: Let $y$ be the common root
So, we have $$y^2+by+c=0, by^2+cy+1=0$$
Solving for $y,y^2$ we get $y^2=\dfrac{b-c^2}{c-b^2},y=\dfrac{bc-1}{c-b^2}$
and using the identity $y^2=(y)^2$ we get $$b^3+c^3+1^3-3\cdot b\cdot c\cdot1=0$$
Now use Factorize the polynomial $x^3+y^3+z^3-3xyz$
Comment: Yep! Thank you very much. This was the very approach which I was seeking here,
$$b^3+c^3+1-3bc=0$$ $$\implies (b+c+1)(b^2+c^2+1-bc-c-b)=0$$ now either $$b+c+1=0$$ or $$b^2+c^2+1=bc+b+c$$


Setting up user permissions for new user

Question: I want to add a new user to my CentOS 6 server (let's call him Barry). I've made the user account Barry and added him to a group I created called webusers like this:
groupadd webusers
useradd -G webusers Barry
passwd Barry

Now that I have a user account all set up with a password and added to a group, I want to give the group permission to write to the nginx config file, restart nginx, and do whatever they need to do in /var/www/ like create files/directories etc.
The nginx config file is located here:
/webservers/nginx/conf/nginx.conf

To restart nginx, I want the webusers group to be able to run the following command:
/etc/init.d/nginx restart

And I want to give them permissions to read and write to this directory:
/var/www/

chmod looks horribly confusing to me, I've never had to use it before and I'm kinda new to system administration.
Answer: For the nginx conf file, simply make it group writable:
chgrp webusers /webservers/nginx/conf/nginx.conf
chmod 664 /webservers/nginx/conf/nginx.conf

To allow the webusers group to restart the service, it'll be easiest to do this with sudo. If it's not installed, install with (as root):
yum install sudo

Then edit /etc/sudoers with:
visudo

Add some entries like:
Cmnd_Alias NGINX=/sbin/service nginx restart
%webusers ALL = NGINX

This will allow members of the webusers group to run the command sudo service nginx restart.
For /var/www you'll need to add group write and add the setgid bit to the directory to ensure new files have group webusers:
chgrp -R webusers /var/www
chmod 2775 /var/www

Answer: Here is a great primer on unix permissions (and using chmod/chown/etc).  It sounds like you'll want /var/www to be owned by the webusers group and with the g+s permission.  You'll probably want to read up on umask and considering having these users use umask 002 for this shared directory.
/etc/init.d/nginx is going to require root permissions since it will want to bind to port 80, for that you'd use sudo.  There should be tons of resources out there for setting up sudo, including the sudoers manpage.


Generic method to sort list of items

Question: I've got two classes which has two common properties Id and SortNumber. I wanted to have a generic method to sort items in a list of said classes.
Is it possible to not implement the interface IOrderitem to classes Foo and Bar but still be able to use the method MoveUp?
Or is reflection the only alternative? Been writing mostly TypeScript code last few years so a bit rusty on C#.
public class Foo
{
   public int Id {get;set;}
   public int SortNumber {get;set;}
   // etc
}

public class Bar
{
   public int Id {get;set;}
   public int SortNumber {get;set;}
   // etc
}

public interface IOrderitem
{
   int Id {get;set;}
   int SortNumber {get;set;}
}

public static void MoveUp<T>(List<T> itemList, int id)
{
    for (int i = 0; i < itemList.Count; i++)
    {
        // reindex items
        var item = itemList[i] as IOrderItem;

        bool isItem = item.Id == id;

        if (isItem && i > 0)
        {
            // set item above eventinfo item to one position lower (0 = top rest lower)
            (itemList[i - 1] as IOrderItem).SortNumber = i;

            // set the item to move up one position higher (0 = top rest lower)
            item.SortNumber = i - 1;
            i++;
        }
        else
        {
            item.SortNumber = i;
        }
    }
}

Comment: You're talking about duck typing. In C#, this is only possible with 2 approaches: Reflection or `dynamic`. Both are slow. I would avoid both unless absolutely necessary.
Comment: This is normally the sort of thing you accomplish through `IComparable` and `IComparer`. (Not to mention that you usually don't reimplement sort logic, since we already have `.OrderBy` and indeed `List.Sort`.)
Comment: If you need the items sorted and ability to move up and down in the sort order maybe you could do better with a LinkedList?
Comment: @JeroenMostert I'm not sorting but moving a item in the list then re-indexing that item.
Comment: @dymanoid if by slow it is a few milliseconds at most then it is no problem.
Comment: @RalfdeKleine It makes your programs very fragile and error prone, which is a much bigger deal than the (sometimes significant) performance costs.
Answer: You could implement a base class for Foo and Bar and let inherit from it.
public class BaseClass
{
    public int Id { get; set; }
    public int SortNumber { get; set; }
    // etc
}
class Foo : BaseClass    {    }
class Bar : BaseClass    {    }

Instead of making List of T, where you have the defined type, you could use dynamic. But I would not recommend to do that. it's not recommended. See Link Is the use of dynamic considered a bad practice?
 public static void MoveUp(List<dynamic> itemList, int id)
    {
       // ....
    }

You can then use the "properties" as usual, but any renaming later, could lead to crashes.
Actually all depends on your purpose to NOT use an interface, which is not clear to me.
Comment: I was wondering if it could be done without interfaces -or- baseclasses -or- abstract classes. I'm using EF classes which exist in a common project I'd rather not change.
Comment: @dymanoid there are some reasons. but please read here: https://stackoverflow.com/questions/31859016/is-the-use-of-dynamic-considered-a-bad-practice. And i wrote, that it's risky, and also why... no need to just downrate IMHO
Comment: @dymanoid: At that point i was not sure, if this would be an option at all. But you are right, I've edited this.
Answer: You write in the comments:

I was wondering if it could be done without interfaces -or- baseclasses -or- abstract classes. I'm using EF classes which exist in a common project I'd rather not change.

So, you want the duck typing feature.
C# is a strongly typed language. Duck typing is rather a dynamic language feature. Although there are some examples of duck typing in the C# compiler itself (see e.g. foreach or await), the extensive usage of duck typing breaks the purpose of the strongly typed language: compile time type safety.
There are two ways you can implement it in C#: using either Reflection or dynamic. Both are slow.
I can show you the dynamic approach.
In your MoveUp<T> method, use
var item = itemList[i] as dynamic;

instead of
var item = itemList[i] as IOrderItem;

So now, T can be even typeof(object). You can access the Id and SortNumber properties - they just need to exist on that object. But: this kinda drops all the benefits you get with the generics.
Drawbacks:

sloooow
no compile-time type safety
no automatic refactoring and other lovely stuff of IDEs
need to handle exceptions if there are no such properties or if they have wrong types or if they are read-only etc

I've created a simple benchmark for you. I have a List<Item> with 10.000 objects. I do:
for (int i = 0; i < 10_000; i++)
{
    sum += objects[i].Value;
}

and
for (int i = 0; i < 10_000; i++)
{
    dynamic o = objects[i] as dynamic;
    sum += o.Value;
}

The results are:
|     Method |      Mean |     Error |    StdDev |
|----------- |----------:|----------:|----------:|
| Direct     |  11.22 us | 0.0268 us | 0.0251 us |
| Dynamic    | 256.15 us | 0.9606 us | 0.8986 us |

So the dynamic approach is 23 times slower (on my machine, using .NET Framework 4.7.2 (CLR 4.0.30319.42000), 64bit RyuJIT-v4.7.3324.0).
Comment: Thanks. I wil not use it but you did answer my question! And learned about duck-typing.
We will be using an interface and break open the common project, seems like the best solution (at this moment).

Generic method to sort list of items


Return results from regular expression pattern matching

Question: I have a string (HTML in this example case) which contains the same pattern for displaying the results of sports games. So, the HTML tags are known, but the values for each game are not.

In Perl, we can do this:
if ( $content =~ /\<\/a\>\
(\d+)\<\/span\>\
(\d+)\-(\d+).+\<\/a\>\
(\d+)\<\/span\>\
(\d+)\-(\d+)/) {
  $visitingTeamScore = $1; // $1 is the 1st matched digit
  $visitingTeamWins = $2; // $2 is the 2nd matched digit
  $visitingTeamLosses = $3; // Etc
  $homeTeamScore = $4;
  $homeTeamWins = $5;
  $homeTeamLosses = $6;
}

which returns the digits inside the parentheses, in this case 6 total integers of varying digit lengths. We can then assign those matches to variables.

From an answer in this question: Swift Get string between 2 strings in a string, I have the following Swift code:
extension String {
    func sliceFrom(start: String, to: String) -> String? {
        return (rangeOfString(start)?.endIndex).flatMap { sInd in
            (rangeOfString(to, range: sInd..<endIndex)?.startIndex).map { eInd in
                substringWithRange(sInd..<eInd)
            }
        }
    }
}

let firstMatch = content?.sliceFrom("
", to: "") // The first integer in the string

The problem comes in when getting the 4th integer which is also between
 and  so the resulting match will be the first digit again.
I can manually count the characters (which itself isn't a perfect science because the digits in each integer can differ) to do something ugly like:
let newRawHTML = content![content!.startIndex.advancedBy(15)...content!.startIndex.advancedBy(5)]

Another possibility is to remove anything matched already from the string, making it shorter for each subsequent search (which I'm not sure how to implement.) What's the way to do this? Is there any way in Swift to "pluck out" the matches?
Answer: The code you have shown as a Perl example, uses regular expression.
And in case the pattern is getting a little bit complex, you'd better use NSRegularExpression directly.
let pattern = "
(\\d+)
(\\d+)-(\\d+).+
(\\d+)
(\\d+)-(\\d+)"
let regex = try! NSRegularExpression(pattern: pattern, options: [])
if let match = regex.firstMatchInString(content, options: [], range: NSRange(0..<content.utf16.count)) {
    let visitingTeamScore = (content as NSString).substringWithRange(match.rangeAtIndex(1))
    let visitingTeamWins = (content as NSString).substringWithRange(match.rangeAtIndex(2))
    let visitingTeamLosses = (content as NSString).substringWithRange(match.rangeAtIndex(3))
    let homeTeamScore = (content as NSString).substringWithRange(match.rangeAtIndex(4))
    let homeTeamWins = (content as NSString).substringWithRange(match.rangeAtIndex(5))
    let homeTeamLosses = (content as NSString).substringWithRange(match.rangeAtIndex(6))
    //...use the values
}

Comment: @Shades, see the **Regular Expression Metacharacters** and **Regular Expression Operators** section of [the official reference](https://developer.apple.com/library/ios/documentation/Foundation/Reference/NSRegularExpression_Class/index.html#//apple_ref/doc/uid/TP40009708).
Comment: I read a bunch of question/answers and articles on NSRegularExpression but I didn't understand how to use it. This is great, thanks!
Comment: Where can I find a list of the Swift wild card characters to use in my regular expressions?


How to emulate  press on startup in vimrc

Question: <F11> makes it full screen in ubuntu (I changed the settings and chose show the menus for a window In the window's title bar rather than in the menu bar) and hides the global menu panel (at the top with the battery and wifi symbols). I didn't want to press <F11> every single time I opened gvim so what do I have to write in .vimrc for this?
Answer: The mappings and Vimscript commands that you can put into your ~/.vimrc are only for scripting Vim itself; you cannot directly control your environment with it. The only way is through launching an external command (via :! or :call system(...), for example wmctrl with the right arguments. Alternatively, you could modify the shortcut / command that launches GVIM to include this maximization, so you don't need to "break out" from inside Vim.
I'm using the :Fullscreen command of the shell.vim - Improved integration between Vim and its environment plugin; it works well on Windows and Gnome. You can launch that automatically by putting Fullscreen into your ~/.gvimrc.
Comment: There's also [vullscreen](https://github.com/KabbAmine/vullScreen.vim) for GNU/Linux, whose sole aim is to provide the full-screen feature.


BlockContent::load for addtoany_block returns null

Question: I am trying to load the "AddToAny Buttons" block of AddToAny module inside a controller. My idea is to render the block content as a part of the page. I have verified the block id of "AddToAny Buttons" block in the Addtoany module's block plugin file which is 'addtoany_block'. But BlockContent::load('addtoany_block') returns null.
Could somebody help me identify where I'm going wrong?
Here is the code snippet
$block = \Drupal\block_content\Entity\BlockContent::load('addtoany_block');
$render = \Drupal::entityTypeManager()->
getViewBuilder('block_content')->view($block);

Comment: `block_content` is the entity type of custom content blocks (the ones editorially created in the custom block library `/admin/structure/block/block-content`) - are you sure that your AddToAny block is one of those and not a code-generated block?
Comment: @Hudri it is a code-generated block. Thanks for your comment
Answer: The addtoany_block is not a block content, but it's a plugin block.
So if you want to get the its build programmatically you should:
1. Get the block configuration (addtoany_block settings).
2. Create an instance of the block.
3. Get the build.
Try the following:
// Block manager.
$block_manager = \Drupal::service('plugin.manager.block');
// Load Block settings / Settings.
$addtoany_config = \Drupal::config('addtoany.settings')->getRawData();
/** @var \Drupal\addtoany\Plugin\Block\AddToAnyBlock $plugin_block */
$addtoany_block = $block_manager->createInstance('addtoany_block', $addtoany_config);
// Get Block build.
$build = $addtoany_block->build();

Comment: Thanks, @berramou. It worked for me.
Comment: i'm glad that helped, mark it as the right answer to help someone else.


Tool to automate basic connectivity testing

Question: After our vendors have setup a certain test environment, we need to go in to perform connectivity testing between PC to servers and also between servers.
The problem is that we run a range of tests to telnet between 2 nodes on several ports and this is a manual and rather tedious process.
Does anyone know of a small tool or script that I can take input on the range of ports to be test and will run an automated range of testing against those ports? All I need to do is to validate whether a TCP connection can be established from the source PC / server to the target server IP address / port.
Thanks,
Wong
Answer: You can use a portscanner like nmap
You can use -P to specify individual ports, or ranges: -P 25,80,110,1024-2048,3306
Comment: Strictly speaking, nmap is the best fit for my use case, with one major problem: it's completely banned. I just spent the past couple of weeks trying to get an exception to the rule but failed. My client's IT security team is adamant that anybody using nmap is a threat to the network and refuses to compromise on this.
Answer: The netcat/nc and possibly expect tools are good for this. With nc for example you can set a timeout and then interrogate the exit status of the command
nc -w 1 example.com  80

would return an exit status of 0 after 1 second if a connection can be established and 1 if a connection cannot.
Answer: For a long term monitoring you should use nagios. You could also configure notifications and escalations when something fails.
www.nagios.org
Comment: I'm more looking for a basic shakedown tool that will be removed as soon as the work is done. Nagios is more of a long term solution which doesn't fit this scenario as well.


loop automático do comando copy

Question: Se copio cada caractere individualmente do edit e dando uma quebra de linha com #13#10, uso um código como esse, só que dependendo do programa fica muito cheio de variveis
procedure TForm1.Button1Click(Sender: TObject);
var
a,b,c,d,e:string;

begin

a:=copy(Edit1.Text,1,1)+ #13#10;
b:=copy(Edit1.Text,2,1)+ #13#10;
c:=copy(Edit1.Text,3,1)+ #13#10;
d:=copy(Edit1.Text,4,1)+ #13#10;
e:=copy(Edit1.Text,5,1)+ #13#10;

memo1.Lines.Add(concat (a + B + C + d +e ));

end;

Não teria um jeito mais simples de se fazer mesmo enxugando o código acima usando um laço for, while ou de outra maneira, para usar apenas uma variável?
tipo assim:
procedure TForm1.Button2Click(Sender: TObject);
var
a:string;
i:integer ;
begin

for i:=0 to Length(Edit1.text) do
a:=(copy(Edit1.Text,i,1)+ #13#10);

memo1.Lines.Add(a);

end;

Answer: Como não sabemos o tamanho do texto de entrada, então teremos que fazer um Array Dinâmico, e percorrer cada caractere e adicionar o Enter no final.
program teste;
var
  vetor :Array of String;
  n,i : integer;
  texto : string;
begin
 texto := 'StackOverflow';
 n := length(texto);

 SetLength(vetor,n); // seta o valor máximo do array.

 for i:=1 to high(vetor) do
 begin
   vetor[i] := copy(texto,i,1)+ #13#10;
 end;

 //Array para impressão
 for i:=1 to high(vetor) do
 begin
    memo1.Lines.Add(a);
    // write(vetor[i]);
    // Showmessage(vetor[i]);
 end

end.

Comment: Agradeçido David , mas é que estou com problema precisaria fazer o loop com Copy mesmo, mais ou menos naquele estilo que fiz acima com o for, com wile, se tiver condições  porque o programa já tá quase pronto,e é muita coisa que teria de mexer ali, dá mais 100 páginas de código, a maioria eu sei a quantidade de strings, então estou apenas presisando enxugar o código,  agradeçido novamente pela ajuda, se você tiver alguma outra dica fico agradeçido
Comment: @acs, tenta ler o código que postei de exemplo, a aplicar ao seu, não tem grandes mudanças, basicamente um vetor novo. Se não conseguir me fala que eu aplico a solução ao seu contexto.
Comment: Saudações David, realmente,  ficou muito bacana mesmo, obrigado
Comment: Poderia marcar a pergunta como respondida? Na dúvida, visite o [tour] para saber como fazer isso. Obrigado.
Comment: de nada, sim sem problema, já está respondido,  só  não encontrei o modo no link do tour acima que você passou, assim que achar eu marco ele, abraço

loop automático do comando copy


Criar um Array com os números digitados pelo usuário

Question: Olá, pessoal. Sou iniciante no estudo de JavaScript e me deparei com um problema que talvez seja relativamente simples. A questão é o seguinte: Não consigo fazer com que os números enviados da variável "num" sejam postos dentro do vetor "numeros". Sempre quando digito console.log(numeros) os números digitados surgem no console como "undefined". Meu código está incompleto e não consigo seguir adiante sem antes resolver esse problema.
Obs: Deixei de fora o código em HTML e CSS, mas caso queiram que eu incremente para melhor visualização estarei postando posteriormente.
let numeros = []
function adicionar () {
            let num = Number(document.getElementById('cNum').value)
            let respF = document.getElementById('respFinal')

            if (Number(num) < 1 || Number(num) > 100) {
                window.alert('Número Inválido')
            } else {
                let respNum = document.getElementById('cText')
                respNum.innerHTML += `${num}\n`
                numeros.push(Number(num).value)

            }

Answer: Me parece que o seu único problema é essa linha:
numeros.push(Number(num).value)
Você não precisa fazer Number(X).value, esse .value não é um atributo válido, por isso, retorna undefined.
Mas além disso, num já é do tipo number, então não precisa reconverte-lo.
Bastaria isso:
numeros.push(num)
Creio que isso soluciona.
Comment: Funcionou. Muito obrigado.


Does family 'ocat' work with gamm4 in R?

Question: I am trying to fit a GAMM to ordered categorical data using gamm4 in R. In the help file for gamm4, it says the argument 'family' is "A family as used in a call to glm or gam." That being the case, I try to use family ocat from the mgcv package, which is designed for ordered categorical data. However, when I follow the example provided in the ocat help page (but adding random effects), I receive an error. Is this a bug, has ocat not properly been synced with gamm4, or is there some other issue I am missing?
Example:
library(mgcv)
## simulated some ordered categorical data...
set.seed(3);n<-400
dat <- gamSim(1,n=n)
dat$f <- dat$f - mean(dat$f)

alpha <- c(-Inf,-1,0,5,Inf)
R <- length(alpha)-1
y <- dat$f
u <- runif(n)
u <- dat$f + log(u/(1-u))
for (i in 1:R) {
  y[u > alpha[i]&u <= alpha[i+1]] <- i
}
dat$y <- y

## plot the data...
par(mfrow=c(2,2))
with(dat,plot(x0,y));with(dat,plot(x1,y))
with(dat,plot(x2,y));with(dat,plot(x3,y))

## fit ocat model to data...
b <- gam(y~s(x0)+s(x1)+s(x2)+s(x3),family=ocat(R=R),data=dat)
b
plot(b,pages=1)
gam.check(b)
summary(b)

##################################################
library(gamm4)

## add in some random effects and use gamm4
dat$f3 <- sample(1:40,400,T)
b2 <- gamm4(y~s(x0)+s(x1)+s(x2)+s(x3),random = ~ (1|f3),family = ocat(R=R),data = dat)

Comment: I think you would be better on an R-site or e-mailing the maintainer of the package.
Answer: No, ocat doesn't work with gamm4(). From ?family.mgcv

As well as the standard families documented in family (see also
       glm) which can be used with functions gam, bam and gamm,
       mgcv also supplies some extra families, most of which are
        currently only usable with gam, although some can also be used
        with bam...

(emphasis added). We need to take this literally.
I believe bits of the documentation have gotten out of sync — you can only use the families that lmer or glmer understand in gamm4().


The tensor product of a Hilbert space with a finite dimensional vector space and the adjoint operator on that space

Question: I am really trying hard to understand how to view the tensor product of a Hilbert space with an $n$-dimensional vector space as being isomorphic to an $n$-dimensional Hibert space. The specific statements are in the following. (This is from the book titled "Hypocoercivity" written by Cedric Villani, one of the Fields medalists.)

(1) Could you help me understand how to view $\mathcal{H} \otimes \mathcal{V}$ as isomorphic to $\mathcal{H}^n$?
(2) Also, here it says the adjoint operator $A^*$. Is it defined from the Hilbert space $\mathcal{H} \otimes \mathcal{V} \to \mathcal{H}$ and $\langle Ah_1, h_2 \rangle_{\mathcal{H} \otimes \mathcal{V}} = \langle h_1, A^{*}h_2 \rangle_{\mathcal{H}} $?
I'd really appreciate it if you'd help me. Thank you.
Answer: Well, there is an isomorphism
$H\otimes_{\Bbb R}{\Bbb R}^m \simeq (H\otimes_{\Bbb R}{\Bbb R})\oplus \ldots \oplus (H\otimes_{\Bbb R}{\Bbb R})$ ($m$-times)
of $\Bbb R$-vector spaces with $H\otimes_{\Bbb R}{\Bbb R}\simeq H$.
Comment: Thank you! Specifically, can I say the isomorphism $\phi$ from $\mathcal{H} \otimes \mathbb{R}$ to $\mathcal{H}$ is $\phi (h \otimes a)=ah$? Also, the isomorphism $\psi$ from $\mathcal{H} \otimes \mathbb{R}^m$ is $\psi (h \otimes (x_1,x_2, \cdots ,x_m))=(h \otimes x_1,h \otimes x_2, \cdots ,h \otimes x_m)$? Could you also recommend me any reference for this? I really can't find a good reference for this.
Comment: @withgrace1040: Sorry but I have no reference for you. I'd look into books about the mathematical foundations of quantum mechanics.
Comment: I see. Thank you for your comment! Could you specify the isomorphism maps or check if the isomorphism maps I wrote are correct? Also, the definition of the hermitian operator $A^*$ above is correct?
Comment: Regarding your second point, I think your understanding of $A^*$ is correct, I am also trying to digest this material


os.path modulo python

Question: Alguém pode me explicar o que ocorre nestas 2 linhas?
caminhos = [os.path.join(pasta, nome) for nome in os.listdir(pasta)]
arquivos = [arq for arq in caminhos if os.path.isfile(arq)]

Answer: Esse código usa o conceito de list comprehension.
List comprehension é um açúcar sintático da linguagem python que segue a seguinte notação:
  [expressão for item in list if condição]

O que ele faz é: para cada item do iterável list caso condição for verdadeira ele executa expressão e armazena o resultado numa variável que é uma lista (os colchetes).
Dessa forma, na primeira linha do código todos os nomes (arquivos e subpastas) dentro da pasta são concatenados com o path gerando o caminho absoluto.
A segunda linha apenas verifica qual desses paths são arquivos (note que podem haver subpastas).
Comment: entendi, mas porque os parâmetros pasta e nome? ele não deveria concatenar os dois?
Comment: ```pasta = r'C:\Users\user\Desktop\mp3'
caminhos = [os.path.join(pasta, nome) for nome in os.listdir(pasta)]
arquivos = [arq for arq in caminhos if os.path.isfile(arq)]
mp3 = [arq for arq in arquivos if arq.lower().endswith(".mp3")]```
Comment: *Nome* e *pasta* foi apenas para seguir sua nomenclatura. Seguindo seu comentário pasta = `C:\Users\user\Desktop\mp3`
Answer: Como os.listdir() retorna o conteúdo da pasta nome por nome, sem o caminho, o autor usou os.path.join() para criar strings com o caminho completo.
os.path.join() junta dois ou mais pedaços de um caminho de arquivo. É quase o mesmo que concatenar, mas tem algumas diferenças:

Se o nome da pasta não terminar em barra, ele coloca a barra certa automaticamente, dependendo do sistema operacional (/ no linux e \ no windows);
Se um dos nomes passados como parâmetro começar com uma barra, significa que é a partir da raiz, então as pastas anteriores a esta são ignoradas.

A segunda linha usa os.path.isfile() para filtrar somente os caminhos que sejam arquivos, ignorando portanto subpastas e outros ítens especiais que possam estar dentro da pasta.
Comment: entendi, muito obrigado.

os.path modulo python


Value is not changing even after appending. Python

Question: I'm very new to python and I just don't understand why the value of 'a' doesn't change even after 'orange' has been appended. len(x) becomes 4 but 'a', which is supposed to be len(x) stays 3. Thankyou for your time.. code-
x = ['apple', 'banana', 'cherry']
a = len(x)
print('list: ',x)
print('Len_x:',(len(x)))
print('a :',a)

x.append('orange')

print('list: ',x)
print('Len_x:',(len(x)))
print('a :',a)

The output
Comment: First try to google stuff
`a=len(x)` means the legth of list `x` is assigned to the variable `a`. To update the value of `a`, you should again write `a=len(x)`  after append operation
Comment: In python when you assign a value to a variable you cannot change what it refers to, other than another assignment. You **can**, for example, change the contents of a container, but not which container a variable refers to.
Comment: @ShivamJha Only if I knew what exactly to Google, I wouldn't have troubled you  guys. Like I said I am very new to Python so I don't the terms/definitions. But thankyou for your time.
Comment: @eeskyy No problem. Just don't loose your beginners mindset and be humble. Happy to help.
Answer: i dont have enough reputations to comment so :
you must change the value of a varrible then the value will be changed.
x = ['apple', 'banana', 'cherry']
a = len(x)
print('list: ',x)
print('Len_x:',(len(x)))
print('a :',a)

x.append('orange')

#Add this to change for example:
a = len(x)

print('list: ',x)
print('Len_x:',(len(x)))
print('a :',a)

Answer: The answer is pretty simple:
x = ['apple', 'banana', 'cherry']
a = len(x)
print('list: ',x)
print('Len_x:',(len(x)))
print('a :',a)

x.append('orange')
a = len(x) # Note this extra line.

print('list: ',x)
print('Len_x:',(len(x)))
print('a :',a)

The extra line serves to change the value of a. In the beginning, a = len(x) makes a = 3 since len(x) = 3. However, after len(x) becomes 4, we must again assign the value of len(x) to a (that is make a = len(x)). Not doing this means the variable a stays stuck at 3.
Python programs and almost all other programming languages run top to bottom. Once, python runs a particular line, it will keep moving downwards and not repeat that line (unless you specifically ask the Python interpreter to do so).
Answer: a variable refers to len(mylist) : the length of the first list (before any modifications).
It points to the object returned by len(mylist) which is an integer (immutable).
Lists are mutable, hence you can modify them inplace.
But a still refers to the previous integer from len(mylist).
Hence you have to call again len(mylist) after you modified mylist and assign it back to a so a get updated.
Answer: you need to change the value of a after you have changed the length of the list. a still remains 3 until and unless you say a= len(x) again. this would change its value to 4
appended code:
x = ['apple', 'banana', 'cherry']
a = len(x)
print('list: ',x)
print('Len_x:',(len(x)))
print('a :',a)

x.append('orange')

a = len(x) #this has to be done

print('list: ',x)
print('Len_x:',(len(x)))
print('a :',a)

Answer: Most answers explained the how part. Let me explain why python behaves like this.
Python like all other languages reads a script from top to bottom. That means whatever it stored from or changed in the upper part of code stays the same if you don't explicitly change.
Consider the first part of your code:
x = ['apple', 'banana', 'cherry']
a = len(x)
print('list: ',x)
print('Len_x:',(len(x)))
print('a :',a)

In this case

on first line python first create an array of 3 elements. Then assign the array to a reference x. Note that arrays are mutable (meaning they can be altered in place with the code written below of array creation)
on the second line python computes length of x (in this case 3) and assigns the computed integer (3) to a reference a. Note that integers are immutable (meaning you cannot alter the value in place below). Also note that after python assigns the value it forgets where did the integer come from. (meaning python only knows there is an integer. it forgets the fact that this integer represents the length of array)
on third line you print x which prints the array referenced by x
on fourth line you print the length of array. Python again computes the length and prints it (it does not print the value referenced by a)
on fifth line you print a. (this prints the value printed by a)

Now consider the second part of your code:
x.append('orange')

print('list: ',x)
print('Len_x:',(len(x)))
print('a :',a)

When you append a new element, since lists are mutable, 'orange' is added in last of list.
Now you print x. So python retrieves the list (which is now modified) and prints it
Now you print length of x. Python again computes the length of x (which would be 4) and prints the length
Now you print a. The value referenced by a is still 3. Since you haven't explicitly changed a, and since python already forget how the value of a is calculated in the first place, python would simply return the initial value it calculated above.

To rectify this, you could reassign a like this:
a = len (x)

Now python would recalculate the length of modified list and assign it again to a. The problem here is an integer is immutable. Hence python would calculate the new value (4); store it in RAM; and reference a to point that value (4). Since the original value (3) is not going to be referenced anymore, that value (3) will be discarded by python. (Eventually removed from RAM by garbage collector)
Comment: I needed this comment. This cleared many of my confusions about How things work in python. I knew adding a = len(x) after appending works but my main concern was  Why do I need to write it again or are there other alternatives. Thank you very much for clearing the why.


Calculating the possible number of configurations

Question: I am wondering how did they get the $19200$ possible configurations? Like, $5^6 = 15625$, where $6$ is the number of hyper-parameters:

ps: just to check I'm doing the righ thing. Is this okay?
The formula is $[a,b]: b -a + 1$. So in the second screenshot, the total number would be $31 \times 71 \times 71\ \times\ 9 \times 9 = 12.657.951$ possible configurations?
Answer: Each hyper parameter listed has $5,5,6,4,4,8$ different values listed. If multiplied, total number of combinations make $5\times5\times6\times4\times4\times8=19200$.
Comment: Yes, that's the correct formula.
Comment: Check the updated OP. I added another screenshot
Comment: It's always good to be able to reduce the number of possibilities, or ranges if you have continuous variables. Bayesian HPO can do better in short time if you do.
Comment: Thank you very much! They are including the values from the extremes i.e., [2,7], 2 and 7 are included.
Comment: Yes, typically brackets $[,]$ means the boundaries are included.
Comment: This would apply? In a closed interval $
 [a,b]$, the number of integers is $
 b-a+1$.
Comment: I have updated the OP with a new screenshot. Is it okay?
Comment: For the first three, it seems correct but I couldn't be sure if $\log \mathcal U$ represents an integer range with boundaries included. For the fourth and fifth options, the range is not integer, so you cannot apply the formula.
Comment: For integer variables the generated values in logarithm domain are transformed back and rounded to the nearest integer
Comment: I don't get what you mean. You need to specify what $\log U(20,30)$ means.
Comment: This is different than your original question. if the range represented by $U$ or $\log U$ is not an integer range like in $U(0.001, 0.009)$, number of possible combinations without specifying a step size is infinite. Bayesian optimization is a clever way of choosing informative hyperparameters over such a large range of possibilities.
Comment: Such a good answer. Should I consider reducing the number of possibilities?
Comment: Indeed there has to be a threshold or something related because I haven't encountered any research paper where they state that you should limit the number of possibilities in Bayeasian a optimization


Vuex create search filter

Question: I'm new to VueJs and Vuex and I want to create a simple search filter. My app looks like this.

Items -> parent
ItemToolbar -> child
ItemList -> child

Items.vue:
<template>

    <ItemToolbar></ItemToolbar>
    <ItemList :allItems="allItems"></ItemList>

</template>

computed: {
  ...mapGetters(["allItems"])
}

So I try to create a filter in getters called searchByTitle.
const getters = {
 allItems: state => state.items,
 searchByTitle: state => searchValue => {
    const search = searchValue.trim().toLowerCase();
    return state.items.filter(
      item => item.title.toLowerCase().indexOf(search) > -1
    );
   }
};

My problem the value of searchValue will come from ItemToolbar component and I don't know where to use searchByTitle should I call it to ItemToolbar component or in the Items component.
Answer: I would emit event from ItemToolbar.vue to Items.vue, that then will decide which items it have to show: if title is present – filtered, if not – all items.
<template>

   <ItemToolbar @filter="title = $event"></ItemToolbar>
   <ItemList :all-items="filteredItems"></ItemList>

</template>

...
data() {
  return {
    title: '',
  }
},
computed: {
  ...mapGetters(['allItems', 'searchByTitle']),
  filteredItems() {
    return this.title ? this.searchByTitle(title) : allItems
  },
},
...

And emit that title from ItemToolbar.vue:
this.$emit('filter', VALUE_OF_THE_TITLE')

Vuex create search filter


Como adicionar muitos clientes de uma só vez em uma tabela de banco de dados?

Question: Preciso adicionar Nome, Telefone e Endereço de muitos clientes que estão no excel e passar isso para o banco de dados. Qual seria a forma mais rápida de fazer isso ?
Comment: Gerar um csv e mandar importar via linha de comando.
Answer: Exportando para CSV você pode usar o HeidiSQL para importar como nesta dúvida respondida (em inglês)
https://stackoverflow.com/questions/3635166/how-to-import-csv-file-to-mysql-table
ou usar o comando LOAD DATA do MySQL descrito na documentação (em inglês) https://dev.mysql.com/doc/refman/5.7/en/load-data.html
Apenas tome cuidado com um detalhe: devido a numeração o Excel exporta CSV não sepradao por vírgula, mas por ponto e vírgula.


Table doesn't reset when click on X

Question: I have following javascript:
$(function(){
        $table = $('#myTable')
                .tablesorter({
                    theme: 'blue',
                    widthFixed: true,
                    headerTemplate: '{content} {icon}',
                    widgets: ['zebra','filter'],
                    widgetOptions: {
                        zebra: ["even", "odd"],
                        // filter_anyMatch replaced! Instead use the filter_external option
                        // Set to use a jQuery selector (or jQuery object) pointing to the
                        // external filter (column specific or any match)
                        filter_external : '.search',
                        // add a default type search to the first name column
                        filter_defaultFilter: { 1 : '~{query}' },
                        // include column filters
                        filter_columnFilters: true,
                        filter_placeholder: { search : 'Search...' },
                        filter_saveFilters : true,
                        filter_reset: '.reset'
                    }
                })
            // needed for pager plugin to know when to calculate filtered rows/pages
                .addClass('hasFilters')
                .tablesorterPager({
                    container: $(".table-pager"),
                    output: '{page} of {filteredPages} ({filteredRows})',
                    size: 5
                });

        $('#search').quicksearch('table tbody tr', {
            delay: 500,
            show: function () {
                $(this).removeClass('filtered');
                $table.trigger('pageSet'); // reset to page 1 & update display
            },
            hide: function () {
                $(this).hide().addClass('filtered');
                $table.trigger('pageSet'); // reset to page 1 & update display
            },
            onAfter: function () {
                $table.trigger('update.pager');
            }
        });
    });

    (function(b,k,q,r){b.fn.quicksearch=function(l,p){var m,n,h,e,f="",g=this,a=b.extend({delay:100,selector:null,stripeRows:null,loader:null,noResults:"",matchedResultsCount:0,bind:"keyup",onBefore:function(){},onAfter:function(){},show:function(){this.style.display=""},hide:function(){this.style.display="none"},prepareQuery:function(a){return a.toLowerCase().split(" ")},testQuery:function(a,b,d){for(d=0;d<a.length;d+=1)if(-1===b.indexOf(a[d]))return!1;return!0}},p);this.go=function(){for(var c=0,b=
            0,d=!0,e=a.prepareQuery(f),g=0===f.replace(" ","").length,c=0,k=h.length;c<k;c++)g||a.testQuery(e,n[c],h[c])?(a.show.apply(h[c]),d=!1,b++):a.hide.apply(h[c]);d?this.results(!1):(this.results(!0),this.stripe());this.matchedResultsCount=b;this.loader(!1);a.onAfter();return this};this.search=function(a){f=a;g.trigger()};this.currentMatchedResults=function(){return this.matchedResultsCount};this.stripe=function(){if("object"===typeof a.stripeRows&&null!==a.stripeRows){var c=a.stripeRows.join(" "),f=a.stripeRows.length;
        e.not(":hidden").each(function(d){b(this).removeClass(c).addClass(a.stripeRows[d%f])})}return this};this.strip_html=function(a){a=a.replace(RegExp("<[^<]+>","g"),"");return a=b.trim(a.toLowerCase())};this.results=function(c){"string"===typeof a.noResults&&""!==a.noResults&&(c?b(a.noResults).hide():b(a.noResults).show());return this};this.loader=function(c){"string"===typeof a.loader&&""!==a.loader&&(c?b(a.loader).show():b(a.loader).hide());return this};this.cache=function(){e=b(l);"string"===typeof a.noResults&&
            ""!==a.noResults&&(e=e.not(a.noResults));n=("string"===typeof a.selector?e.find(a.selector):b(l).not(a.noResults)).map(function(){return g.strip_html(this.innerHTML)});h=e.map(function(){return this});f=f||this.val()||"";return this.go()};this.trigger=function(){this.loader(!0);a.onBefore();k.clearTimeout(m);m=k.setTimeout(function(){g.go()},a.delay);return this};this.cache();this.results(!0);this.stripe();this.loader(!1);return this.each(function(){b(this).on(a.bind,function(){f=b(this).val();g.trigger()})})}})(jQuery,
                    this,document);

following html:
<form>

        <input id="search" type="search" placeholder="Search" />

</form>

Show
    <select class="pagesize">
        <option selected="selected" value="5">5</option>
        <option value="10">10</option>
    </select>entries |  |
    <button type="button" class="btn prev">←</button>
    <button type="button" class="btn next">→</button>

        One
        Two
        Three
        Four

        abc 123
        10
        Koala
        http://www.google.com

        abc 1
        234
        Ox
        http://www.yahoo.com

        abc 9
        10
        Girafee
        http://www.facebook.com

        zyx 24
        767
        Bison
        http://www.whitehouse.gov/

        abc 11
        3
        Chimp
        http://www.ucla.edu/

        abc 2
        56
        Elephant
        http://www.wikipedia.org/

        abc 9
        155
        Lion
        http://www.nytimes.com/

        ABC 10
        87
        Zebra
        http://www.google.com

        zyx 1
        999
        Koala
        http://www.mit.edu/

        zyx 12
        0
        Llama
        http://www.nasa.gov/

        abc 111
        10
        Koala
        http://www.google.com

        abc 1
        234
        Ox
        http://www.yahoo.com

        abc 9
        10
        Girafee
        http://www.facebook.com

        zyx 24
        767
        Bison
        http://www.whitehouse.gov/

        abc 11
        3
        Chimp
        http://www.ucla.edu/

        abc 2
        56
        Elephant
        http://www.wikipedia.org/

        abc 9
        155
        Lion
        http://www.nytimes.com/

        ABC 10
        87
        Zebra
        http://www.google.com

        zyx 1
        999
        Koala
        http://www.mit.edu/

        zyx 12
        0
        Llama
        http://www.nasa.gov/

        abc 222
        10
        Koala
        http://www.google.com

        abc 1
        234
        Ox
        http://www.yahoo.com

        abc 9
        10
        Girafee
        http://www.facebook.com

        zyx 24
        767
        Bison
        http://www.whitehouse.gov/

        abc 11
        3
        Chimp
        http://www.ucla.edu/

        abc 2
        56
        Elephant
        http://www.wikipedia.org/

        abc 9
        155
        Lion
        http://www.nytimes.com/

        ABC 10
        87
        Zebra
        http://www.google.com

        zyx 1
        999
        Koala
        http://www.mit.edu/

        zyx 12
        0
        Llama
        http://www.nasa.gov/

It works almost good. I have one issue only.
When I click X to reset filter - nothings to happens.
desired result - filter should reset and table should update.
Also I have a problem when I erase symbols in search field - table don't update

How to fix this issue?
Answer: It looks like the quicksearch demo no longer works properly.
So, instead of using the quicksearch plugin, you could use the filter widget to match content in all columns:
<input class="search" type="search" data-column="all">

then include that input as an external filter, and hide the filter row
filter_external : '.search',
filter_columnFilters: false

To do the same thing, and have the "x" in the input work properly.
Full code & demo:
$(function () {
    $table = $('#myTable')
        .tablesorter({
            theme: 'blue',
            widthFixed: true,
            headerTemplate: '{content} {icon}',
            widgets: ['zebra', 'filter'],
            widgetOptions: {
                zebra: ["even", "odd"],
                filter_external: '.search',
                filter_columnFilters: false
            }
        })
        .tablesorterPager({
            container: $(".table-pager"),
            output: '{page} of {filteredPages} ({filteredRows})',
            size: 5
        });
});

Answer: have already tried adding needed plugin in head section

<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/jquery.tablesorter/2.21.5/addons/pager/jquery.tablesorter.pager.min.css">

Table doesn't reset when click on X


Scala: hierarchy of typeclasses and implicit resolution

Question: Suppose I'm trying to represent, say, the domain of boolean logic (ignoring reduction for now). So I'll have in my store instances of Bools, or Ands and Ors or Nots etc. However, whilst I'll have concrete representations for these things, in many cases all I'll care about is that something can, say, be viewed as a Bool, or as a combination of two Bools (this doesn't quite make sense here, but the bigger example is some kind of heterogenous data store where I might request, say, all things that might have a colour). There are multiple potential hierarchies, so subclassing doesn't really cut it, and since I want to avoid explicit conversion, typeclasses seem to be the way to go. So I have something like this:
trait Delegated[-B, +A] {
  def bind(b : B) : A
}

trait Thing[A <: Thing[A]] {
  type Class[B] = Delegated[B,A]
}

trait BoolLike extends Thing[BoolLike] {
  def value : Boolean
}
class Bool(val value : Boolean) extends BoolLike

Now, however, to avoid repeating myself, I would like to specify that, for any Thing, a subclass will satisfy Thing#Class. So my attempt at this was the following:
implicit def SubclassIsClass[A <: Thing[A], B <: A] : A#Class[B] = new A#Class[B] {
  def bind(b : B) = b
}

However, if I do
implicitly[BoolLike#Class[Bool]]

I get no evidence, yet I can quite happily call SubclassIsClass[BoolLike, Bool] and get an appropriate Delegate. Should this be implicitly inferrable?
Answer: Solved it - if I change
trait Delegated[-B, +A]

to
trait Delegated[B,A]

then this works. Given that the annotations were left over from a different way of doing things, this seems like a fine solution.


Alternative to Field Collection

Question: Does anyone know an alternative to the module "field collection" ?
While the concept of field collection is very good, I'm having trouble with the collaboration of other modules, like e.g. features or search api. So I'm looking for alternatives.
Comment: Field collection really is the top drupal module for solving problems if it's class. I have found it's support across different modules is great. It works with features, and you simply have to make sure your display preferences are setup  correctly for it to work with search.
Comment: Sam, I'm not sure what you mean by "correct display preferences". Can you please clarify?
Answer: See the Multifield module.

This project seeks to provide a true compound field solution for
  Drupal 7. As much as I love Field collection, it still has to save
  actual entities, and can cause performance problems due to having to
  load all the referenced field collection entities on node, or parent
  entity load.

I am not sure of its compatibility with Features or Search API though.
Comment: That module is currently "unstable" so use with caution on a dev site, but definitely don't use on a live site without heavy testing
Comment: Unfortunately Feeds does not support multifield import out of the box so this may not be a viable option if you are looking to import data in to this field
Comment: The "Related Links" section on the multifield module page is helpful.
Answer: Try the Paragraphs module, it integrates with Search API and Features.
Comment: Yes, paragraphs is best alternative to Field_collection.
Answer: You could consider creating a new content type to represent the collection and then using Inline Entity Form to allow creation of the 'collection' inside of the content type referencing it. See: Inline Entity Form.
Comment: But does this integrate with Search? I want to get the "whole Page" as a search result and not only the "inline Content Type" ?
Comment: I am not sure what you mean by 'whole page' as a search result. Can you clarify?
Comment: For example: I'm using the Content Typ "B" within my Content Type "A" as an Inline Entity Form just as you described (this Content Type B contains the string "test"). When I now search for the string "test" - what will I get as the search result? From my point of view it must be the node of the Content Type B. But want I want is the node of the Content Type A (that contains the CT B).
Comment: This is essentially what field collections accomplish, but in a far more streamlined manner.
Comment: Thanks for the detailed explanation scar. Looking at Search API there is an issue queue explanation that essentially says: if the contrib module is correctly built then yes. (https://drupal.org/node/1118282) Since IEF supports Entity Reference module fields that would be the module to check. The issue queue there does seem to indicate that it *should* work with this issue here: https://drupal.org/node/1651606.
Comment: The above link was broken by a typo (a period). For your convenience:
[Inline Entity Form](https://www.drupal.org/project/inline_entity_form)

Alternative to Field Collection


What causes consonance in music?

Question: I am trying to understand why certain pitches or notes sound pleasant together and others doesn't. So far my understanding is that simpler ratios between the frequencies of the notes means they are more consonant. But why is it that way? Because of the overtones? If so then can two or multiple sine waves be consonant or sound pleasing?
Edit: I am using the piano as a reference for this question. Please feel free to correct me If I've misunderstood since I am quite new to this.
Comment: You might want to check out questions with the [consonance-and-dissonance](https://music.stackexchange.com/questions/tagged/consonance-and-dissonance) tag to see if they offer anything helpful.
Answer: A short and simplified answer is that it can be explained with where the peaks of the waves line up with each other. For one example, if the wave peaks line up in regularly spaced intervals, such as when you have a 2:1 ratio (octave), then you will hear a smooth sound. If the peaks are closer and irregularly spaced, we perceive it as a grinding or dissonant sound.
An imperfect visualization of the effect would be when you throw rocks into a pond. If you throw in two rocks to a place where the waves end up matching each other, you will either get more evenly spaced waves, or taller single waves.
If you throw the rocks to where the waves cross each other you will get crossing peaks and valleys with odd bumps in the pattern.
The matching waves could be considered consonant, the peaked waves dissonant.
Comment: Thanks a lot for your answer I really appreciate it! It made things clearer.  However if two sine waves can have consonance due to simple ratios how does the overtone/harmonic series fit in the picture? Whats the relationship between the harmonic series and consonance?  Im very grateful for some more clarification on the subject.
Answer: Sound waves can be looked at from a 'time domain' or 'frequency domain' point of view. Alphonso's answer is a good one from a 'time domain' viewpoint; I'll answer from a 'frequency domain' angle.
As I mention in this answer, the human ear analyses sound in the frequency domain - it is constantly monitoring how much energy there is at each frequency. However, the auditory system also tries to simplify things for us by working out which points of energy excitation are at multiples of the same frequency, and are thereby likely to be components of the same sound.
This mechanism isn't only triggered by sounds that are integer multiples - it can also kick in when we have other simple rations. For example, if we have a sine wave at 500 Hz, and another at 750 Hz, they're both multiples of 250 Hz - this doesn't necessarily mean we'll hear the combination as a 250Hz tone, but they will sound consonant together. To relate this to Alphonso's answer, every third peak of the 750Hz tone (or possibly a different point on the wave, depending on phase) would line up with every second peak of the 500Hz one.

If two sine waves can have consonance due to simple ratios how does the overtone/harmonic series fit in the picture?

Consonance / dissonance is a result of the full set of partials the ear can hear. You don't need to draw a logical line between the fundamental and the overtones; they're all in the mix together.
If each sound has more partials, there are more frequency points for the ear to try to 'make sense of' and find relationships between. This can have different effects on the level of consonance - for example, if you play a nice perfect fifth (or as near as you can get, given the piano) somewhere in the middle of the piano, there are more groups of partials with simple ratio relationships, and you'll get a lovely rich sound. On the other hand, if you play a fifth down at the bottom of the piano, you'll get a more dissonant sound, as the low harmonics are weaker, and the higher harmonics ae more stretched due to string stiffness.

What causes consonance in music?


Add Special Characters in Editor

Question: In CKEditor source view I wrote Jiří for Jiří and save in mysql db it looked fine on browser but when I open in edit view but without any change save & recheck browser shows Ji?í I am using
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
do I need to specify another character-set (UTF-16?) in the  tag.
Answer: Fixed: I follow HOW TO:Produce UTF-8
 my related point was:

Ensure your database (if you are using one) is set to accept UTF-8 or
Unicode (UCS-2) characters.

Add Special Characters in Editor


How to restore a logical Volume Group with missing devices?

Question: I have a volumegroup which consists of three harddisks and several LVs (var,tmp,root,swap).
One of the harddisks crashed recently, but i urgently need some data from LV var.
So, after rebooting the machine without the crashed disk, i run
vgchange -D -a y volGroup0

in order to activate the volumegroup and mount the logical volumes.
However, the command returns
Cannot activate XXX. All segments are missing
...
0 logical volume(s) in volume group "volGroup0" now active.

What does that mean? Is all data lost? What could be the next step in order to rescue some data?
Comment: Were you using dm-RAID at all, or just spanning multiple PVs with volGroup0?
Answer: In order to recover the data (note that any data on the failed disk is lost), you'll need to replace the failed disk with a new one and rebuild the LVM. You won't be able to mount the group otherwise.
To do this, you'll need to know the failed disk's UUID by using pvscan. It'll say that a UUID is missing and this is what you need.
Then, when you have the new disk in the server, type: pvcreate --uuid uidhere /dev/sdc where "uidhere" is the UUID you got from pvscan and /dev/sdc is the new disk device.
Then, type vgcfgrestore volgroupname where volgroupname is the name given to the volume group (so vgcfgrestore volGroup0).
Then, type vgscan to recover the volume group. And finally, vgchange -ay volGroup0 to activate the group. You'll likely need to e2fsck the affected partition if it's unreadable.
Reference: http://www.novell.com/coolsolutions/appnote/19386.html#DiskPermanentlyRemoved


Infinite sum of a function $g(n)=\sum_{d|n \; d\ne n}g(d)$

Question: Let the function $g:\Bbb{N}\to\Bbb{N}$ be defined as  $$g(n)=\sum_{d|n \; d\ne n}g(d)$$
with $g(1)=1$, how can we evaluate a sum like $$\sum_{i=0}^\infty{g(15^i)\over15^i} \tag1$$
Need we find a closed form for $g(n)$? I have tried to do this with the Möbius inversion formula, but it has not gotten me anywhere. If we add $g(n)$ to both sides of the definition
$$2g(n)=\sum_{d|n}g(d) $$
I'm unsure if it is acceptable to use the Möbius inversion formula on $2g(n)$, but if it is then
$$g(n)=\sum_{d|n} \mu(d)\cdot2g\left(\frac nd\right) \Rightarrow g(n)=-2\sum_{d|n \; d\ne n}\mu(d) \,g\left(\frac nd\right)$$
but I don't think this is very useful.
It also doesn't help that $g$ is not multiplicative and I can discern no easy pattern from a table of its values here. Clearly $g(p)=1$ and the more divisors a number has, the greater the output is. How can I quantify this exactly?
EDIT
I have found that $g(n)$ is the same as the number of ordered factorizations of $n$, so in $(1)$
$$\begin{align}
g(15^i)&=g(3^i5^i)=2^{2i-1}\sum_{k=0}^i {i\choose k}^22^{-k}\\
\Rightarrow 1+\sum_{i=1}^\infty{g(15^i)\over15^i} &=1+\sum _{n=1}^{\infty } 2^{2 n-1} 15^{-n} \, _2F_1\left(-n,-n;1;\frac{1}
{2}\right)
\end{align}
$$ Where $F_1$ is a hypergeometric function. Based on some partial sums I think this goes to $\frac{11}{7}$ How can we show this by hand?
Comment: @ThomasAndrews Thanks, fixed
Comment: $g(p^2)=g(1)+g(p)=2$. $g(pq)=g(1)+g(p)+g(q)=3$. $g(pqr)=13$. Try to find a formula for $g(15^i)$.
Comment: See [OEIS A$002033$](http://oeis.org/A002033) and [OEIS A$074206$](http://oeis.org/A074206).
Comment: @Lucian I noticed that, thanks! I included it in the edit
Answer: Just the start of an idea, really.
Define $h(1)=1$ and $h(n)=-1$ if $n>1$. Then:
$$(g*h)(n)=\begin{cases}1&n=1\\0&n>1\end{cases}=I(n)$$
where $I(n)$ is the identity under the Dirichlet convolution.
Now, as it turns out $h(n)=2I(n)-\mathbf 1$.
So, $g*(2I-\mathbf 1)=I$ or $g*(I-\mathbf 1/2)=\frac{1}{2}I$.
Let $f_0=I$ and $f_{k+1}(n)=(1*f_k)(n)=\sum_{d\mid n} f_k(d)$.
Then $f_k$ is multiplicative, by induction, and we can show that for $k>1$:
$$f_k(p^m)=\binom{m+k-1}{k-1}$$
Let $u = \sum_{k=0}^{\infty} \frac{1}{2^k}f_k$.
Then $u*(I-\mathbf 1/2)=I$, by the usual power series argument, when the series converges, so $(u/2)*(2I-\mathbf 1)=I$, so $u/2=g$
For example:
$$\begin{align}g(p^m)&=\frac{1}{2}\sum_{k=1}^\infty \frac{1}{2^{k}}\binom{m+k-1}{k-1}\\
&=\frac{1}{4}\sum_{k=0}^{\infty} \frac{1}{2^k}\binom{m+k}{k}\\
&=\frac{1}{4}\frac{1}{\left(1-\frac12\right)^{m+1}}\\
&=2^{m-1}
\end{align}
$$
Which is the value you see when you just compute by hand.
Using the above formula for $g$, since $f_k$ is multiplicative, $f_k(15^i)=f_k(3^i)f_k(5^i)$, and we have:
$$g(15^i)=\frac{1}{4}\sum_{k=0}^\infty \frac{1}{2^{k}}\binom{i+k}{k}^2$$
This means you might want to look at the double power series:
$$\sum_{i,k=0}^\infty \binom{i+k}{k}^2 x^iy^k$$
where $x=\frac{1}{15}$ and $y=\frac{1}{2}$.
But more generally, that series for $g(n)$ is not symmetric for all $n$.
For example:
$$\sum \frac{g(12^i)}{12^i} = \sum_{i,k=0}^\infty \binom{i+k}{k}\binom{2i+k}{k} \frac{1}{2^k12^i}$$
I'm not sure that gets you any closer to a value for the series you want...


What is the simplest data source for a cloud-init home lab?

Question: I'm using cloud-init 22.1-14 to spin up VMs using Ubuntu cloud images and kvm/qemu on a home server. I think I'm at the stage where I need to implement a data source because my VM creation dies if I try to write arbitrary files as a part of my init. Here's what I do to generate an ISO image containing the configuration data.
cloud-localds --network-config=/srv/init/network-init.cfg /var/kvm/mldc-seed.qcow2 /srv/init/cloud-init.cfg

Here's an example of me trying to write a .tmux.conf file using syntax that does not work with cloud-init 22.1-14.
write_files:
  - path: /home/msh/.tmux.conf
    content: |
          unbind C-b
          set -g prefix C-a
          bind-key C-a last-window
          bind-key k confirm kill-window
    owner: 'muh:adm'
    permissions: '0640'

Since I paid attention to the version of cloud-init I had installed, my ability to write arbitrary files has improved. Now I can write any number of text files without breaking the cloud-init run.
write_files:
  - content: |
      set ts=2
      set sts=2
      set sw=2
      set expandtab
path: /home/msh/.exrc
owner: root:root
permissions: '0660'
defer: true

Comment: I have learnt that I can tail
/var/log/cloud-init.log
and
/var/log/cloud-init-output.log
on the VM to find errors. Previously I had been looking at log files on the hypervisor (host), and that wasn't useful.
Comment: And by 'on the VM' I mean _in_ the VM.
Answer: The data source we use if we don't use a third party or 'external' data source is called NoCloud. Running cloud-localds locally means you're using NoCloud.


How Firm to hold Bansuri

Question: I understand that one must blow softly on Bansuri, as if cooling a food item.
But what about how firm to hold Bansuri. I noticed my hands got tired after 6 minutes of playing because I held onto the Bansuri holes tightly.
Any guidance?
Comment: It's somewhat like beginners playing guitar. They feel they have to press really, really hard on the strings. After a while, they realise that just enough pressure does the job just as well. You must do the same. By closing a hole really really hard, is it better than just closing the hole? Of course not, so experiment and use *sufficient* finger pressure over the holes, not more than is needed. Balance of the bansuri will also mean no need to hold on to the instrument to stop it falling.
Answer: As with any wind instrument you should only hold the instrument tightly enough to keep it stable, but no tighter. The problem with any flute type instrument is the balance and that takes some practice to get secure. Once you have the instrument balanced in your hands you need almost no finger pressure, just enough to keep the holes fully closed. Concentrate on precise finger movement rather than strength.
One cause of your hand tiredness might be the finger stretch, particularly if you are playing a larger instrument. You just need to start slowly and build up your endurance.
Answer: It is very hard to describe "how to hold" without showing ...  Assuming you have a bass bansuri, otherwise the grip is pretty straight forward.
The fingers should lay on the holes without any force. Make sure you can hold the flute in balanced position with all of the holes open. Then try to to close the first three holes with your left hand fingers (I assume you're right handed) by just laying down the fingers on the holes. The index finger should cover the hole with a knuckle ,same with the second hole. only the ring finger should cover the hole with a tip.
The same goes with the right hand — just lay the fingers down on the holes in a natural manner, and that should be the basic grip from which you can begin.

How Firm to hold Bansuri


How to add custom text settings to a custom theme?

Question: I'm working on a custom theme called "YingYang". I didn't make the theme, but I have to do some stuff with it. The theme has custom text settings which is bassically some pre-set content.
It looks like this

Now my question is: How can I create a new text setting for this theme?
I've been searching for a while in the drupal UI and in the code, but I can't find anything about it.
Thanks!
Comment: Do you want to give new text in this field or want to add a new textarea field..??
Comment: create a new option (add new textarea field)
Comment: You can use this manual http://www.metaltoad.com/blog/how-add-theme-settings-drupal-7
Answer: Right now this option in your theme is in configuration setting. I think they done it using some custom module. Edit the module file, add a new text area using following code..
<code> $form['name']= array(
'#type' => 'textarea',
'#title' => t('Main Address'),
</code>
);
Save the
<code>$form_state['values']['name']
</code>
using variable_set('name' , value) in form submit. Then retrieve variable in template using variable_get('name').
Another easy method is just edit your theme-settings.php. Add a new textarea field. you will get the field in your Home » Administration » Appearance » Settings.
 You can access that value using
<code>theme_get_setting('field name');
</code>
Hope this will helps you...


I am trying to ping www.google.com using JAVA in my office but it is not pinging the same

Question: I am trying to ping www.google.com in my office network but it is not pinging. Code which i am using is as follows:
<code>import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;

public class demo1 {

    public static void main(String[] args) throws UnknownHostException, IOException {
        try {
            String  address = InetAddress.getByName("www.google.com").getHostAddress();
            InetAddress inet = InetAddress.getByName(address);
            System.out.println("Sending Ping Request to " + address);
            if(inet.isReachable(50000)){
                System.out.println("Host is reachable");
            }
            else{
                System.out.println("Host is not reachable");
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}
</code>
I dont know what is the issue. It cant ping to www.facebook.com or www.youtube.com. I get "Host is not reachable" but it can ping to my office internal systems. In the browser all these external systems like google.com opens but Why it can't ping, I don't know. So, can anyone please help me with this?
Comment: Does PING command SUCCESS on your Office Machine?
Comment: use proxy settings of your internal network
Comment: The router that connects your office network to the internet might not pass PING packets on, and external servers may not respond to PING anyway.
Comment: Could be a security thing. I wrote a program to post tweets, but it wouldn't connect to Twitter unless I ran it in Administrator mode.
Comment: Is there any alternative pgm using which I can ping external systems in java??
Answer: There are many other preferred methods of pinging a server, and it appears like isReachable() has some definite design flaws. This has been addressed here: Why does InetAddress.isReachable return false, when I can ping the IP address?


htaccess - creating directories and files of the same name

Question: I want to create a bunch of files without an extension showing at the end.  The easiest way to do that was to do this:
/usa/index.php
/usa/alaska/index.php
/usa/alabama/index.php
/usa/california/index.php

What I want to do is this
/usa/alaska.php
/usa/alabama.php
/usa/california.php

and have it show up as:
/usa/alaska
/usa/alabama
/usa/california

However, I have one more level I want to add to this, the cities
/usa/alaska/adak.php
/usa/alaska/anchorage.php
/usa/california/los-angles.php

I don't want the ".php" showing up, but then each state exists as both a file and a directory.  What I want is an htaccess rule that serves up the file version of the file, not the directory which is the default.  I also want to strip the .php off of the end of the files so the final result looks like
/usa
/usa/alaska (alaska.php)
/usa/alaska/adak  (adak.php)

I know I can get close to this by creating all the directories and using index.php for each directory, but then I will have thousands of directories each with one file in it and updating is a pain in the butt.  I would much rather have one directory with 1000 files in it, than 1000 directories with 1 file in it.
Please, can someone point me in the right direction and know that I am doing this for all 50 states.
Jim
Comment: Do you really need a separate `php` file for each state and each city in a state?
Answer: I would also suggest using a single php (e.g. index.php) file and redirecting all urls starting with usa to it, instead of separating them in different directories and files. The you'd need a couple of rewrite rules like the following
RewriteEngine On
RewriteRule ^usa/([^/.]+)$ index.php?state=$1 [L]
RewriteRule ^usa/([^/]+)/([^/.]+)$ index.php?state=$1&city=$2 [L]

So then in your index.php you'd only need to check the $_GET parameters.
Update:
If you don't feel comfortable enough to use a database and pull the needed data from there you could always use the parameters to dynamically include/require the needed files. Something like this
<?php
    $source = ''; //or the 'ROOT' directory
    if(isset($_GET['state'])) $source .= $_GET['state'].'/';
    if(isset($_GET['city'])) $source .= $_GET['city'].'.php';
    include($source);  // here $source would be something like 'alaska/adak.php'
                       // and is assumed that the dir 'alaska' is on the same
                       // level as 'index.php'
?>

But to answer your original question nevertheless you could use the following .htaccess
RewriteEngine On
RewriteRule ^usa/([^/.]+)$ usa/$1.php [L]
RewriteRule ^usa/([^/]+)/([^/.]+)$ usa/$1/$2.php [L]

Comment: Thank you, I had a similar idea last night, where it pulls the right file. Eventually, I could expand the file to dynamically pull from the database, but at that point I would want to include, in this case, CubeCart's database cache.  In effect, that is what I'm doing here, a poor man's cache.
Comment: Havelock, this would mean I would have to upload my database and dynamically create my pages on the fly.  I'm not sure I have the skill in PHP to do that.  It is easier for me to create a single php file with all the variables and store that on the computer.
Comment: @JimCubbageJr That would be one possibility. Another one would be to include(display) dynamically html/php files based on the `state` and `city` parameters.
Comment: @JimCubbageJr I updated my answer to exactly match your question now :)
Comment: Note: Answer to original question is incomplete.  I tried what you said, the problem is that if alaska.php and /alaska/ both exists, it will always server the directory to the browser, not the file.
Comment: after playing with this for a while, I believe your first suggestion is the best way to go as I can handle errors better.  Of course, I have to use PHP for regular expression matching.
Answer: what about creating just one single file:
/usa/index.php

With
$_SERVER["REQUEST_URI"]

you can read the current URI.
Well, now if a user enters "http://domain.foo/usa/alaska" for example, he will get an 404 error of course.
But to call your index.php instead, you could write this line to the .htaccess:
ErrorDocument 404 /usa/index.php

Now the index.php receives everything what is written to the URI and you can match the result and include files or handle errors.
But maybe there is a better solution with .htaccess only, don't know. :)
Comment: I will have to check that solution, but I think the search engines will see the 404 in the header chain and invalidate every page below.
Comment: But even so, it does not get me beyond my current problem of trying to access /usa/alaska (alaska.php with extension removed) the file, vs having the web server show the directory of /usa/alaska/.


Logistic Regression: Interpreting Continuous Variables

Question: I had a couple of questions about interpreting odds ratios for continuous variables in logistic regression. I feel like these are basic questions about logistic regression (and probably about regression in general), and although I'm slightly ashamed that I don't know the answers, I'm gonna swallow my pride and ask them so I know them in the future!
Here's my situation...I'm looking at a sample of adjudicated youth who, as part of their probation, were enrolled in a job/life skills training program. I wanted to see the extent to which the age at which they were released from the program predicted employment six months post-release from the program.
(Also, keep in mind that there are other predictors in the model, but I've excluded them because they are not statistically significant and I want to keep this as clear as possible.)
Predictor:
Age of release from training program (Mean age = 17.4, SD=1.2, Range 14.3-20.5)
Outcome:
Employed or not (Employed=1, Not Employed=0)
Result:
Odds ratio 3.01 (p<.005)
(I've excluded goodness of fit stats, etc. because I'm seeking answers about the interpretation of the odds ratio only; I feel comfortable w/ the evaluation of model fit, CI's, etc.)
Putting it into words:
As age increases by one year, the odds of being employed six months post-discharge increase by three units.
Questions:
1) When I say, "As age increases by one year..." what is the starting point for age?
Does age start at zero? For example, "As age increases from 0 [i.e., the lowest age if you were to place this model on a graph]..."
Does age start at the the lowest age among the range of ages in the sample? For example, "As age increases from 14.3..."
OR
Does age start at the mean age of the sample? For example, "As age increases from 17.4...",
2) Would centering help me interpret this result OR is that only effective in interpreting the y-int?
If it would help, I was thinking of doing either mean centering or subtracting the lowest age in the range from all the other ages in the sample.
Any suggestions?
3) Finally, is it appropriate to say that compared to a 14-year-old youth, a 17-year-old youth is nine times more likely to be employed?
I ask because I know that logistic regression assumes a sigmoidal relationship, and I'm curious as to whether this 3 unit increase in odds remains consistent at any point along the regression line.
Thanks so much!
Aaron
Comment: Removal of "insignificant" variables is very problematic.
Comment: You might be interested in [this](http://stats.stackexchange.com/a/42960/8141).
Comment: @FrankHarrell could you elaborate on why removing insignificant variables is very problematic in this case?
Comment: This has been discussed at length on this site.  Briefly it ruins standard errors, P-values, confidence interval coverage, etc.
Answer: 1) Since it is an odds ratio it doesn't matter where you start. The odds for an 18 year old are 3 times those for a 17 year old. Or the odds for a 17 year old are 1/3 those of an 18 year old. Same thing.  If you want to get the probability that a person of a particular age will be employed, you can use the formula with the parameter estimates (not the ORs). Or you can get the program you are using to do it for you.
2) Whether centering helps is a matter of opinion. I don't find centered models clearer, but some people do.
3) The odds are not exactly the same as "likely" (although many people speak as if they were) and the odds for a 17 year old would be 27 times those of a 14 year old.
Finally, I'd be cautious about this model. The model assumes that the OR is the same between 14 and 15, 15 and 16 and so on. That seems unlikely to me, based on what I know about the subject.
Answer: The average odds of enrolling in the training problem for an individual is # times the odds for another individual who are one year younger/older, after holding all other variables constant.
That's my take.
Comment: Can you expand on how this adds to the previous answer?


For a sequence of positive real numbers converging to a limit (which is not equal to 0), show that infimum > 0

Question: I think to do this I either need to prove the infimum is a minumum or a limit but I'm not sure how.
I have tried this:
By definition of the infimum:
" Let A be a subset of the real numbers and b be a real number.
Then b is the infimum of A if:
(i) b≤a for all a ∈ A
(ii) c≤a for all a ∈ A will imply that c≤b."
We know for all a ∈ A, a>0.
If we consider the second case, this means the infimum (b) is such that 0≤b.
We can assume for a contradiction that b = 0 in order to leave just the case 0 < b.
b cannot be the minimum of the set, as all a > 0.
because all the terms are positive, for the infimum to be 0, it means the limit of the series is zero (and the sequence must be decreasing), but L cannot be equal to 0 so we have a contradiction.
This highlighted bit is the jump I'm struggling with.
Comment: What have you tried so far ?
Answer: Hint:  you can use the fact the sequence converges to say the inf of all the numbers past some point $N$ is greater than, say, half the limit.  Just get $N$ from whoever told you the sequence converges by giving them $\epsilon$ as half the limit.  Now there are only finitely many numbers out to $N$.
Comment: Doesn't that assume it's a decreasing sequence?
Comment: @timtfj:  Not at all.  As long as the sequence converges to $L$, there is some $N$ so that all the terms past $N$ are within $(\frac L2, \frac {3L}2)$ by using the $\epsilon-N$ definition with $\epsilon=\frac L2$.  It can bounce around however it wants.
Comment: Maybe I've misunderstood what you mean, but II if for example it converges upwards to the infimum of the sequence, the whole sequence is below its own infimum, surely? So the infimum isn't the infimum.
Comment: @timtfj:  No the inf of the sequence is the largest number that is less than or equal to all the terms of the sequence.  If it is increasing all the terms are below the limit.  If the sequence is $1-\frac 1n$ for $n=3,4,5,\ldots$ the limit is $1$ but the inf is $\frac 23$
Comment: My problem is that the first sentence of your answer, seems to say that the infimum (past some N) *is* the limit. Am I misunderstanding?
Comment: @timtfj:  yes, you are misunderstanding.  The point of the problem is that you can have a set of positive numbers with infimum $0$.  An example would be the sequence $\frac 1n$.  We want to prove that if you have a sequence of positive numbers that converges to a positive limit, the infimum of the set is strictly positive.  I am saying that all the terms past $N$ are at least $\frac L2$, so the inf of all those terms is at least $\frac L2$.
Comment: Now I realise I was misreading an ambiguous phrase: parsing it as *the sequence converges to, say, the inf of all the numbers...* Amazingly most of the sentence still holds together when misread that way! Sorry for the bafflement.
Answer: Outline of what I'd try:
The limit can't be negative, since then terms approaching it would be negative. Its not allowed to be zero, so is positive.
Call the sequence $(x_n)$ and the limit $k$. Choose an $\epsilon$ such that $k-\epsilon >0$.
Beyond some $n=N$, all $x_n>k-\epsilon$ because of the convergence.
The first $N$ terms are all positive by definition, and have a minimum value $m$.
If the infimum is below both $m$ and $k-\epsilon$ it can't meet the definition of an infimum. So it's $\ge$ the lower of them, which is positive. Therefore the infimum is positive.
I think that does it, once it's translated into more precise language. (My aim here is to make it as human-readable as I can, to make clear how it works.)
Comment: This is an elaboration of my hint.  I thought it better to leave more to OP.
Comment: It is, but as I totally misread your hint I didn't know I was elaborating it. I only realised the correct reading just now. My initial version of this was pretty vague and and in the end I decided enough hours had gone past for more detail to be OK.
Answer: Let $(x_n)$ be a sequence of positive real numbers such that $ \ \displaystyle \lim_{n \to \infty} x_n = L \neq 0 \ $. As $ \ \frac{|L|}{2}>0 \ $, by definition, there exists $ \ N \in \mathbb{N} \ $ such that, for all $ \ n \in \mathbb{N} \ $, if $ \ n>N \ $, then $ \ |x_n - L|< \frac{|L|}{2} \ $.
Let $ \ A = \{ 0,1,2,3,...,N \} \subset \mathbb{N} \ $, $ \ B = \mathbb{N} \setminus A = \{ N+1, N+2, N+3, ... \} \subset \mathbb{N} \ $ and $$m= \min \{ x_0 , x_1, x_2 , x_3 , ... , x_N \} \ .$$ Then $ \ \mathbb{N} = A \cup B \ $ and $ \ A \cap B = \varnothing \ $. Hence, for all $ \ n \in \mathbb{N} \, $, we have either $ \ $ (i) $ \ n \in A \ $ or $ \ $ (ii) $ \ n \in B \ $, for which

(i) $ \ $ if $ \ n \in A \ $, then $ \ 0 < m \leq x_n \ $ ;

and

(ii) $ \ $ if $ \ n \in B \ $, then $ \ n \in \mathbb{N} \ $ and $ \ n >N \ $ and we have that $ \ |x_n - L|< \frac{|L|}{2} \ $. Therefore $$|L| -|x_n| \leq \big| |L| - |x_n| \big| \leq |L - x_n| = |x_n - L| < \frac{|L|}{2} \ , $$ that is, $$x_n = |x_n|>|L|- \frac{|L|}{2}= \frac{|L|}{2} >0 \ . $$

Choosing $ \ c = \min \left\{ m , \frac{|L|}{2} \right\} \ $, we get that $ \ x_n \geq c>0 \ $, $\forall n \in \mathbb{N}$. So $ \ c>0 \ $ and $c$ is a lower bound for $(x_n)$. We conclude that $ \ \displaystyle \inf_{n \in \mathbb{N}} x_n \geq c > 0 \ $.
Comment: This is what I hoped I could get OP to produce.
Answer: When studying new mathematical material, an attempt must be made be to write down 'the setup' in a mathematically precise way, and to avoid using logical arguments that use the informal language of, say, English.
The setup:
$\tag 1 \lim\limits_{n \to +∞} a_n = L, \text{ with } L \gt 0 \text{ and } a_n \gt 0$
$\tag 2 A = \{ a_n \, | \, n \in \mathbb N\}$
$\tag 3 b = \text{inf}(A)$
Assume $b = 0$.
Using open intervals of the form $(0, \varepsilon)$, a strictly decreasing sequence  $b_n$ with $b_n \in A$ can be constructed such that
$\tag 4 \lim\limits_{n \to +∞} b_n = 0$
Now $b_n$ might not be a subsequence of $a_n$, but you can take another pass over it, throwing out terms if necessary to get the desired subsequence. Since every subsequence of $(a_n)_{ \, n \in \mathbb N} $must have the same limit, $L = 0$, we arrive at a contradiction.
Note that you can construct $b_n$ as a subsequence on the first pass, but thought it might be easier to follow by breaking it into two steps. The basic truth is that for any finite set of positive numbers, an $\varepsilon \gt 0$ can be found such that the open interval $(0, \varepsilon)$ is disjoint from that set.

The OP states in bold

it means the limit of the series is zero (and the sequence must be
  decreasing)

Let $(a_n)_{ \, n \in \mathbb N} $ be defined by
$$
    a_n  = \left\{\begin{array}{lr}
        \frac{1}{n+1}, & \text{for } n \text{ even }\\
       \frac{1}{n-.5}, & \text{for } n \text{ odd }
        \end{array}\right\}
$$
This sequence of positive numbers converges to $0$, but it is not a decreasing sequence
(see the wikipedia definition).


Paste data from the first empty line of a specific column

Question: I'm trying to paste datas from a workbook into another one. I need to import those datas on the first empty line of a column. Since this column may contain blank cells, I have to determine the first empty line thanks to another column in which no blank cells is possible.
I wrote this code:
=> To determine first empty line:
Dim n
With Worksheets("Dest")
n = .Range("L" & .Rows.Count).End(xlDown).Row + 1
End With

=> To paste at the right position:
For j = 0 To (finas - debutas)
Worksheets("Dest").Cells(n, debutad + j) = Vcol(j)
Next j

But the system keeps pasting the datas on the first line...
What did I do wrong ?
Thanks for answers ! :)
Answer: You are not incrementing n in your loop.
For j = 0 To (finas - debutas)
  Worksheets("Dest").Cells(n, debutad + j) = Vcol(j)
  n=n+1
Next j

'or

For j = 0 To (finas - debutas)
  Worksheets("Dest").Cells(n+j, debutad + j) = Vcol(j)
Next j


Apply multidimension array data to an object

Question: For a given PHP object (loaded from CouchDB) $obj:
class stdClass#1 (3) {
    public $_id =>
    string(10) "nochecksum"
    public $_rev =>
    string(34) "1-4f734a24465bf7ba2de316fe87ffa0c1"
    public $rooms =>
    class stdClass#2 (1) {
        public $kitchen =>
        class stdClass#3 (1) {
            public $ceilingFan =>
            bool(false)
        }
    }
}

And for a given multidimensional array of data $arr, consisting of changed or new values for properties:
array(1) {
    'rooms' =>
    array(1) {
        'kitchen' =>
        array(1) {
            'needsCleaning' =>
            bool(true)
        }
    }
}

How is it possible to set $obj's properties to be values from $arr?
The solution is simple for a single dimension array:
foreach ($arr as $k=>$v) {
    $obj->{$k}=$v;
}

I tried with a recursive function, but I don't know how to reference the parent(s):
$obj = setObjectFromArray($obj, $arr);

function setObjectFromArray($obj, $arr, $tree=Array())
{
    foreach ($arr as $k=>$v) {
        if (is_array($v)) {
            $tree[]=$k;
            $obj = setObjectFromArray($obj, $v, $tree);
        } else {
            // Here $tree is Array('rooms','kitchen')
            // I want to set $obj->rooms->kitchen->{$k}
        }
    }
    return $obj;
}

I think passing a reference of the object's property to the recursive function might work - but I don't understand either enough to make an educated guess. Any help appreciated
Answer: You could do it like this:
function setObjectFromArray($obj, $arr) {
    foreach ($arr as $k => $v) {
        $obj->{$k} = is_array($v) ? setObjectFromArray($obj->{$k}, $v) : $v;
    }
    return $obj;
}

The major difference with your code is the assignment to $obj->{$k} instead of $obj: that way you rewrite (or create) the property at each level of the recursion tree.
Be aware that even if you call the function like this:
$result = setObjectFromArray($obj, $arr);

... $obj will still have been modified and be equal to $result.
Answer: This solution is not totally obvious and maybe can fail somewhere but still - it's pair of json functions:
$r = array(
    'rooms' => array(
        'kitchen' => array(
            'needsCleaning' => true
        )
    )
);

echo '
',print_r(json_decode(json_encode($r))), '
';

Explanation: you encode array to json-string and then decode this string to object.
Maybe you can expand this code further.