Automatic Item Number Creation (For article posting as a Reference for Quick Searching)

Question: I'm looking for a solution for automatic item number creation that will auto-create a reference number/code for any posted article, whatever the Node type. The purpose being that for any posted article (any Node type) that is created & posted by an author (with permission Roles authorised to post content) will have an item reference which can be traced throughout all aspects of workflow (including any Ticket Support document output - printer etc). This could quite simply be a standard item number as of that used on eBay (string of numbers) or similar used in organisational-wide portal. It might be for use in a local sales listing references (as in Gumtree), a vehicle listing platform (autotrader.co.uk) or simply to give a volumous document based content site a posting reference (internal intranet/external netsite), which for example, a 3rd party reader can jot down on paper, (email, cut and paste in Notes etc) and come back later and do a simple 'search' with the reference number, but not a 'purchase order' reference (as in Ubercart), purely for article reference purposes.
I'm not looking for anything tremendous (I'm not a PHPer (yet!) and I know this is more of a backend SQL DB but being more a Drupal 'plumber'/experimentalist I'm looking for simple solution for now that can be built upon later; something that Barcode module can also take advantage of and I can use in future projects of informational DataBases. Does anyone know of such a suitable solution/module for D7?
Any comments or How-tos welcome. Thanks.
Comment: Just a final note. I installed & used the UUID module and edited my Content Node (Panel template Variant) to include the UUID, and Voila! a system generated number, most suitable as an 'ultimate' system ID for the said content was included and shown in the content. This is EXCELLENT and provides just the short of thing I wanted, albeit a little long, it is most suitable. Now I just need to turn it into a QR using Barcode. Thanks again to everyone's comments and advice.
Answer: Option 1. You can use an existing node ID (NID).
Each node already has an ID and can be accessed via /node/[nid], [nid] being the ID of the node. Or you can generate a path alias by inserting <?php print l('link', 'node/' . $nid); ?>, $nid being the ID of the node. To retrieve NID of a current node, insert <?php print $node->nid; ?> into node.tpl.php.
Option 2. You can also use the combination of Automatic Nodetitles and Token module. This will allow you to automatically generate node title with the values from the Token.
Once the modules are installed, go to Structure -> Content Types, click on Edit, next to your content type. While on the Automatic title generation tab, select to Automatically generate the title and hide the title field, and in Pattern for the title, post a token from the options below; see the image below. There are many options with tokens, such as Unix timestamp (my favorite), random numbers and more.

Update:
For a truly random serial number, instead of using the Token module, I'd suggest using uniquid(); it generates a 13 character long random serial, no duplicates. This would be my choice. To do so, put this into "Pattern for the title" field, don't forget to check "Evaluate PHP in pattern":
<?php echo uniqid(); ?>

If you have spare time, there is also a Serial Field and Universally Unique IDentifier module, which also generate unique values.
Comment: That's very interesting and helpful, thank you Timofey for your response. I'll check it out and see what I can do with your helpful suggestions.
Comment: Further to timofey's suggestion, I'll use http://drupal.org/project/auto_entitylabel for my Drupal v7.15 and see if it helps generate ID references suitable for Article Content (node). I quite like the idea of the 'Random' option above.
Comment: Sorry, but just to clarify that this is the correct route, the created Pattern will be capable of being written to a field associated to the said Article Node so that in future any user can search for an article based on a ref (ie: pancake recipe titled "10 Ways To Make Quick Pancakes": Ref ID: 24356578 or PANC-QK-10-2012). I know libraries use a standard format but I'm not looking for any international standard, but something that works similar, or like an Amazon.com product/SKU.
Comment: Yes, if you add a field or use an existing field, with a generated number, it will be searchable within Drupal. Just don't forget to run Cron, to index search, before you try searching.
Comment: Also, I've added a bit more info on my post. You might be better off using uniqid() instead of tokens
Comment: You can also style your search result to include your SKU numbers on each result. To do so, copy /modules/search/search-result.tpl.php to your theme directory and edit the output to include your SKU field. search-result.tpl.php themes each item in search result.
Comment: Thanks again, timofey that is all very helpful. Good karma to you!
Answer: Checkout this module Universally Unique IDentifier . It may suit your needs.
Comment: Thank you that is very helpful, I will look to UUID module today.
Comment: It's already been mentioned in the previous answer.


Andengine: Connect two bodies

Question: I'm creating a simple game, I've tried to create a small piece that when it's collides
with another body it's sticks to this another body.
Here a snippet:
<code>ContactListner(){
    ...

    Body b1 = x1.getBody();
    Body b2 = x2.getBody();
    Player p = ((Player) x2.getBody().getUserData());
    DistanceJointDef d = new DistanceJointDef();
    d.initialize(b1, b2, b1.getWorldCenter(), b2.getWorldCenter());
    d.collideConnected=true;
    physicsWorld.createJoint(d);
</code>
My ContactListner is working, but this body isn't connecting both bodies.
Both of then are Dynamic Bodies.
Thx
Answer: You can not modify the world in Step()-Call of Box2D because the World is locked!. See Box2D AndEngine: app hangs out when creating Joints during ContactListener?

Andengine: Connect two bodies


Is font.loadAsync necessary for custom fronts in React Native 0.62.2?

Question: I built my project via
expo init App

and chose the default 'blank' option, so I do not have any iOS or Android directories.
After following this tutorial, Expo threw the following error when I initially tried to reload my app:
fontFamily "Aileron-Black" is not a system font and has not been loaded through Font.loadAsync.

I noticed that no other tutorials used loadAsync for custom fonts, so I was curious if this method is truly necessary? Moreover, after changing the text within my JavaScript file, I found it surprising that no errors arise and the custom font is displayed properly. Is this a bug or is this an installation issue? If the latter applies, what is the proper way?
Notes:

react-native-cli: 2.0.1
react-native: 0.62.2
expo: 3.23.1
OS:  Catalina 10.15.6
Answer: Cache your font before application startup using expo-font
Here the code

import React from "react";
import { Text } from "react-native";
import * as Font from "expo-font";

export default class App extends React.Component {
  state = {
    appIsReady: false,
  };

 componentDidMount() {
    this.prepareResources()
 }

  prepareResources = async () => {
    await cacheAssets();
    this.setState({ appIsReady: true });
  };

  render() {
    if (!this.state.appIsReady) {
      return <Text>loading...</Text>;
    }

    return <YourApp />;
  }
}

async function cacheAssets() {
  const fontAssets = cacheFonts([
    { "poppins-regular": require("./assets/fonts/regular.ttf") },
    { "poppins-bold": require("./assets/fonts/bold.ttf") },
  ]);

  await Promise.all([...fontAssets]);
}

function cacheFonts(fonts) {
  return fonts.map((font) => Font.loadAsync(font));
}

And now trying adding your custom font family to your Text component.


How does the new table tennis ranking system work? Any examples?

Question: I am new to table tennis and my objective is to be able to play in official competitions. I read the ITTF rules and the ranking system but it didn't make any sense to me, maybe because English is not my mother tongue.
I also read other posts but the explanation is done for the pre-2018 system. Could someone explain how the current ranking system works with examples?
Say I played with 4 different players who are ranked by ITTF and I won all the games. Is my ranking now going to be 4?
Answer: See the ITTF ranking document here.  The short answer is that you get a number of points for a win in an ITTF sanctioned event (an official tournament), and depending on the kind of event it awards more or less points. Page 8 shows the points; winning the Olympics gives you 2000 points, placing top 64 gives you 45 points.  Winning an International Event gives you 75 points.
You take your top 8 finishes by points, and then everyone does the same, and sort by points - whomever has the most points in their top 8 events is #1, whomever is second most is #2, etc.  These ranking points last for a year, so if you win an Olympic event in 2024, you will have 2000 points (plus your next 7 finishes!) for the next year, but in summer of 2025 it will expire and those points will go away (and be replaced by your next highest finish).
A player might have:

Olympic win 7/28/2024 = 2000
Continental Cup win 8/19/2024 = 500
WTT Contender finalist 9/15/2024 = 280
International Event win 8/12/2024 = 75
International Event win 9/24/2024 = 75
International Event finalist 7/15/2024 = 55
International Event finalist 9/8/2024 = 55
Continental Championship R16 11/4/2024 = 45
Continental Championship R16 2/4/2025 = 45
WTT Champions R32 5/16/2025 = 15

On 6/1/2025, their ranking score would be 2000+500+280+75+75+55+55+45 = 3085 points (leaving off the last two since they only keep the top 8 scores).  On 8/1/2025, two events would fall of - the Olympics and the International Event finalist from 7/15 - so they'd have 500+280+75+75+55+45+45+15, or 1090 points, if they didn't have any additional results that scored in that time period.


How to find 'alert-warning' in web page with Selenium (Python)

Question: I have this HTML code:
<button ng-show="vm.loading_update" class="alert alert-warning">
  Upgrading firmware... Please Wait...
</button>

This alert message is open when a previous button was clicked (this is ok).
So, I have this small code but doesn't work, the alert message isn't found.
self.elem = self.driver.find_element_by_xpath('//button[text()="Upgrade"]')
self.elem.click()
time.sleep(1)

WebDriverWait(self.driver, 2).until(EC.alert_is_present(),
                                     "Upgrading firmware... Please Wait...")
alert_test = self.driver.switch_to.alert()
alert_test.accept()

I need to know if this message is displayed to continue the test...
Thanks in advance.
Comment: Because this is not a standard alert.
Answer: Use the following code:
try:

    WebDriverWait(self.driver, 2).until(EC.visibility_of_element_located((By.CSS_SELECTOR, ".alert.alert-warning>strong")))

except:

    print("The alert is not displayed!")

Comment: Thank you, it's working. And I will remove the "button" type, because doesn't make sense in this situation, because this alert message isn't a clickable item, is only information to user.


How can I show that if $\gcd(a, 3) = 1$, then $a^{560} = 1 \pmod 3$?

Question: I need help getting started on a longer proof and this is the first part:
Show that if $\gcd(a, 3) = 1$, then $a^{560} = 1 \pmod 3$
Then we show the same thing with $11, 17, 561$. I have a feeling the same technique will be used to prove all of them, so if it can, all I really need to know is how to prove the first part.
The eventual goal is that we've shown $561$ is composite, but will pass the Fermat Primality Test.
Answer: Since $a$ and $3$ are coprime, Fermat's little theorem says $a^2\equiv 1\pmod{3}$. Can you use that to show what you want?
Comment: So, does this mean I can remove all the powers of 2 (since they are congruent to 1 (mod 3)) and be left with $a^{35} mod (3)$? Or is that the wrong direct to go?
Comment: @AgentKC, It means you can remove all even powers of $a$. But notice $a^{560}\equiv (a^2)^{280}\equiv 1^{280}\equiv 1\pmod{3}$.
Comment: Ohhh! That makes a lot more sense! And then we can do basically the same thing for the other numbers. Thank you!
Comment: @AgentKC Exactly, glad to help.


Sorting values with the same index in a data frame by column value

Question: I am trying to arrange rows in a data frame first by index in ascending order, yet I I have rows with duplicate indexes. For these, I want them to be arranged in ascending order by their value in a specific column. Below is what my data frame looks like:
           layer   row   col       stage  conductance   riverbott
row_Index
8            0.0   8.0  29.0  123.170732    1250000.0  122.170732
6            0.0   6.0  21.0  123.170732    1250000.0  122.170732
7            0.0   7.0  22.0  123.170732    1250000.0  122.170732
8            0.0   8.0  24.0  123.170732    1250000.0  122.170732
10            0.0   8.0  14.0  123.170732    1250000.0  122.170732
12            0.0   8.0  53.0  123.170732    1250000.0  122.170732
8            0.0   8.0  23.0  123.170732    1250000.0  122.170732
10            0.0   8.0  12.0  123.170732    1250000.0  122.170732

I have tried doing
df = df.sort_values(['col'])
df = df.sort_index()

In my data frame, my index value is equal to my value in 'row'. I have tried using df = df.sort_values(['row']) instead of df.sort_index(). However, I keeping running into issues where my data frame is  first sorted by index in ascending order (this is desired), yet rows with duplicate indexes are arranged sometimes with the lowest column value coming first, and others with the highest column value coming first. For example:
           layer   row   col       stage  conductance   riverbott
row_Index
6            0.0   6.0  21.0  123.170732    1250000.0  122.170732
7            0.0   7.0  22.0  123.170732    1250000.0  122.170732
8            0.0   8.0  23.0  123.170732    1250000.0  122.170732
8            0.0   8.0  24.0  123.170732    1250000.0  122.170732
8            0.0   8.0  29.0  123.170732    1250000.0  122.170732
10            0.0   8.0  14.0  123.170732    1250000.0  122.170732
10            0.0   8.0  12.0  123.170732    1250000.0  122.170732
12            0.0   8.0  53.0  123.170732    1250000.0  122.170732

I would like my data frame to be organized like so:
           layer   row   col       stage  conductance   riverbott
row_Index
6            0.0   6.0  21.0  123.170732    1250000.0  122.170732
7            0.0   7.0  22.0  123.170732    1250000.0  122.170732
8            0.0   8.0  23.0  123.170732    1250000.0  122.170732
8            0.0   8.0  24.0  123.170732    1250000.0  122.170732
8            0.0   8.0  29.0  123.170732    1250000.0  122.170732
10            0.0   8.0  12.0  123.170732    1250000.0  122.170732
10            0.0   8.0  14.0  123.170732    1250000.0  122.170732
12            0.0   8.0  53.0  123.170732    1250000.0  122.170732

The reason I am doing this is because I want to remove duplicate indexes, keeping the one with the lowest value in 'col'.
Thanks for the help.
Answer: To sort:
df = df.reset_index().sort_values(['row_Index', 'col']).set_index('row_Index')

Output:
           layer  row   col       stage  conductance   riverbott
row_Index
6            0.0  6.0  21.0  123.170732    1250000.0  122.170732
7            0.0  7.0  22.0  123.170732    1250000.0  122.170732
8            0.0  8.0  23.0  123.170732    1250000.0  122.170732
8            0.0  8.0  24.0  123.170732    1250000.0  122.170732
8            0.0  8.0  29.0  123.170732    1250000.0  122.170732
10           0.0  8.0  12.0  123.170732    1250000.0  122.170732
10           0.0  8.0  14.0  123.170732    1250000.0  122.170732
12           0.0  8.0  53.0  123.170732    1250000.0  122.170732

Then to remove duplicates:
df.loc[~df.index.duplicated(keep='first')]

Comment: `sort_values` accepts Index names as well as column names, so just `df = df.sort_values(['row_Index', 'col'])`


Music theory. Extended Chords and barre chords

Question: The Cadd9 chord is played on the 3rd,2nd and 3rd fret of the A D and B string respectively.
What would be the resulting chord if I were to barre the first fret with my index finger?
Or for that matter, what would happen to any open chords that operate from fret 'n' and I barre fret 'n-1' where n is not equal to 1.
Is there any way of finding what resulting chords I get when I barre open chords that operate from the second fret onwards(like Dsus4,C5, etc) ?
And by "way of finding" I mean, how we determine that a Gmaj chord is just moving the Fmaj chord by a wholestep because F and G are one tone apart.
Comment: It's actually played with the 3rd and top strings (open) as well. Giving C, E, G, D, E. And other options include bottom open or bottom 3rd fret, and top 3rd fret. Or possibly a combination!
Answer: Your starting chord...

X 3 2 0 3 0
X C E G D E

re-arrange the letters by thirds...
C E G (no B) D
That give us Cadd9, no minor seventh so it's just an add9.
That chord is open so we can sort of think of it as barred at fret zero.
Next, barre the first fret and you get...

X 3 2 1  3 1
X C E G# D F

re-arrange the letters in thirds...
C E G# (no B) D F
That gives us C#5add9add11 or maybe it should be C11#5add9. I would not spend time trying to give it a sensible label, because the barre was just arbitrarily added. That's not how functional chords are constructed. Is this really a 9th or 11th chord? Where is the dominant 7th then? Without the 7th we have to resort to using add labels. But do you really mean to construct a chord based on the ^1,^2,^3,^4 scale degrees then a #^5? This is more like non-tertial harmony or tone-clusters. You can do it if you want, but trying to figure out a label for the result doesn't make much sense. I don't mean to sound chiding, I just want to 'unpack' what's going on in the example.
Maybe if this chord was followed by sliding all the non-barre fingers up one fret the "chord" could be considered a type of suspension/retardation between a Cadd9 and a Dbadd9. If so, formally it should not be called a chord.
But I'm not sure I you meant to switch fingers 2,1,3 to 3,2,4 and move them up one fret to match the change of the barre from open (fret zero if you will) to fret 1. Personally, my hand can't make the stretch to do that, but it would  be...

X 4  3 1  4  1
X Db F Ab Eb F

Notice I made the enharmonic change of G# to Ab.
Re-arrange the letters in thirds...
Db F Ab (no C) Eb
That gives us Dbadd9
Notice that I came up with a Db root whereas @Tim came up with a C# root. Neither choice is right or wrong. Certainly guitar seems to "favor" keys with sharps so C# is a natural choice.
I chose Db because of the change of the E. If we sharp the C then we should sharp the E and get E#. Personally I think it's easier to read F natural. So I started by changing the pitch class - meaning the letters. So, E goes up to F and C goes up to a D that is a half step above which is Db. My root is Db.
Sorry if that's a bit long winded! But I thought it might be helpful to explain. When you get used to making enharmonic changes you kind of do all that stuff without much thinking.
But the important point is theoretically you could take any open chord shift the fingered tones up X frets and then barre at fret X to get a chord of the same quality but with the root shifted by X semi-tones. Some of the resulting chords may be impossible or difficult to play especially the ones based on open C, G, and D.
Comment: I think we're both on a hiding for nothing with this one!
Comment: I like your answer very much, but I would change your first example from 032030 to X32030 because the first string is not played. (Consequently the second example would be X32131)
Comment: @coconochao, good point. I missed the X in the chord diagram. I updated my answer.
Answer: You need to identify all the played notes, then try to form a major or minor triad from them, if you can, initially.
Your idea gives, bottom to top, F, C, E, G#/Ab, D and another F. Nothing there gives a triad as in 1 3 and 5. C&E is part of Cmaj., E&G# part of Emaj., D&F part of Dm., but nothing decisive. A name could be offered for it, but it's going to be contrived, and not a lot of use to many, if any, and I'd be hard pushed to find a useful place for it in a song.
Your last paragraph muddies things, as there, you mention wholesale moving of a complete shape, which is not what you describe earlier. If indeed that is what you meant, then moving Cadd9 up by a fret, and barre the 1st fret, then it's simply C#add9.
Enlightened by your comment, it's quite complicated, as with each shape, different strings will change notes when a barre is applied. Creating different notes in relation to the original chord/shape.
Comment: The last paragraph was an example to show how one determines chords when complete shapes move up and down the fretboard. I wanted to know if there was any hard and fast rule (like the example I mentioned) for determining chords that are obtained by barring the previous fret. Sorry if I caused any confusion :)
Comment: What happens to other chords like D5 when they are barred on the first fret?
Comment: It's going to depend on what notes get changed. I can think of a couple of 'D5' shapes, but the solution is simple. Write out the individual notes, and try to find a chord they constitute. There's no simple answer here, apart from that. As there are too many different shapes to consider.


Maximum and minimum value of $\frac{8x - 3y}{\sqrt{4x^2+y^2}}$?

Question: For real numbers $\,x, y\neq 0\,$ consider
$$\frac{8x - 3y}{\sqrt{4x^2+y^2}}\,.$$
How to find the maximum and minimum value?
I've already got the maximum by using the Cauchy–Schwarz inequality
$$\big[(2x)^2 + y^2\big]\big[4^2 + (-3)^2\big] \geq (8x - 3y)^2\\[3ex]
25 \geq \frac{(8x - 3y)^2}{(2x)^2 + y^2}\\[4ex]
5 \geq \frac{8x - 3y}{\sqrt{(2x)^2 + y^2}}$$
But I cannot get the minimum value.
Comment: If $(x,y)=(0,1)$, your expression evaluates to $-3$, which is less than $5$. So your minimum is wrong. (Also, [please use MathJax](https://math.meta.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference)!)
Comment: Sorry , I lost another constraint.
$x , y$ are non-zero real number
Comment: Isn't Cauchy Schwarz valid only for non-negative numbers?
Comment: You have Cauchy-Schwarz backwards! Your $\le$ should be $\ge$.
Comment: @TonyK thank you, I have corrected it.
Answer: You are almost there: Note that by Cauchy-Schwarz you  did
$$25 \geq \frac{(8x - 3y)^2}{(2x)^2 + y^2}\,.$$
Thus
$$\left|\frac{8x-3y}{\sqrt{4x^2+y^2}}\right|\le 5\tag {*}\\[5ex]
\implies -5\le \frac{8x-3y}{\sqrt{4x^2+y^2}}\le 5$$
The important part was in step (*). The modulus was crucial as $8x-3y$ could be negative too.
Comment: Sir Albus Percival Wulfric Brian Dumbledore, bear with me please for permitting myself to accomplish some obvious mod's.
Comment: @Hanno LOL ,didnt know the mathjax and BTW After reading  dwathly hallows for over 5 times still havent taken time to memeorise Dumbledores full name
Comment: Thanks for editing
Answer: Let $r > 0$ and $0 \le \theta < 2\pi$, and $x = r \cos \theta$, $y = 2r \sin \theta$, so that $$4x^2 + y^2 = 4r^2,$$ hence $$\begin{align}f(x,y) &= \frac{8x-3y}{\sqrt{4x^2 + y^2}} \\ &= \frac{8r \cos \theta - 6r \sin \theta}{2r} \\ &= 4 \cos \theta - 3 \sin \theta \\
&= 5 \left(\frac{4}{5} \cos \theta - \frac{3}{5} \sin \theta \right) \\
&= 5 \left( \sin \psi \cos \theta - \cos \psi \sin \theta \right) \quad \quad \psi = \arcsin \frac{4}{5} \\
&= 5 \sin(\theta - \psi).
\end{align}$$  Now we can see this function depends only on the choice of angle $\theta$.  This is obviously maximized when $\theta = \psi + \pi/2$ and the maximum attained is $5$.
This also happens to get us the minimum for free, which occurs when $\theta = \psi + \frac{3\pi}{2},$ and the minimum is $-5$.


Nice olympiad inequality :$\frac{xy^2}{4y^3+3}+\frac{yz^2}{4z^3+3}+\frac{zx^2}{4x^3+3}\leq \frac{3}{7}$

Question: I have this to solve :

Let $x,y,z>0$ such that $x+y+z=3$ then we have :
  $$\frac{xy^2}{4y^3+3}+\frac{yz^2}{4z^3+3}+\frac{zx^2}{4x^3+3}\leq \frac{3}{7}$$

I try to use Jensen's inequality but the function $f(x)=\frac{x^2}{4x^3+3}$ is neither concave or convex on the interval $[0,3]$
I can't use Karamata's inequality too .
Maybe brute force is the only way to solve it .
I try also to use the derivative but it becomes a little bit difficult .
In fact my idea was to use rearrangment inequality we have :
$$\frac{xy^2}{4y^3+3}+\frac{yz^2}{4z^3+3}+\frac{zx^2}{4x^3+3}\leq \frac{x^3}{4x^3+3}+\frac{y^3}{4y^3+3}+\frac{z^3}{4z^3+3}$$
An use the inequality of Jensen's on $[0.8,1.2]$ with $f(x)=\frac{x^3}{4x^3+3}$
So it's a partial answer .
My question is how to complete my answer or can you provide an other answer ?
Thanks a lot for sharing your knowledge and your time .
Comment: Sometimes I wonder how do they come up with questions like these te begin with, let alone finding an answer.
Comment: Maybe some of the answer to [this question](https://math.stackexchange.com/questions/1806414/prove-fracxy5y34-fracyz5z34-fraczx5x34-leqslant-frac13) could be useful.
Answer: Note that (tangent line trick)
$$\frac{5+2y}{49} - \frac{y^2}{4y^3+3}  = \frac{(8y^2+36y+15)(y-1)^2}{49(4y^3+3)}.$$
Thus, we have
$$\frac{y^2}{4y^3+3} \le \frac{5+2y}{49}, \quad \forall y \ge 0.$$
Thus, we have
$$\sum_{\mathrm{cyc}} \frac{xy^2}{4y^3+3} \le \sum_{\mathrm{cyc}} \frac{x(5+2y)}{49}
= \frac{5(x+y+z) + 2(xy+yz+zx)}{49} \le \frac{3}{7}$$
where we have used the fact that $xy+yz+zx \le \frac{(x+y+z)^2}{3}$. We are done.
Comment: @Michael Rozenberg  Nice. Thank you.
Comment: By AM-GM $(4y^3+3)(2y+5)\geq49\sqrt[7]{\left(y^3\right)^4y^2}=49y^2.$
Answer: Using AM-GM, we have
$$4y^3+3=y^3+y^3+y^3+y^3+1+1+1\geq 7\left((y^3)^41^3\right)^{1/7}=7y^{12/7}.$$
So
$$\frac{xy^2}{4y^3+3}\leq\frac{xy^2}{7y^{12/7}}=\frac{xy^{2/7}}{7}.$$
Now, note by Holder's inequality that
$$\sum_{cyc}xy^{2/7}\leq (x+y+z)^{5/7}(xy+yz+zx)^{2/7}.$$
By Cauchy, $xy+yz+zx\leq \frac{(x+y+z)^2}{3}$.  Thus,
$$\sum_{cyc}xy^{2/7}\leq \frac{(x+y+z)^{9/7}}{3^{2/7}}.$$  So
$$\sum_{cyc}\frac{xy^2}{4y^3+3}\leq \frac{\sum_{cyc}xy^{2/7}}{7}\leq \frac{(x+y+z)^{9/7}}{7\cdot 3^{2/7}}.$$
Thus, $\sum_{cyc}\frac{xy^2}{4y^3+3}\le\frac{(x+y+z)^{9/7}}{7\cdot 3^{2/7}}$ for all $x,y,z\ge 0$, where the equality case is $x=y=z=1$.  When $x+y+z=3$, we get
$$\sum_{cyc}\frac{xy^2}{4y^3+3}\leq \frac{3^{9/7}}{7\cdot 3^{2/7}}=\frac{3}{7}.$$
The equality holds iff $x=y=z=1$.
More generally, for non-negative real numbers $x,y,z$, for parameters $a,b>0$, and for real exponents $m,n$ such that $$(m-1)(a+b)\le an\le m(a+b),$$ we have $$\sum_{cyc}\frac{xy^m}{ay^n+b}\leq \frac{\sum_{cyc}xy^{\frac{m(a+b)-an}{a+b}}}{a+b}\le \frac{\left(\sum_{cyc}x\right)^{\frac{an-(m-1)(a+b)}{a+b}}\left(\sum_{cyc}xy\right)^{\frac{m(a+b)-an}{a+b}}}{a+b}\leq \frac{\left(\sum_{cyc}x\right)^{\frac{(m+1)(a+b)-an}{a+b}}}{3^{\frac{m(a+b)-an}{a+b}}(a+b)}.$$
The equality case is $x=y=z=1$.  In particular if, in addition, $x+y+z=3$, we get
$$\sum_{cyc}\frac{xy^m}{ay^n+b}\leq \frac{3}{a+b}.$$
The equality holds iff $x=y=z=1$.
Answer: Let $\{x,y,z\}=\{a^2,b^2,c^2\},$ where $a\geq b\geq c>0$.
Thus, $a^2+b^2+c^2=3$ and by AM-GM, C-S, Rearrangement and AM-GM again we obtain:
$$\sum_{cyc}\frac{xy^2}{4y^3+3}=\sum_{cyc}\frac{xy^2}{2y^3+1+2y^3+2}\leq\sum_{cyc}\frac{xy^2}{3y^2+4\sqrt{y^3}}\leq$$
$$\leq\frac{1}{(3+4)^2}\sum_{cyc}xy^2\left(\frac{3^2}{3y^2}+\frac{4^2}{4\sqrt{y^3}}\right)=\frac{9}{49}+\frac{4}{49}\sum_{cyc}x\sqrt{y}=$$
$$=\frac{9}{49}+\frac{4}{49}\left(\sqrt{x}\sqrt{xy}+\sqrt{y}\sqrt{yz}+\sqrt{z}\sqrt{zx}\right)\leq\frac{9}{49}+\frac{4}{49}\left(a\cdot ab+b\cdot ac+c\cdot bc\right)=$$
$$=\frac{9}{49}+\frac{4b}{49}\left(a^2+ac+c^2\right)=\frac{9}{49}+\frac{4abc}{49}+\frac{4b(3-b^2)}{49}\leq\frac{9}{49}+\frac{4\cdot1}{49}+\frac{4\cdot2}{49}=\frac{3}{7}$$
and we are done!


Custom www-data user in Ubuntu

Question: I use apache2-mpm-itk to run one of my web applications with a custom uid and gid, both for audit and security reasons. This works nicely, however I am not sure what kind of privileges this user would need. I am currently doing something like useradd mywebapp -U -d/tmp -c"Custom webapp User" but that creates pretty much a regular user.
So first a newbie question: how do I add a 'system' user that can that cannot be used for e.g. ssh'in or does not appear in the login screen on Ubuntu Desktop?
And what kind of privileges would I need to give this user? E.g. I assume that www-data can write to the Apache log files, so it needs something more than a regular user. But at the same time I don't want to give it more privileges than necessary to run my webapp, definitely not root.
Answer: sudo useradd username

will work just fine for your requirement. It creates the user with unset/random password. If you insist on disabling shell access to the user you could change the shell option for this user to /bin/false with commands like
sudo chsh username

As for not showing username in GDM login screen, you need to give the username UID below 1000. This makes Ubuntu treat the user as a system user, which then won't show up on the login screen.
Add the user in whatever way you prefer(maybe just like above), and then run:
sudo usermod -u 599 username

Where 599 is an unused UID below 1000, and username is your new user.
Comment: cat /etc/passwd | awk -F: '{print $3}' | sort -n
Comment: if you want to be able to make everybody able to view central access.log and error.log of apache, chmod o+r access.log and error.log
Comment: Is there a smart way I can detect if a UID has been taken? All of this has to end up in an Ubuntu package.
Comment: What would be a smart way to find an unused uid between say 500 and 1000?
Comment: there is no inbuilt commmand that i know of that will do the job. How about writing your own script for that !
Comment: Alright. But this does not address the permissions issue. The new user won't have permission to write to access.log / error.log , etc...

Custom www-data user in Ubuntu


Script encrypted mail

Question: Please help me with an PowerShell script to send an encrypted email on Outlook application.
I have a PowerShell script to send mail with attachments on Outlook application but want to encrypt that mail.
<code>$Outlook = New-Object -ComObject Outlook.Application
$Mail = $Outlook.CreateItem(0)
$Mail.To = "mail"
$Mail.Subject = "Action"
$Mail.Body = "Hi Aviral, Good to see you"
$file = "C:\Users\a.raghorte\Desktop\UNIX\Utilization.txt"
$Mail.Attachments.Add($file)
$Mail.Send()
</code>
Comment: Please add neccessary code to your question, not to comments
Comment: Maybe it's not a great idea to use your corporate email address as an example?
Comment: Do you want the client to server part encrypted (ie, using SSL/TLS and Submission) or do you want the server to server part encrypted (using ESMTP) or do you want the actual message encrypted (using PGP/GPG/etc) ?
Comment: You can say I want to digitally Sign that mail.
Comment: *I actually need the complete mail to be encrypted i.e. the subject body etc.* Mail encryption doesn't work that way. You can encrypt the body, but not the headers.
Comment: suggest me how to send an encrypted mail from outlook using PowerShell script.
Answer: <code>$Mail.PropertyAccessor.SetProperty("http://schemas.microsoft.com/mapi/proptag/0x6E010003", 0x03)
</code>
That should do the trick while Outlook is running. If outlook is not running, the Mail goes to "Outbox" without signature/encryption.
0 = none, 1 = sign, 2 = encrypt, 3 = both

Script encrypted mail


How to identify the root note of a chord

Question: I struggle with chords on the staff because I'm not sure which note is the root note. Is it the top note with the rest of the notes falling below it? E.g., if the top note is C, and bundled below it are an F and a G, is it a C Major triad? Also, what about the situation where the stem of the note, if it's a quarter note for instance, is facing downward?
I'm quite new to reading piano notation as I'm from a drumming background so I'm a little intimidated, because in drum notation you don't have to so quickly determine the fine placement of the note between the staff lines.
Comment: The point is that often you can't identify the root note of a chord if all you are looking at is the chord in isolation. You have to consider the chord in the context of the music you are reading, and identify the key center. Then you can figure out how the chord functions in that context.
Comment: Which note is root doesn't matter. The notation is what it is. You read the notes and play the notes. You do not have to understand the harmonic theory in detail in order to **read** the music, or even to emotionally connect with what you're playing.
Comment: Related: http://music.stackexchange.com/q/2265/1678
Comment: find the chord which the other chords all resolve to at the moments where the sound is the most conchordant, concordant, (french word).. normaly that's at the start and the end of bars. the concordant note is the most calm note of a song because all the other notes are much less related to each other than they are together related to the chord.
Answer: The root note is always the note that is the basis for the chord, regardless of its inversion.  In root position the lowest note is the root (hence the name), but other notes are the lowest in other inversions of the chord.
For example, take a C Major chord.  In every position, the root note is C.  Whether it is voiced as C-E-G (root position), E-G-C (first inversion), or G-C-E (second inversion) is irrelevant.  (The voicing is always given from the lowest note to the highest.)
There are multiple ways to interpret chords as well.  For example, C-E-A could be considered a C Major 6th in root position or an A minor chord in first inversion.  How you interpret it depends upon its function in the song as well as the song's key.  In the key of A minor you would definitely consider it to be an A minor chord.
C-E-A could also be considered a rootless F Major 7th chord (normally F-A-C-E) in second inversion.  You might interpret it this way in certain F Major pieces, for example.  In this case you might say it has no root, or that the root is an "implied" F.

As for reading the notation and playing it, a couple points:

The directions of the note beams (the "neck of the note") are irrelevant, they're mostly aesthetic.
In most cases, it doesn't matter which note is technically the root.  You'd be playing the same notes regardless.
Comment: @iamcreasy I'm not sure what that would even mean?  In any case, no -- lowest in terms of pitch.
Answer: It might also help if you figure out the FUNCTION of the chords.  I can't easily tell what chord is what without realizing its function.
For example, the most common cadence is V-I.  If you're in the key of F major, V is C and I is F.  If you have a chord that looks C-ish going to a chord that looks F-ish, that might be your answer!  Also, use your ear -- does it sound like a cadence?  Does it sound like the piece keeps moving?  Is there tension in the chord (aurally)?
Also, stack your chords in thirds.  That is what everyone above just did, and I don't think it was necessarily explained well.  A C triad is C E G (with whatever accidentals you want to change the quality of the chord, e.g., Eb for minor chord) -- it doesn't matter if you have the E in the bass or the G in the bass, it'll still be a C chord.  (There are reasons for why a composer might write one versus the other, but that's a different story.)
As a basic piano student, it will also be useful to know this: in a cadence (like V-I) there are often V7 chords.  This has a root, third, fifth and seventh.  In our C chord example, that'd be C E G Bb (because we're in F major).  In order to make this easily playable by a pianist, it is notated a specific way -- E Bb C.  This is missing the fifth, or G.  It is a) common to drop the fifth of seventh chords and b) recognizable by its shape to be a V7 chord.  Knowing that it's a V7 chord will tell you where the root is, because it will always be in the same place when notated like that.
Did that help or hinder?
Comment: Oh and the direction of the stem is easy!  It has nothing to do with harmony, and everything to do with the center line.  Is your note below the third line in your staff (any clef)?  Then the stem goes up!  Is your note above the third line in your staff?  Then the stem goes down!  The reason for this is to keep all of your notation IN the staff lines to make it easier to read.
Answer: One way to think of chords is you're playing a few selected notes from a chord that stretches from sub-bass to ultra-sonic. So the full C major chord contains all the Cs, all the Es and all the Gs. With enough pairs of hands, you could play 8 octaves' worth of this chord on a piano.
This is a C major chord, and C is the root note. All of the Cs are root notes -- there isn't one particular C that's "more root" than the others, although a particularly loud C in the bass register might help anchor it for the listener.
Now, no matter how many notes you take away from this "full" chord, it will remain consistent with being a C major chord.

If you take away all but three neighbouring notes, you'll have a triad. There are three inversions you can get this way. Regardless of which you get, C is still the root note.
If you take away all the Es, you've removed the note which distinguishes C major from C minor.
If you take away all the Cs, it's still consistent with being a C major, but the "C major-ness" is weakened (and the "E minor-ness" is strengthened)
The more note letters you remove, the more ambiguous the chord is.

In general a triad is the most unambiguous chord. The root is present. The fifth reinforces the root. The third tells you whether it's minor or major.
Adding notes makes things more ambiguous, taking away notes makes things more ambiguous, and this is where context helps.
Comment: Sub-bass = "deeper than a human can hear"; ultra-sonic = "higher than a human can hear". To play a chord containing all the Cs, just hold down every C on the keyboard (you may need help, as two hands is not enough).
Answer: A note about stems and beams: pianists often work with both hands in one register or area of the keyboard, and music notation tells the pianist which hand to use when, such as when hands are crossed over one another in playing a riff or string of notes.  When that is the case, stems up tell the pianist to use the right hand, and stems down, the left hand.
Answer: One handwaving characteristic of the "root note" is that its frequency is the greatest common divisor of the chord notes.  It takes a lot of handwaving since for one thing, with an equal-tempered tuning there is at best an approximate gcd (you have to use some scale with just intontation, and of course the choice of scale influences the result), for another, many jazz chords are ambiguous and consist of at least two partly overlapping triads with different root note/function.
All being said and done, a pretty god bet is the presence of a perfect fifth of some kind: that points to the lower note of the fifth (or equivalently the upper note of a fourth) to point to the root note.
Except, of course, when it doesn't like in suspended chords.  Suspended chords, however, are usually readily recognized by their following resolution.
Answer: As indicated above, function is important, but then again so is spelling. For example, take the notes A, C, E, and G. First blush would be an Amin7, but they could also spell a Cmaj6 equally well. Context matters.
Answer: Here's an idea.  A scale is every possible note for the melody.  So for C major it's:

C D E F G A B

A chord on the other hand is every other note. So a C chord is:

C E G

A D minor chord is:

D F A

And all those fancy jazz chords are every other note as well. A C11 is:

C E G B D E F

only we throw out most of the notes that aren't C E or F.
So all you have to do is play anagrams with the notes.
EGC? Hmm, CEG. C major.  It could also functionally be a Em add(#5) but I've seen this notated as C/E (C chord with an E in the bass).
AF with a C way up in the upper octaves? FAC. F major.
Don't worry about the exact names of chords. Thelonious Monk, the harmonic inventor of traditional jazz, couldn't tell you the music school versions of the chords he was playing either. (Source: "To Be or Not to Bop" by Dizzy Gillespie) It's all about what sounds good.  I couldn't tell you how many amazing musicians I've heard who couldn't identify the chord they were playing if you held a gun to their heads.  But they sure sounded good.
Comment: C major: C E G.  Em(add#5): E G C.
Comment: Could you please explain how Cmajor and Eminor(add#5) are equivalent?
Answer: This is actually an answer to a question that this question is marked as an exact duplicate of (putting it here to contribute a few more nuances to the body of answers):

I've been working on a piece in GarageBand on my iPad that ends with a B7 chord; the little knowledge I have of music theory is only what I have gleaned from practical experience as a three-year member of my high school's choir, so I would like some clarification on the terms used to define the notes in a chord because I am not very sure that my understanding is correct.
I know the notes in the B7 chord are B, E flat, G flat, and A; I've mainly seen the chord as the notes ascending in that order. If I have the notes ascending in the order of Eb, Gb, A, and B, is Eb now the root of the chord, or is the root of the chord always the note that the chord is named after, and therefore the root of the chord is still B?

The usual "spelling" of B7 is B, D#, F#, A. Note that this spelling omits every second letter, so that the chord is a series of stacked thirds; this is typical in Western harmony.  A dominant seventh, then consists of the root, a major third above the root, a perfect fifth above the root, and a minor seventh above the root.  This chord can of course be inverted; in any case, the root of a chord with those notes is always B, no matter what order they're in.
In this particular case, there is nothing else those notes are likely to be. However, if you examine a Bdim7, on the other hand, you will see that it is spelled B, D, F, Ab. The interval between each of those is a minor third (three half-steps). That means it would consist of the same pitch classes as a Ddim7, a E#dim7, or a G#dim7. (Why didn't I call the last two an Fdim7 and an Abdim7? Hold on!) So how can you distinguish between a Bdim7 and a Ddim7, for instance?
There are two basic contexts in which the difference becomes apparent. The first is notational: Ddim7 is spelled D, F, Ab, Cb. Note that this, like any other seventh chord, preserves the "every other letter" pattern (assuming the musical alphabet to wrap around after G). Thus, for a diminished seventh, as for any seventh, the root is the only note for which every other note class is a third, a fifth, or a seventh above it (possibly moved up or down an octave or two, depending on the voicing).  An E#dim7 would be E#, G#, B, D, and a G#dim7 would be G#, B, D, F.
The second is functional. The diminished seventh has a dominant function in a minor key. In C minor, for instance, you will typically see the Bdim7 (the leading tone diminished seventh) resolve to C- (the tonic minor). That role could also be played by G7 (the dominant seventh); this isn't surprising, given that both chords share B, D, and F in common, with the only difference being the G in G7 versus the Ab in Bdim7. This is why we have a Bdim7, a Ddim7, an Fdim7, but a G#dim7 rather than an Abdim7: A Bdim7 resolves to C- and a Ddim7 resolves to Eb-.
But Abdim7 would resolve to...what? One would like to say A-, but Ab isn't the leading tone of A-; G# is, so that's what the root of that diminished seventh "should" be. One might venture that Abdim7 could resolve to Bbb-, but Bbb isn't a tonic minor key in conventional music—at least not in anything that isn't trying explicitly to be at least a little weird.  Likewise, an E#dim7 would resolve to F#-, so that's what we call it, an Fdim7 would resolve to Gb-, which, again, doesn't exist much.  (As a tonic minor.  It could be a secondary key.)
None of this has any impact on the sound of the chord, and so it may seem a little academic.  But these regularities in the way that chords are notated makes it easier to make sense of them, and to remember how they form progressions.


Are there any best open source BI and i wanna host that BI on any server?

Question: I am looking for a BI Tool for basically good vicualization and report generation.
I need below features to be basic needs of my requirement.

Open Source
Need to access any database using their credentials and host.
Able to host in any server
I can APIs to get data

Please suggest me which one will be the good one to go with
Answer: I think  Pentaho is the best bi  tool that you can find free of charge. Check their site Web for more details.
Hope that helps!


Techniques for incremental online learning of classifier on stream data

Question: Which may be good techniques to face this abstract problem?
You have a data stream of a continuous signal, as one from a physical sensor. That signal has real (discretized) values, no attribute; addictional features (e.g., power, auto-correlation, entropy) might be extracted. You can assign one label from a finite set to a window of the signal. Let this label be a training label. You have to choise start and end points of the window as well as the window label.
The task is to classify next windows online, as just as the signal is received.
I am asking for an incremental algorithm, in the sense that it should increase its detection performance given more training labels. But it must be able to classify even after only one training label.
If the problem turns out to be too hard because of windows-boundaries detection, let's say you can fix their size at a small constant. Thus the algorithm classifies little slices of the signal and then it merges adjacent ones with same labels. If you use that simplified approach, please justify why it is reasonable.
Answer: If this is a binary classification problem then it should be possible to apply an online SVM such as Bordes, A. and Bottou, L., "The Huller: a simple and efficient online SVM", ECML 2005.
If this is a non-binary classification (i.e. more than 2 possible labels) you could look into kernel recursive least-squares techniques. They are made for online regression, but they perform pretty well for online classification too. Here's one basic KRLS algorithm: Y. Engel, S. Mannor and R. Meir, "The Kernel Recusrive Least Squares Algorithm", IEEE Trans. Signal Processing, 2004.
Both of these approaches will require fixed window-sizes in order to compare input vectors of the same size.


How to compare two negative exponential growth models?

Question: I have two negative exponential growth models which I want to compare in respect of the overall slope of the fitted regression lines (are the two lines significant different?). Below an image of the two models and the underlying data (model m1[black], model m2[red]):

Below is the reproducible code in R.
(a) Example data:
time <- rep(c(rep(0,7),7.1,rep(9.4,2),rep(25.6,3),rep(46,4),rep(106,5),rep(160,6)),2)
group <- rep(c("A","B"), each=28)
intensity <- c(0.026, 0.043, 0.035, 0.027, 0.031, 0.041, 0.053, 0.088, 0.120, 0.152, 0.229,
    0.215, 0.243, 0.346, 0.327, 0.303, 0.311, 0.367, 0.373, 0.368, 0.367, 0.428, 0.434,
    0.434, 0.408, 0.409, 0.390, 0.438, 0.035, 0.036, 0.036, 0.039, 0.033, 0.030, 0.047,
    0.227, 0.251, 0.282, 0.324, 0.301, 0.317, 0.417, 0.432, 0.399, 0.408, 0.508, 0.517,
    0.502, 0.497, 0.529, 0.536, 0.528, 0.543, 0.541, 0.570, 0.546)
data <- data.frame(time=time, intensity=intensity, group=group)

(b) Negative exponential growth model:
getModel <- function(df){

    nl_model <- function(a, b, c, x){

        y = a * exp(c * x) + b * (1 - exp(c * x))
        return(y)
    }

    x_grid <- seq(0, 160, length = 200)  ## prediction grid

    mcoeff <- nls(intensity ~ a * exp(time * c) + b * (1-(exp(time * c))),
        start = list(a = 0.01, b = 0.5, c = -0.01), data = df,
        control = list(maxiter = 500))

    coeff <- as.data.frame(summary(mcoeff)["coefficients"])

    y_pred <- data.frame(intensity = do.call(rbind, lapply(x_grid, nl_model,
        a = coeff["a",1], b = coeff["b",1], c = coeff["c",1])))

    model_coord <- data.frame(time = x_grid, y_pred)
}

m1 <- getModel(subset(data, group=="A"))
m2 <- getModel(subset(data, group=="B"))

(c) Visualisation:
plot(subset(data, group=="A")$time, subset(data, group=="A")$intensity, col="black",
    ylim=c(0,0.575), xlab="time", ylab="intensity")
points(subset(data, group=="B")$time, subset(data, group=="B")$intensity, col="red")
lines(m1$time, m1$intensity, type = "l", col = "black", lwd=1.5)
lines(m2$time, m2$intensity, type = "l", col = "red", lwd=1.5)

I read the following posts What test can I use to compare slopes from two or more regression models? + How to calculate the difference of two slopes? and understand how to compare the slopes of two linear models. I wonder if something similar could be done with the negative exponential growth model? I also know that I can compute the overall slope value of a regression line by predicting y values using the model and a reference grid. But this would just give me a single mean slope value for each model, not sufficient for any statistical test. I would also be happy to directly use the input values for test statistics, any suggestions which test could be applied in this context would be very helpful, too.
Answer: The way I'd approach this problem is similar to the answers you've already linked.
First, I'd fit a model that constrains the $a$, $b$, and $c$ parameters to be the same regardless of the group, along with another model that estimates separate parameters by group, and then run an F test to compare them.
The nls formula allows you to define some parameters to vary by groups using the parameter[group] syntax. For example:
# Convert group to factor
df <- data.frame(time = time,
                 intensity = intensity,
                 group = as.factor(group))

# Denote start values
start_vals <- list(a = 0.01, b = 0.5, c = -0.01)

# Fit null model - equal a, b, and c parameters for each group
m0 <- nls(intensity ~ a * exp(time * c) + b * (1-(exp(time * c))),
          start = start_vals,
          data = df)

# Fit model with differing a, b, and c parameters by group
m1 <- nls(intensity ~ a[group] * exp(time * c[group]) + b[group] * (1-(exp(time * c[group]))),
          start = lapply(start_vals, rep, 2),
          data = df)

# Compare with F-test
anova(m0, m1)

For the data you provided we find:
Analysis of Variance Table

Model 1: intensity ~ a * exp(time * c) + b * (1 - (exp(time * c)))
Model 2: intensity ~ a[group] * exp(time * c[group]) + b[group] * (1 - (exp(time * c[group])))
  Res.Df Res.Sum Sq Df  Sum Sq F value    Pr(>F)
1     53   0.169120
2     50   0.037145  3 0.13198  59.217 < 2.2e-16 ***
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Note that this is a joint test for equality of all the parameters defining the slopes - it is possible that you may have reason to constrain one or more parameters to be the same across groups (e.g., fixing $a$, which corresponds to the starting value, across groups), or isolate parameters (e.g., determine whether $b$ alone differs by group). You'd just need to adjust the code above accordingly.
Comment: Certainly! Have a look at Chapter 8 of "Nonlinear Regression with R" by Ritz & Streibig (2008). The differing parameters by group syntax is introduced on pg. 111, and the F-test approach described here on pg. 115. They also discuss the use of the `nlme` package, which has some really nice functions for non-linear models with grouping variables.
Comment: Dear awhug, great idea! Could you recommend any reference for the parameter[group] syntax for further reading?


Should I always close BufferedReader?

Question: Here is a line reading a file into a List:
List<String> lines =
    new BufferedReader(
        new InputStreamReader(classLoader.getResourceAsStream(fileName)))
            .lines()
            .collect(Collectors.toList());

Is this correct or should I assign the BufferedReader to a variable to be able to close it later?
Comment: [This](https://stackoverflow.com/questions/31171489/does-collect-operation-on-stream-close-the-stream-and-underlying-resources) seems to imply close is *not* called by collect.
Comment: @MS90, could you provide a link which you mean?
Comment: Sorry, take a look down below from official documentation in my reply. @Ekaterina
Answer: You should always close your resources. Closing may not be a big problem for small programs which only use a couple of files quickly, since most mature OSes will close the files for you when the process completes. However, there are usually limits on how many files you can have open at one time. It is good to be tidy, so that you don't hit those limits when you start writing bigger programs. There are also other types of resources, like network and serial ports, which you may want to let others use once your program is done with them, even if it is still running.
An alternative to closing the file manually is using try-with-resources syntax, which ensures that the file will be closed properly even in case of an error:
List<String> lines;
try(BufferedReader reader = new BufferedReader(
        new InputStreamReader(classLoader.getResourceAsStream(fileName)))) {
    lines = reader.lines().collect(Collectors.toList());
}

Answer: Well, in your concrete example, the stream opened by
classLoader.getResourceAsStream(fileName)

is never closed. This stream must be closed - it is most likely a file handle in the local system. You can close it by closing the BufferedReader, which closes the wrapped InputStreamReader, which closes the underlying InputStream. You could instead also store a reference to the original InputStream and only close this.
Please also have a look into try-with-resources, this could potentially make things easier for you here.
Answer: I stand corrected

From documentation:
Streams have a close() method and implement AutoCloseable interface, but nearly all stream instances do not actually need to be closed after use.
Generally, only streams whose source is an IO channel, for example a BufferedReader.lines will require closing.
Most streams are backed by collections, arrays, or generating functions, which require no special resource management. If a stream does require closing, it can be declared as a resource in a try-with-resources statement.

Should I always close BufferedReader?


tightness and convergence for Hilbert spaces

Question: Let $(X_n,n\geqslant 1)$ and $(Y_n,n\geqslant 1)$ be sequences of  stochastic processes taking values in some Hilbert space $H$ and defined on the same probability space. Assume that $(X_n,n\geqslant 1)$ converges weakly to some limit process.
Next, suppose that $\lVert Y_n\rVert_{H} \leq \lVert X_n\rVert_{H}$ for all $n$.
Is $(Y_n,n\geqslant 1)$ tight?
In general, I am confused with the following: Assume me have a majorating  weakly convergent process. Then, another process, majorated by convergent one, is not necessarily convergent, but it it not (is it?) tight either.
Answer: Answer
In general, your conjecture is not true. You can see it by the obversation that:  One direct implication from your conjecture is that
"Every sequence of random variables bounded in $H$  is tight"
Which is clearly wrong for any infinite-dimensional normed vector space (not hibert space alone).
For example,taking $H= l_2$ ; $Y_n= e_n$ . The sequence $(e_n)$ is bounded, while it is clearly not a relatively compact subset of $H$.
(Though it converges in weak topology, but this topology is not the canonical topology when we regard $H$ as a normed vector space)
Comments
My two-cent comment: If I'm not wrong, what you want to search is essentially the relation between the tightness and the norm of value space (the codomain). As I showed in the previous example, the first step you need to overcome is to form the bridge between the compacity and norm. However, while that relationship is clear in finite dimension, it is extremely weak when you deal with infinite-dimensional space. Much work needs to be done, some change in approach might be nessessary.
Comment: Dear @Paresseux Nguyen , I am confused about the following: "norm reduction does not guarantee tightness"...
Comment: I don't know if I ever gave that line. Perhaps my explanation is not clear. Would you mind elaborating more on the part that you are confused about in my comment?
Comment: no... this is my question, it is not about you comment
Comment: Hm, so let's put it this way. If every random variable you have is deterministic ( no randomness in it) , what will your statement be? So, it will be a statement telling a relation between the compacity and norm.
Comment: More precisely, it is :" If  $x_n$ converges to something in H and $y_n$ satisfies that $|x_n| \ge |y_n|$ , then $\{y_n\}$ is a relative compact subset of $H$"


Rendering Taxonomy Custom Fields in page.tpl.php

Question: Ahoy all, so, having some issues with displaying specific fields related to taxonomy terms in a page I created (page--taxonomy.tpl.php)
Essentially, I am trying to set a background image to a div, to pull from an image field (field_hero_image)on the taxonomy term. I have this working for normal nodes just fine with the following code:
<div id="herowrap" style="background:url(<?php echo file_create_url($node->field_hero_image[$node->language][0]['uri']); ?>) no-repeat center center;background-size: cover;">

However, been having difficulty understanding how to modify this to pull this same image field from taxonomy terms.
It needs to be in page--taxonomy.tpl.php as it is being pulled before the node.tpl.php is being called (if i understand correctly?)
Any reason I can pull this easily from nodes, and not for taxonomy terms?
Thanks for any help!
Dan
Answer: I suggest taking a look at the 2 answers to this question. I think it's a similar case.
Answer: I have actually been developing a site and I have learned an interesting method to do what you want and I think this method would help you here.
I would bypass taxonomy all together and use Content Types, Entity Reference and Views instead.
What you do is create a content type with only two fields:
1)  The title field.  Rename it to "category" or "taxonomy" or whatever makes sense.
2)  An image field.
Then in your article or whatever you use for content, you add an entity reference field to that new content type you just created.    The beauty here is that you can be consistent with your terms and you can bring over the image anytime you want because it is part of the referenced content type.
In the views module, you create a block and then make a relationship to the referenced content and a contextual filter based on ID in the URL.  Your fields for the view will be the title, content, the "term" and the image (because of the relationship).
You can use re-write rules to style how you like.
So, instead of having a url that looks like www.example.com/term/foo-bar   Your URL will be www.example.com/foo-bar and the image will simply follow because of the entity reference.
The biggest benefit to doing this?  No coding other than CSS.


Inference on a probabilistic graphical model with observed continuous variable

Question: Suppose we have the following probabilistic graphical model:
$L \rightarrow X, L \rightarrow Y, F \rightarrow Y, X \rightarrow D, Y \rightarrow D$.
That is, the joint is: $P(D,X,Y,L,F) = P(D|X,Y)P(X|L)P(Y|L,F)P(L)P(F)$.
Here $L,F,D$ are discrete, $X,Y$ are continuous random variables (having proper pdf's).
I want to compute $P(D=d,L=l | X=x, F=f)$. Note that we have already observed ($x$) for one of the continuous variables.
Here is my solution attempt so far:
$P(d,l | x, f) = \frac{P(d,l,x, f)}{P(x,f)}$  Let's ignore the denominator for now. The numerator:
$P(d,l,x,f) = \int_y P(d|x,y) P(x|l) P(y|l,f)P(l)P(f)$
Now, $P(x|l)$ and $P(y|l,f)$ should be zero because they are continuous variables. But we have already observed the value of X. So, I am not sure how to proceed from now on. My guess is that we should use the pdf's instead of probabilities:
$P(d,l,x,f) = \int_y P(d|x,y)\;f_{X|L}(x|l)\;f_{Y|L,F}(y|l,f)\;P(l)\;P(f)dy$
Is this correct?
If this is correct, then another question is how to compute this integral. Would the
following work?
Sample a $y$  from $f_{Y|L,F}(Y|l,f)$, compute $P(d|x,y)$ and then compute $g(y) = P(d|x,y)\;f_{X|L}(x|l)\;P(l)\;P(f)$. Do this a large number of times and take the average of $g(y)$'s.  ???
Any ideas, hints, directions would be highly appreciated.
Answer: Your derivation looks correct and is consistent with how joint distributions that are a mix of discrete and continuous are normally handled.
Note that some of the things inside your integral do not depend on $y$. You can re-write it as
$$ P(d,l,x,f) = P(l) P(f) f_{X|L}(x|l) \int_y P(d|x,y)  f_{Y|L,F}(y|l,f) dy $$
This is an integral against the conditional density of $Y|L,F$, which you can estimate using the procedure you described, which is known as Monte Carlo Integration. The basic idea is that if you want to estimate an integral against a density, $p(x)$:
$$ I = \int g(x) p(x) dx $$
then this can be written as the expected value of the random variable $g(X)$, where $X$ has distribution $p$. Therefore, if you
(1) Simulate values of $X \sim p$ and
(2) Calculate $\hat{I}$, the sample mean of $g(X)$
then $\hat{I}$ is a consistent estimator of $I$, by the Law of Large Numbers. In finite samples, the standard deviation of this approximation will be $\sqrt{{\rm var}( g(X) )/n}$, so you can see the larger the sample size you use, the more accurate your estimates will be, both in terms of the potential bias (i.e. the consistency of the estimator) and the precision (the reduction in variance).
In your case, note that the integral in your problem can be written as an expectation against the joint density of $Y|L,F$:
$$ P(d,l,x,f) = P(l) P(f) f_{X|L}(x|l) \cdot E_{Y|L,F} \left( P(d|x,Y) \right) $$
Therefore, if you can generate from the conditional distribution of $Y|L,F$, then the method you described is feasible for estimating $E_{Y|L,F} \left( P(d,x,Y) \right)$; all other terms are constants in $y$, and so they can be pulled out the integral. Above I've described the simplest possible form of monte carlo integration and if simulating from this distribution has high computational cost, you may consider a more sophisticated method (like importance sampling) that will require less simulation for a fixed level of monte carlo error you're willing to accept in your estimate.
Edit: Another method for calculating the integral is numerical integration, which only requires you to be able to calculate the integrand. Numerical integration is typically difficult itself when the objective function is complicated and is not as intuitive as monte carlo integration, so you probably don't need to consider it unless the distribution of $Y|L,F$ is impossible to sample from or is computationally expensive to the point that you couldn't take enough samples to get a precise estimate of the integral.
Comment: this question also has an open bounty ending in 3 days at [mathoverflow](http://mathoverflow.net/questions/97999/inference-on-a-probabilistic-graphical-model-with-observed-continuous-variable)
Comment: What about $f(x|l)$? This is actually the likelihood of $x$ as a function of $l$, and its absolute value is immaterial. How to deal with this? I'm thinking of using likelihood ratios where the likelihood function in the denominator is kept the same for all values of $l$. Does it make sense?
Comment: I accidentally left that term out of the final equation - thanks for catching that (fixed). In terms of the integral, $f_{X|L}(x|l)$ is a constant, so you can just factor it out and multiply at the end.
Comment: I will compute this probability for different values of $L$ so the value of $f(x|l)$ matters.
Comment: Once you have the value of $E_{Y|L,F} \left( P(d|x,Y) \right)$, which you can calculate by monte carlo integration, calculating the joint probability is no more difficult than evaluating the constant terms out in front
Comment: I flagged that bounty to be removed but it's been ignored so far.


WPF - add scrollviewer to panel with codebehind

Question: For certain reasons I need to add elements to my form with codebehind.
There is a main panel. By clicking a button - I am adding some content to it as below:
    private void AddCodeKlantFieldButtonOnClick(object sender, RoutedEventArgs routedEventArgs)
    {
        var button = sender as Button;
        if (button != null)
        {
            var panel = (StackPanel)button.Tag;
            var stackPanel = new StackPanel { Orientation = Orientation.Horizontal };
            AddLabel(stackPanel, "Klant van:", 135);
            opzoekenLandVan = new OpzoekenCode(OpzoekenCodeTable.Klant, "");
            opzoekenLandTot = new OpzoekenCode(OpzoekenCodeTable.Klant, "");
            stackPanel.Children.Add(opzoekenLandVan);
            AddLabel(stackPanel, "tot en met:", 100);
            stackPanel.Children.Add(opzoekenLandTot);
            var count = panel.Children.Count;
            panel.Children.Insert(8, stackPanel);
        }
    }

That works fine! But if I add too much items, there is not enough space on the form - so a scrollviewer would be needed. I am quite new and can not figure out how to handle it. I tried this:
        var scrollViewer = new ScrollViewer();
        scrollViewer.Content = panel;
        scrollViewer.Visibility = Visibility.Visible;
        scrollViewer.VerticalScrollBarVisibility = ScrollBarVisibility.Visible;
        scrollViewer.CanContentScroll = true;

But the scrollbar does not appear. If I try to add it to the form
panel.Children.Add(scrollViewer);
I am getting an error:
An exception of type 'System.InvalidOperationException' occurred in PresentationFramework.dll but was not handled in user code
Additional information: Logical tree depth exceeded while traversing the tree. This could indicate a cycle in the tree.
Comment: Hehe :) Believe me, I tried it!
Comment: Well there's your problem right there... www.tinyurl.com/jmdw9lf
Answer: In the code below, you did not add the scrollViewer to the visual tree so it's not displaying
    var scrollViewer = new ScrollViewer();
    scrollViewer.Content = panel;  //this does not add to visualtree
    scrollViewer.Visibility = Visibility.Visible;
    scrollViewer.VerticalScrollBarVisibility = ScrollBarVisibility.Visible;
    scrollViewer.CanContentScroll = true;

one of the lines above is
scrollViewer.Content = panel;

so you will get an error on trying to add it to panel's children.
panel.Children.Add(scrollViewer);

You see the circular issue?  First line, you put panel inside scrollViewer, next line you put the same scrollViewer in the panel.
Try commenting out scrollViewer.Content = panel but leave panel.Children.Add(scrollViwer) in, this should add the scrollViewer to the visualtree.  But it'll probably be invisible due to 0 width or height since it has no content and is in a stackpanel.
Comment: The only problem with infinite recursion is infinite recursion.
Comment: Thank you so much! I understand the issue now. I followed your advice and it worked! I created another panel, which contains the actual content(which is dynamically added/removed) and set that new panel as a content of scrollviewer, which is added to the main panel. So it does what I want now! Thanks again!


Robocopy in powershell

Question: I want to copy the csv files from two different servers and then paste those files at some location on 3rd server.
CSV File location on 1st server is - E:\HC_Disk\Sample\"+"DiskSpace-"+(Get-Date -format yyyyMMdd)+".csv
CSV file location on 2nd server - E:\HC_Disk\Sample\"+"DiskSpace-"+(Get-Date -format yyyyMMdd)+".csv
I have the script which generates the files everyday. My main concern is to club the two files together in the powershell.
Can you please help me with that. Thanks
Comment: Is this a request to create a code for you or there is your code which is not working properly? If the latter, please share it
Comment: I have not written any code for it so far. If you have any, please share it with me. Thanks!
Comment: When I use the Robocopy command : robocopy \\ServerA\E:\HC_Disk\Sample\"+"DiskSpace-"+(Get-Date-format yyyyMMdd)+".csv\ \\ServerB\E:\Test\   I'll get the error as invalid parameter "-format". Could you please suggest on this?
Answer: If you're referring to merging two CSVs, assuming the same headers, try below (modify for your filenames/paths):
Get-Content file1.csv, file2.csv | Select-Object -Unique | Set-Content mergedfile.csv

Comment: @HaninderCheema Have you made any effort at all to solve this yourself?
Comment: Thanks for the answer. My headers are same in both the files. Also if I have to copy the above two files from two different servers to the 3rd server, how can we use ROBOCOPY for that?
Comment: Copying files from one system to another system is a basic and thoroughly documented process that can be achieved using a plethora of methods, all of which can be found via Google.  Combining the files after copying can be achieved using the code I posted above via PowerShell, or another method if you prefer.

Robocopy in powershell


Add days to an Oracle Date in SSRS

Question: I'm connecting to ORACLE data for SSRS purposes, using Microsoft Business Intelligence Development Studio.
I need to return data where a date is less than 15 days from today. I've tried the sql that works in ORACLE:
<= to_char(sysdate, 'yyyymmdd')-15

but it doesn't work in BIDS - when I move away from the filter field quotes are applied to turn the whole function into a string.
If someone can let me know the correct syntax it would be a real help.
Thanks
Neil
Answer: Try this:
to_char(trunc(sysdate)-15, 'yyyymmdd')

Trunc will remove the time part from your system timestamp.
Comment: Hi Mucio, I tried, but ssrs converted it into the following: = TO_CHAR(TRUNC(TO_CHAR(SYSDATE, 'J')) - 15, 'yyyymmdd'), and then returned an ORA-01481 invalid number format model error when run
Comment: Thank you - this did work when I entered it directly into the code view of BIDS, rather than the design view, which does not parse oracle SQL correctly.

Add days to an Oracle Date in SSRS


How can I count the result of SQLite Query Xamarin Forms?

Question: I want to get how many rows does my SQLite Query. The problem is my code cannot be Deserialize in order to get the total row count. I am using this as a login method in my application. There is an error in "var result = JsonConvert.DeserializeObject>(userData);". The error is

Newtonsoft.Json.JsonSerializationException: Cannot deserialize the current JSON object

var db = DependencyService.Get<ISQLiteDB>();
var conn = db.GetConnection();

var getCaf = conn.QueryAsync<CAFTable>("SELECT * FROM tblUser WHERE UserID=? AND UserPassword=?",Username,Password);
string userData = JsonConvert.SerializeObject(getCaf);

var result = JsonConvert.DeserializeObject<List<UserData>>(userData);

if (result.Count < 1)
{
   MessagingCenter.Send(this, "Http", Username);
}
else
{
   Application.Current.MainPage.Navigation.PushModalAsync(new NavigationPage(new MainMenu()), true);
}

Answer: I'm not sure why you are using json here at all?  It is not needed.
QueryAsync should return a List<T>
var getCaf = await conn.QueryAsync<List<CAFTable>>("SELECT * FROM tblUser WHERE UserID=? AND UserPassword=?",Username,Password);

then just count the results
var count = getCaf.Count;

Comment: I just followed a tutorial there is no need to return a list
Comment: there is an error on var count = getCaf.Count(); the error is "does not contain for 'Count' accepting a first argument of type"
Comment: sorry, Count is a property, not a method.  Your query is returning a SET of rows, so it makes sense to map it to a List.  If ALL you want is the count, there are ways to do that without selecting and returning all of the data.
Comment: I tried var result = getUser.Result.Count; and it worked


MySQL finding the average of a count() of rows

Question: I'm trying to find a way to modify this query:
SELECT work_order_number, COUNT(1)
FROM tmanagerprod.work_order_detail
where client_id = 'x' and transaction_type = 'y'
group by work_order_number;

The query returns a count of the number of records where work_order_number = 'x' and I need the average of that count. I've tried various iterations of the avg() function, trying to average the COUNT(1) but so far it's resulted in a string of errors.  I have also reviewed similar questions on here but they all seem to be average data values not row counts and the suggestions have not worked for me.
Any assistance greatly appreciated.
Comment: Not sure what you mean here as you can interpret this question/SQL on multiple ways.. See [Why should I provide a Minimal Reproducible Example for a very simple SQL query?](https://meta.stackoverflow.com/questions/333952/why-should-i-provide-a-minimal-reproducible-example-for-a-very-simple-sql-query)
Comment: Welcome to SO. Please see: [Why should I provide an MCRE for what seems to me to be a very simple SQL query?](https://meta.stackoverflow.com/questions/333952/why-should-i-provide-a-minimal-reproducible-example-for-a-very-simple-sql-query)
Answer: Put it in a subquery.
SELECT AVG(count)
FROM (
    SELECT COUNT(*) AS count
    FROM work_order_detail
    WHERE client_id = 'x' and transaction_type = 'y'
    group by work_order_number) AS x

Comment: Thank you, that worked brilliantly, and thank you for the super fast response!


C# API Rotas (Iniciante)

Question: Criei um novo projeto do tipo: ASP.NET Web Application - WEB API
Crei um novo controller, porém, não estou conseguindo diferenciar as ACTIONS.
Se eu tenho mais de um método do tipo GET, na hora que eu requisito recebo o erro:
"Multiple actions were found that match the request: \r\nIndex on type DGBar.Controllers.TestController\r\nTeste on type DGBar.Controllers.TestController"

A rota configurada é a padrão:
routes.MapRoute(
      name: "Default",
      url: "{controller}/{action}/{id}",
      defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
  );

Acredito que o erro esteja na rota, onde não foi configurarda o endereço com "api" mas não consegui fazer os ajustes necessários para que funcionasse.
Estou requisitando "https://localhost:44398/api/Test/Teste" mas a action TESTE está sendo completamente ignorada.
Alguém poderia ajudar?
Obrigado.
https://github.com/zecaloteiro/DGBar
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;

namespace DGBar.Controllers {
  public class TestController : ApiController {
    [HttpGet]
    public IHttpActionResult Index() {
      return Json("Index");
    }
    [HttpGet]
    public IHttpActionResult Teste() {
      return Json("Teste");
    }
  }
}

Comment: consegue postar os métodos que tem na sua controller também?
Comment: Opa, claro. Editei o post. Muito obrigado pela força.
Answer: Você pode criar suas próprias rotas da seguinte forma.
namespace DGBar.Controllers {
  public class TestController : ApiController {
    [HttpGet]
    public IHttpActionResult Index() {
      return Json("Index");
    }
    [HttpGet("teste")]
    public IHttpActionResult Teste() {
      return Json("Teste");
    }
  }
}

O seu erro ocorre por terem dois métodos com o verbo GET sem diferenciação entre eles.
Comment: Obrigado pelo retorno. Mas se eu utilizo a notação que você sugeriu, obtenho erro: 'HttpGetAttribute' does not contain a constructor that takes 1 arguments
Comment: Acredito que meu conceito de API REST está um pouco equivocado pois após pesquisar acredito que minha estrutura deveria ter apenas tipos de chamada (get, post, put, delete, etc) dentro do controller e não precisar criar {controle}/{action}
Answer: Você pode fazer assim:
Nas suas configurações, vai ficar o default:
config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{action}"
        );

Já na sua controller, você deve usar duas nomenclaturas:
 [RoutePrefix("test")]
    public class TestController : ApiController
    {
        [HttpGet]
        [Route("index")]
        public string Index(string No)
        {
            try
            {
                return No;
            }
            catch (Exception e)
            {
                return string.Empty;
            }
        }

        [HttpGet]
        [Route("teste")]
        public string Teste(string No)
        {
            try
            {
                return No;
            }
            catch (Exception e)
            {
                return string.Empty;
            }
        }
    }

Aí para consumir utilize:
endereco/api/test/index ou endereco/api/test/teste
Você pode ler mais sobre na documentação oficial:
https://docs.microsoft.com/en-us/aspnet/web-api/overview/web-api-routing-and-actions/attribute-routing-in-web-api-2
Comment: Obrigado. Funcionou. A notação Route("") substitui o  [HttpGet("teste")] do .net Core.

C# API Rotas (Iniciante)


Options for RPC in Mono? (WCF Alternatives)

Question: I have had the opportunity to spend a great number of hours trying to use WCF in mono. It is simply too poorly implemented at this point to be put into a production environment, for anything beyond toy applications. It does not survive a 24/7 load.
I do currently have WCF on Mono running in a production environment, but I need to move away from it, at least in the near term, to bring stability to my software. Currently I'm surviving by restarting processes every few hours, and often times that is not enough.
I'm looking for potential alternatives. All of my communicating entities are .net based, with some being Mono on Linux and others being ms.net on Windows Server. I'm very tempted to roll my own RPC layer with protobuf-net as the serialization layer, but I'd prefer not to do this. The big plus with protobuf-net is that it has good C++ support, which is something that I value.
Has anyone out there achieved stability with RPC on Mono? If so, what did you do?
Updated: I did not mention that I'm looking for stateful duplex messaging. This is a considerably important piece of information. I'm not stuck with it, but I very much want it. WCF provides this with net-tcp duplex channels.
Comment: This is an excellent question and I really hope to see some decent answers.  I, too, run into the same issues with mono.  Insofar, mono is not something I can trust in a production environment when it comes to WCF.
Answer: Try ServiceStack for REST/WS

A modern, code-first, DTO-driven, WCF replacement web services
  framework encouraging best-practices for creating DRY,
  high-perfomance, scalable REST web services

If you're looking for something duplex and tcp based, you might consider zeroMQ, although it's problem set is slightly different than WCF.
Comment: After a great deal of research and a whole lot of code, I am switching to zeroMQ. I am using zeroMQ for the transport and protobuf for the message formatting. I have implemented a few patterns such as Request/Reply, Pub/Sub, etc. It's working very well and is stable under mono. It's not perfect, but it is certainly working well for my environment. Thanks for the answer!
Comment: +1 This looks like a great option for RESTful web services, and an alternative to one WCF feature. I will find a use for this in some places, but (unless I'm missing something) you cannot implement a stateful duplex service. I have updated my question to highlight this detail.
Comment: @John Hargrove: You might also be interested in zeroMQ (updated my answer) if you're interested in duplex tcp.
Answer: RestSharp is often mentioned in Mono's IRC channel (e.g. #mono on GimpNET) as an alternative and works with Mono, MonoTouch, Silverlight, Windows Phone 7 and, of course, the regular FX too.
Comment: I'll look into this possibility. My sentiments are the same as I mentioned to Brook in his answer re: ServiceStack. It replaces one aspect of WCF, but there is a lot of WCF to replace, and I have places where a REST service won't cut it.
Answer: Remoting? http://msdn.microsoft.com/en-us/library/kwdt6w2k(v=vs.71).aspx
Comment: Can anyone comment to the reliability of remoting in Mono? I'm not really a fan of remoting, but if it works, it works.
Comment: It works like a charm. It is an extremely stable piece of sw.
Answer: Try NFX.Glue - works on Mono
Blog with overview


J-query loop issues

Question: I have what is supposed to be a simple jquery delayed image loop
The fiddle is here
I have checked my syntax and i do not know why it refuses to work.
All the css and code seems to be correct.
Here is the function
$(document).ready(function () {
$.doTimeout('loop', 500, function () {
    //changes the background of img2 to 'i' in 'sequence'
    $(".img2").css('background', 'url(' + sequence[i] + ')');
    //increments 'i' for the next image
    i++;
    //toggles the class
    $("img1").toggleClass("img2");
    //changes the the background of img1 to 'i' in 'sequence' ready for when class is toggled again
    $(".img1").css('background', 'url(' + sequence[i] + ')');
    //toggles the class
    $("img2").toggleClass("img1");
    //increments 'i; for the next change
    i++;
    //restarts the loop if i is equal to the sequence length
    if (i === sequence.length) {
        i = 0;
    }
});

toggleclass has to be there because i intend to later add css3 transitions which will make each image fade in
Can someone help, please!
Comment: sorry, the link was broken, i have fixed it now
Answer: Return True in your callback for the loop to happen again, it is mentioned in the document.
$(document).ready(function(){
  // Start a polling loop with an id of 'loop' and a counter.
  $.doTimeout('loop', 500, function(){

      $('.img1').css('background', 'url(' + sequence[i] + ')');
      i++;
      return true;
  });
});

Another issue is that your loop will break as your array will go out of bounds as you keep incrementing, instead use Array.shift to get the first element out of array and push it back to the end of the array. With this elements in the array will go in a cycle, you dont have to maintain a counter and reset it etc...
Right way to do it is:-
Demo
var sequence = ["http://goo.gl/u4QHd",
    "http://goo.gl/s5tmq",
    "http://goo.gl/MMsQ6",
    "http://goo.gl/dtEYw"];

$(document).ready(function(){
  // Start a polling loop with an id of 'loop' and a counter.
  $.doTimeout('loop', 500, function(){
     var url = sequence.shift(); //Remove the first element out of the array
      sequence.push(url); //push it to the end of the array. probably you can put it after the next statement.
      $('#img1').css('background', 'url(' + sequence[0] + ')');//get the first item from the array. this will always be the next one to previous cycle.
      return true;
  });
});

Comment: Updated my answer.. Does it make sense?
Comment: @CaedanLavender The documentation is free for everyone: https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/push and https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/shift
Comment: can you explain what .shift and .push is doing in your script?
Comment: @bažmegakapa Thanks... @@CaedanLavender Hope you got it now...
Comment: @CaedanLavender Please consider marking as answer if this resolved your issue and got your questions answered...
Comment: Alright, your answer has made the delay work perfectly, however the next part of the problem is that when it toggles class to the other div the css3 transistions are not working. The fiddle should have been updated but just in case here is the:[link](http://jsfiddle.net/caedanlavender/XTkB3/)

J-query loop issues


Importing Bootstrap CDN-mediated styles into the Sub-theme's Style.css

Question: I've opened a fresh Bootstrap sub-theme. This sub-theme is empty of any styles. What is the right way to import the CDN-mediated style sheets into the (now-empty) Style.css of the sub-theme?
It's a long story why I don't want to use the Bootstrap CDN in that particular case but I really just want everything to be local.
How could I import the basic Bootstrap Stylesheets into my Sub-theme's Style.css file and finally use everything local?
Thanks,
Answer: You can use Bootstrap Library module to do that. quoting from the project page:

This module is fully compatible with the Bootstrap Theme. If you wish,
  use it as an alterative to the CDN loading.
Comment: there is take a look at your subtheme.info file and instruction in this page [this page](https://www.drupal.org/node/1978010). but I think using the library is more flexible
Comment: Yes, that's all.
Comment: Isn't there a manual way? Just in case?
Comment: After enabling, should I now open a directory at sites/all/libraries by the name "Bootstrap" (all lowercase I guess) and extract a clean Bootstrap-install from http://getbootstrap.com ? That's all?
Comment: In getbootstrap.com here: http://getbootstrap.com/getting-started/#download there are 3 download options: Bootstrap, source code, and SASS. I guess "Bootstrap" which is compiled is what I need but I may be wrong: Could you please update your answer with these details and say what is most fitted and how to set the folders inside the newly-created "bootstrap" library folder? Thank you,
Comment: Can you please detail on this in the answer?
Comment: @benos, my answer is answering your question. how to setup the libraries is not the scope for the question.  The answer is clearly directed you to the right direction. you even accepted the answer then unaccepted it!
Comment: I know what I did but when I came to did that I've seen various versions of Bootstrap and I think that an answer that totally answers the question and doesn't let you gamble on what version is the right one - should mention it in the first place. To save time for anyone who will come across it and deliver the most precise direction.


how to return view html into controller to ajax success

Question: I want to return whole html into controller to ajax response. I am using render() but not getting any data into the return method
Below is my ajax:
$.ajax({
                            type: 'GET',
                            url: '{{url('/filter_each_video')}}',
                            data : { resolution : myCheckboxes, fps : myCheckboxesfps },
                            dataType: 'json',
                            success: function (response) {
                                console.log(response);

                            },
                            error: function (data) {
                                console.log(data);
                                // console.log(data);
                            }
                });

Below is my controller from where actually render the view
function filter_each_video(){
        if(request()->ajax()){

            $item = Item::whereIn('format', $_GET['resolution'])->get();
            $formats = DB::table('items')->select('format')->distinct()->get();
            $fps = DB::table('items')->select('fps')->distinct()->get();
            $data['item_count'] = $item;
            $data['item'] = $item;
            $data= $this->sellWise($data);
            $data= $this->starWise($data);
            $data= $this->dateWise($data);
            return view('frontend.pages.videos_for_each_filter', compact('data','formats','fps'))->render();
        }
    }

Below is the view file from where I am set value and tha whole html return to controller to ajax response
<?php
        $html ="";
               $html.= '
';

               foreach($data['item'] as $video){

                  $html.= '

Video Name

';

                }

                $html.= '
';

    return $html;

?>

If anyone have idea what exact i am doing wrong to fetch html content to controller then please let me know
I want to return whole html to the ajax response
Comment: Can you please change `dataType: 'json',` to `dataType: 'html', ` inside the ajax?
Comment: @ Shamir Imtiaz still not getting any response.
Comment: Do you get properly the data from controller? Please just pass in random data like `return "hello";` in controller and check the data is properly coming in ajax `success:`.
Comment: @Shamir Imtiaz from controller return data commingin ajax success. Return Hello pproperly comes in ajax success:
Comment: Sir, inside your view, you dont need to return html or anything. Just use normal php/blade code in view file. Please update your code and let me know the code is working.
Comment: @Shamir Imtiaz I removed html But still I am getting empty data
Comment: Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/238210/discussion-between-shamir-imtiaz-and-praful).
Answer: (1) Have you tried with response($output, 200, $headers)?
$html = view('frontend.pages.videos_for_each_filter', compact('data','formats','fps'))
           ->render();

\Log::debug('Rendered HTML', ['html'=>$html]);

return response($html,200);

Check your /storage/logs to double check the $html is right.
(2) You can also try with JSON:
return response()->json(['html' => $html]);

And on client side,
console.log("res is ", response.data.html);

On a side note, you should validate the request data and not use $_GET directly. Your controller method should look more like this...
use Illuminate\Http\Request; // (? From memory, maybe check the namespace)

public function filter_each_video(Request $request)
{
    $request->validate(['resolution' => 'required|string']);

    if( $request->ajax() ){

        $item = Item::whereIn('format', $request->resolution)->first();

        // ... cont'd
    }
}

If you're getting an empty response, throw some \Log::debug statements in there and find out where you're losing the response.
Comment: I tried both above but in response I am getting empty data. Like this {"html":""}
Comment: Did you check your storage logs to make sure that `$html` is not empty?


How best to search a Javascript array for partial matches?

Question: I'm very new to Javascript and I expect there is a simple answer, but how can you search a Javascript array for a partial match?
So if I have an array such as:
const fruits = ["Banana", "Orange", "Apple", "Mango"];

I know I can easily check if the array contains something using:
fruits.includes("Mango");

But what if I want to know whether an array contains a value that partially matches a certain sequence of characters?
For example, if I want to know if the above array includes an entry that has the string "Man" in it.
Answer: You can use filter if you want to find multiple objects might match, or find if you only want one, or if you just want to know if it exists at all use some

const fruits = ["Banana", "Orange", "Apple", "Mango"];

const fruitsWithMan = fruits.filter(x => x.includes("Man"))
console.log(fruitsWithMan); // returns array

const oneFruitWithMan = fruits.find(x => x.includes("Man"))
console.log(oneFruitWithMan); // returns single item

const hasFruitWithMan = fruits.some(x => x.includes("Man"));
console.log(hasFruitWithMan); // return boolean
Comment: @LiamPillay no reason at all. `includes` is almost certainly more appropriate.
Comment: Why are you using `indexOf` instead of `includes`?
Answer: You could filter the array this way :

const fruits = ["Banana", "Orange", "Apple", "Mango"];

console.log(fruits.filter(fruit => fruit.includes("Man")));
Answer: ["Banana", "Orange", "Apple", "Mango"].some(fruit => fruit.includes("Man"));


Excel Macro to Combine two excel spreadsheets based on duplicate data

Question: I have two excel spreadsheets which contain data. Both of these sheets contain an ID number and then other corresponding data. Sheet 1 is essentially a master sheet which contains all existing ID numbers (and other corresponding data), while sheet two is a specific set of data that will only contain some of the ID numbers found in sheet 1 (All ID numbers in sheet 2 exist in sheet 1, but not the other way around). Currently, sheet 1 contains data from columns A to F, with the ID number in column C, while sheet 2 contains data from columns A to C with the ID number on column A. Also note that ID numbers are in increasing order as we move down the sheet and each ID number in it's respective sheet is unique.
What I want, is if an ID from sheet 2 is equal to an ID in sheet 1, then I would like to tack on columns B and C from sheet 2, to the end of the corresponding row in sheet 1, and then also delete any rows in sheet 1 where there does not exist the same ID number in sheet 2. To clarify, sheet 1 looks like this:
+-------+----------+--------+--------------+
|Year   |Country   |  ID #: |Columns D,E,F |
+-------+----------+--------+--------------+
|2012   |CA        |123456  |data          |
+-------+----------+--------+--------------+
|2015   |US        |565382  |data          |
+-------+----------+--------+--------------+
|2008   |US        |765382  |data          |
+-------+----------+--------+--------------+
|2012   |CA        |956471  |data          |
+-------+----------+--------+--------------+

Sheet 2 looks like this:
+-------+----------+--------+
|ID #:  |Quantity  |Value   |
+-------+----------+--------+
|123456 |435       |12523   |
+-------+----------+--------+
|765382 |1136      |52342   |
+-------+----------+--------+
|956471 |49        |5562    |
+-------+----------+--------+

Then after combining the rows with the same ID number and deleting all the ones from sheet 1 that do not contain a corresponding ID from sheet 2, we get:
+-------+----------+--------+--------------+-----------+---------+
|Year   |Country   |  ID #: |Columns D,E,F |Quantity   |Value    |
+-------+----------+--------+--------------+-----------+---------+
|2012   |CA        |123456  |data          |435        |12523    |
+-------+----------+--------+--------------+-----------+---------+
|2008   |US        |765382  |data          |1136       |52342    |
+-------+----------+--------+--------------+-----------+---------+
|2012   |CA        |956471  |data          |49         |5562     |
+-------+----------+--------+--------------+-----------+---------+

Since my sheet contains hundreds of thousands of rows, I cannot do this manually, so I need a macro that can finish this task much more efficiently.
Here is what I have so far:
Sub mergeSheets()

Dim c As Range, cfind As Range, x, dest As Range, cfind1 As Range
On Error Resume Next
Worksheets("sheet3").Cells.Clear
With Worksheets("Sheet1")
.UsedRange.Copy Worksheets("sheet3").Range("a1")

For Each c In Range(.Range("a2"), .Range("c2").End(xlDown))
x = c.Value

    With Worksheets("sheet2")
    Set cfind = .Cells.Find(what:=x, lookat:=xlWhole)
    If cfind Is Nothing Then GoTo line1
    .Range(cfind.Offset(0, 1), cfind.End(xlToRight)).Copy
        With Worksheets("sheet3")
        Set cfind1 = .Cells.Find(what:=x, lookat:=xlWhole)
        If cfind1 Is Nothing Then GoTo line1
       cfind1.End(xlToRight).Offset(0, 1).PasteSpecial
        End With 'sheet3
     End With  'sheet2
line1:
 Next
 End With 'Sheet 1
    Application.CutCopyMode = False

End Sub

Thanks
Comment: What have you tried? SO is not a "code for me" site, but rather "help me with my code". Please read [How to Ask](http://stackoverflow.com/help/how-to-ask) for how to ask a question. Please post any code/macros/formulas you've tried so far.
Comment: Why VBA?  Why not simply use `VLOOKUP` on sheet1, and then filter out the `#N/A`'s?
Comment: So where did you go?
Answer: Maybe a different approach than your code, loop through column C in sheet1  and find the ID# in columnA in sheet2, then get the info, copy and paste would not be required.
Sub Get_It()
    Dim sh As Worksheet, ws As Worksheet
    Dim LstRw As Long, Rng As Range, c As Range, Fx As Range

    Set sh = Sheets("Sheet1")
    Set ws = Sheets("Sheet2")

    With sh

        LstRw = .Cells(.Rows.Count, "C").End(xlUp).Row
        Set Rng = .Range("C2:C" & LstRw)

        For Each c In Rng.Cells

            Set Fx = ws.Columns(1).Find(what:=c, lookat:=xlWhole)

            If Not Fx Is Nothing Then
                c.Offset(, 4) = Fx.Offset(, 1)
                c.Offset(, 5) = Fx.Offset(, 2)

            Else: MsgBox c & " is Not Found"' remove msgbox if desired, just an example

            End If

        Next c

    End With

End Sub


login example for iphone

Question: Can anyone get me a login page example for iphone ?
Answer: short answer - Create a view with 2 labels (lblLogin & lblPassword) and 2 text fields (txtLogin & txtPassword) then generate the necessary source
long answer - post what you have tried so far
Comment: using IB and XCode, link the button press(es) to actions.  If that doesn't make sense, SO will not help you (you'll need to learn more about the platform before going any further)
Comment: I want to find how to trap the button's click gesture. how to do that ?

login example for iphone


Forming piano arpeggios/accompaniment for a particular song

Question: I am an intermediate self-taught pianist(Trinity Grade 5).
I learnt a beautiful arrangement of a GOT song which I found on YouTube. It had really difficult left hand patterns and the arranger seemed to have created them for that particular song only. They fit perfectly to the song and when I tried using them elsewhere, it just doesn't sound right. I hope I am clear.
I want to know how pianists create original arpeggios, get creative and what process goes into creating amazing arrangements and I want to do the same in my own arrangements and pieces. Any help would be appreciated.
Answer: You get better at arranging with experience.  Lots of trial-and-error.  Make sure you have the correct chords for the song you are arranging.  Decide what style of accompaniment would suit it best - flowing arpeggios, chords, or simple bassline only, etc.  Each song will have its own particular accompaniment (including chordal sequence and style) and its up to you to fashion it to suit.  Also, choosing a different style of accompaniment for the same song will change the song's character.