Does this passage have a lydian sound?

Question: The music sources is Album national russe (Köhler, Louis), and the particular passage is...

...before saying the music is in G major and there isn't any C# to make lydian, hear me out. The basic voice leading for I6 IV would have voice leading of ^5 ^6, and if the line to the ^6 was a descent it would use a lowered seventh, like these...

If the lowered seventh version were tonicized to C the line would become ^5 ^4 ^3. So, the point I'm getting at is the ^7 is raised rather than the typical lowered. It's even emphasized as an accented passing tone. The F# is played above a bass/root C for an augmented fourth.
I would think from a jazz perspective that C chord would be labelled not as plain Csus4 but something like C(#4). Of course the style of this music isn't jazz, but it seems to me that augmented fourth (keep in mind it's not resolving like a dominant tritone to B-G, C is the chord root) is the source of the lydian sound. My understanding is common practice avoided that sound by lowering the ^7. The fact that it isn't lowered, and is accented, makes me think the passage could be described as having a lydian sound, lydian tonality. Even if it is for only a brief passage.
Comment: Why wouldn't "basic" voice leading for I6-IV involve ^5-^4 and more than 3 voices (so SATB can get ^5-^4, ^1-^6, ^1-^1, and ^3-^4 respectively)?
Comment: I don't really see this: it's "lydian" just as much as any passage on the fourh grade that uses the leading tone, but besides that there's no modulation, it's just a passage from I to IV, the melodic movement is in the tonality, and I don't see using the lowered seventh as mandatory in this case; yes, it's in the downbeat, but it's also very short and used almost like an appoggiatura.
Comment: There is a difference in how classical analysis and jazz analysis think about modes, and I think your question falls in that crack.
Comment: @Dekkadeci, the SATB voice leading you gave is essentially the `V65/IV IV` I gave but without the motion through the `^7`. That just avoids the whole point of my question regarding `^7`.
Answer: If you analyze the passage as if it tonicizes C major instead of remaining in G major, then you can say that the passage has a Lydian sound. F♯ does turn the C major scale into the C Lydian scale, after all.
Do note that every bar in the passage except for the highlighted Bars 9-10 and the similar Bars 13-14 make claiming that Bars 9-10 tonicize C major (the IV chord) a hard sell, as Bars 1-8 keep up a G-D double pedal on the first beats of those bars, and Bars 11-12 and Bars 15-16 can both be harmonically analyzed as V-I in G major, inversions and nonchord tones notwithstanding. Bars 15-16 cadence at a repeat and an assumed phrase ending to boot, making a sell that the passage drifts away from G major at any point even harder.
Answer: To complement @Dekkadeci's correct analysis ...
OP mentions a "jazz context". So let's imagine this song being played by a jazz group with a soloist improvising over the chord changes.
The expected "arrangement" of measures 9–13 would be G | C | D | G without alterations. Jazz musicians would recognize that the entire passage is in the key of G, and that the C chord is not changing the tonality. Thus, the soloist (and accompanying instruments) would play F#, not because the chord needs alteration or any reference to Lydian, but because G major has F# in it.
Certainly, heard in isolation, there is a Lydian-ish sound, but this is incidental and would not be considered analytically significant. Said another way: the measure is Lydian-ish, but the passage as a whole is not.
An equivalent question would be to ask if measure 11 has a Mixolydian sound, since there is a C natural against what is otherwise a D major chord. And in a jazz context, many musicians would use a Mixolydian scale in that measure, but analytically there's no change of mode.

It's also worth noting that the melody itself is an elaborated, descending G major scale:

Does this passage have a lydian sound?


Checkpointing and restarting X11 applications

Question: I want to checkpoint and restart X11 applications.  I am using the BLCR (Berkeley Lab Checkpoint/Restart (BLCR)) tool.
BLCR is not able (without modifications) to reinitiate the connection to the X-Server.  I used an interposition library to log all Xlib function calls with their parameters to a text file.
Now I want to be able to re-use this logged function call.
Is there a better way than to save them to a text file and parsing/interpreting them during the restart procedure?
The application which is checkpointed should redo the calls which were logged, but this seems to be not as easy as it has sounded first.
Comment: I think the approaches used by http://pages.cs.wisc.edu/~zandy/guievict/ or http://code.google.com/p/partiwm/wiki/xpra make more sense than your approach.  What do you think?
Comment: Good question, but a hard problem.
Comment: I don't follow, why redo the calls?
Answer: I've not tested this, but I think you might be able to solve this one by spawning an xmove child process and making sure this gets stored in the checkpoints. Your application would talk to xmove instead of the XServer directly and every time you restore from checkpoint you would "move" to the current xserver again.


How to find factors of a number using the simplest python method

Question: how to find all factors of a number and list the factors in a list.
Input:
   >>>factors(72)

Output:
   [2, 2, 2, 3, 3]

I have taken some code down because this is getting a lot of views and this is a HW questions so i don't want it copied.
Comment: What's not working? Any error messages / exceptions?
Comment: after running the def factors i get this
Comment: For reading material, please see [this post](http://stackoverflow.com/questions/453793/which-is-the-fastest-algorithm-to-find-prime-numbers) discussing various fast algorithms to determine prime factorization. It is tagged as `C++` but is mostly language agnostic.
Comment: No, you don't need `math`. Because you use `yield`, it returns a generator. Try `list(factors(360))` (or whatever number you want) for output
Comment: no, still same thing while keeping the same for loop
Comment: Also, you should take the second `for` loop outside of the `def` block (or you'll get some nasty recursion problems).
Comment: if i do that it give me more issues:
    for i in range(2, n + 1):
TypeError: 'float' object cannot be interpreted as an integer
Comment: @Michelle Please see and read my answer.
Answer: With regard to your question 1: factoring is hard. That's why it's at the core of many cryptographic algorithms --- we currently don't know a way to quickly factor a very large number.
For small numbers, your algorithm will do. For slightly larger numbers, I've had the same question --- apparently Pollard's Rho is a good algorithm for this purpose. For large numbers, we don't know.
Now to your question 2:
First of all, in your prime(n) function, you don't need to check if n%i==0 all the way up to n. You only need to check this up to sqrt(n), because if there is any pair of integers (a,b) such that a * b = n, then one of these integers will necessarily be less than or equal to sqrt(n). So you only need to check up to sqrt(n). This saves you a lot of computations.
Here's your factors function:
from math import ceil

def factors(n):
        factors = []
        while n > 1:
                for i in range(2,int((ceil(n/2.0))+1)):
                        if n%i==0:
                                factors.append(i)
                                n = n/i
                                continue
                factors.append(n)
                break
        return factors

Answer: def factors(n):
a = []
x = 2
while x * x <= n :
    if n % x == 0:
        a.append(x)
        n /= x
    else: x += 1
if n > 1: a.append(n)
return a

all downvoted  as quickly as possible.
Answer: Here is a solution using decomposition by prime numbers. It is much faster.
import bisect
import math
import pathlib

primes = []
last_prime = None

def _get_primes():
    """
    Load all the primes in global primes. Set global last_prime to last prime
    read.
    """

    global primes
    global last_prime
    path_to_primes = pathlib.Path(__file__).parent \
            .joinpath('../resources/primes.txt')
    with path_to_primes.open() as file:
        for line in file:
            for n in line.split():
                n = n.strip()
                if n:
                    n = int(n)
                    primes.append(n)
    last_prime = primes[-1]

def gen_primes_before(n):
    """
    Generates all the primes before n in reverse order.
    """

    assert n <= last_prime, "Maximum value for n is {}".format(last_prime)
    pos = bisect.bisect_left(primes, n)
    if pos:
        yield from primes[:pos]

def gen_factors(n):
    """
    Generates all the factors of a number. May return some values multiple
    times. Values returned are not ordered.
    """
    type_n = type(n)
    assert type_n is int or (type_n is float and n.is_integer()), "Wrong type"
    n = int(n)
    r = int(math.sqrt(n)) + 1
    assert r <= last_prime, "n is over limit"
    yield 1
    yield n
    for prime in gen_primes_before(r):
        partner = n/prime
        if partner.is_integer():
            yield from gen_factors(prime)
            yield from gen_factors(partner)

def get_factors(n):
    """
    Get all the factors of n as a sorted list.
    """
    return sorted(set(gen_factors(n)))

_get_primes()
if __name__ == '__main__':
    l = (1e9,)
    for n in l:
        print("The factors of {} are {}".format(n, get_factors(n)))

I made a repository: https://github.com/Pierre-Thibault/Factor


Sampling uncertainty of posterior probability distribution

Question: I'm working on a problem with 3 possible outcomes and a bunch of features. I have a regression model that outputs probabilities for each category and I'd like to extend these probabilities to probability distributions. So instead of getting an output of <code>[0.2,0.3,0.5]</code>, I'd get a probability density function or at least a quantification of the uncertainty of the prediction. I've looked into some models that give these distributions but haven't found any way to use it on a multiple output problem. Is there any way to do this?
Comment: Only your title is too general. You can change this to something like: sampling uncertainty of posterior probability distribution - or something similar, but more specific than your present title.
Answer: Interesting problem - which is most often overlooked in data science and machine learning. The output probabilities $\bf{y}$ are indeed estimates of the underlying (true) posterior probabilities (your $[0.2,0.3,0.5]$). Sampling a different training set (from your presupposed 'oracle'), will yield a slightly different set of output probabilities, when the identical input feature vector $\bf{x}$ is presented to the classifier.
The distributions of $\hat{P}(\bf{y} \mid \bf{x},\bf{\theta})$ - they have been studied for linear and quadratic discriminant analysis ($\theta$ is the parameter vector of the discriminant classifier).
And yes, also the sufficient parameters of these distributions of $\hat{P}(\bf{y} \mid \bf{x},\bf{\theta})$ have been derived. Specifically the variance of each posterior probability has been derived. A mathematically sound description (with the relevant references to papers in the statistical literature), can be found in Chapter 11 in the book: Discriminant analysis and statistical pattern recognition by G.J. McLachlan, Wiley (2004).


Select rows from Spark DataFrame based on a condition

Question: I have two Spark dataframes:
df1
+---+----+
| id| var|
+---+----+
|323| [a]|
+---+----+

df2
+----+----------+----------+
| src| str_value| num_value|
+----+----------+----------+
| [a]|     ghn12|      0.0 |
+----+----------+----------+
| [a]|     54fdg|      1.2 |
+----+----------+----------+
| [a]|     90okl|      0.7 |
+----+----------+----------+
| [b]|     jh456|      0.5 |
+----+----------+----------+
| [a]|     ghn12|      0.2 |
+----+----------+----------+
| [c]|     ghn12|      0.7 |
+----+----------+----------+

I need to return top 3 rows from df2 dataframe where df1.var == df2.src and df2.num_value has the smallest value. So, desired output is (sorted by num_value):
+----+----------+----------+
| src| str_value| num_value|
+----+----------+----------+
| [a]|     ghn12|      0.0 |
+----+----------+----------+
| [a]|     ghn12|      0.2 |
+----+----------+----------+
| [a]|     90okl|      0.7 |
+----+----------+----------+

I know how to implement this using SQL, but I have some difficulties with PySpark/Spark SQL.
Comment: Are ```df1.var``` and ```df2.src``` columns of ArrayType()?
Comment: Yes, `df1.var` and `df2.src` are `array` type with `element:double`
Answer: from pyspark.sql.window import Window
from pyspark.sql.functions import row_number, col

windowSpec  = Window.partitionBy("src").orderBy("num_value")

df_joined = df1.join(df2,df1.var==df2.src).drop("var", "id")
df_joined.withColumn("row_number",row_number().over(windowSpec)).filter(col("row_number")<4).drop("row_number").show()

# +---+---------+---------+
# |src|str_value|num_value|
# +---+---------+---------+
# |[a]|    ghn12|      0.0|
# |[a]|    ghn12|      0.2|
# |[a]|    90okl|      0.7|
# +---+---------+---------+

Answer: I would do it using dense_rank window function.
from pyspark.sql import functions as F, Window as W

w = W.partitionBy('src').orderBy('num_value')
df3 = (
    df2
    .join(df1, df2.src == df1.var, 'semi')
    .withColumn('_rank', F.dense_rank().over(w))
    .filter('_rank <= 3')
    .drop('_rank')
)


Let $Y$ and $Z$ be subspaces of the finite dim vector spaces $V$ and $W$, respectively. Let $R=\{α\in L(V,W):α(Y)\subset Z\}$. What is $\dim R$?

Question: How would I go about proving this? I tried by considering maps from $Y$ to $Z$ and the space of all such maps would have $\dim Y\times\dim Z$ but I have no idea how to extend it to the entire vector space.
My guess is that it would be $\dim Y\times\dim Z + (\dim(V/Y)\times\dim W$ but I'm not sure about this.
Comment: It's a nice guess :) Hint: write $V$ as an internal direct sum $V = Y + Y'$.
Answer: Hint As is often the case, it can be helpful to pick a basis adapted to the constraints of the problem. So, pick a basis $\mathcal E_0 = \{e_1, \ldots, e_{\dim Y}\}$ of $Y$ and extend it to a basis $\mathcal E = \{e_1, \ldots, e_{\dim V}\}$ of $V$, and likewise extend a basis $\mathcal F_0$ of $Z$ to a basis $\mathcal F$ of $W$. In terms of our bases, $\alpha(Y) \subseteq Z$ if and only if $\alpha(\mathcal E_0) \subseteq \operatorname{span} \mathcal F_0$, that is, if its matrix representation has the form
$$[\alpha]_{\mathcal E, \mathcal F} = \pmatrix{\ast & \ast \\ 0 & \ast},$$ where the upper-left block has size $\dim Z \times \dim Y$.


How to define the password protection scheme (e.g. hash function) used by ldappasswd?

Question: I am using OpenLDAP 2.6. When I set an object's password via
ldappasswd -x -D <dn of root user> -W -S <dn of object whose pwd shall be set>

then some hash of the password end up in the attribute userPassword.
What hash function does ldappasswd use? How do I configure the hash function? From the look of it, I assume it defaults to a SHA1 which isn't secure anymore.
Answer:
What hash function does ldappasswd use?

Technically none – it just invokes the 'Change Password' LDAP Extended Operation which causes the LDAP server to use some hash function it finds appropriate (and to store the hash in wherever it finds appropriate – not necessarily in userPassword).
So the hash used by the 'Change Password' exop is configured server-side. For OpenLDAP, that's the olcPasswordHash parameter which defaults to "SSHA" (salted and iterated SHA-1), similar to $1$ hashes. If you want something stronger, you can choose either {CRYPT} to use whatever hash algorithms the system's crypt() function provides (i.e. the same as with /etc/shadow – possibly bcrypt or yescrypt if the OS uses libxcrypt, otherwise the same sort of salted SHA), or {ARGON2} if you have the additional slapd-argon2 module installed (it's part of OpenLDAP but in the "contrib" tree).

slapd.conf
cn=config

Default (iterated/salted SHA-1):password-hash {SSHA}
Default:olcPasswordHash: {SSHA}

System crypt() using yescrypt, if libxcrypt is in use:password-hash {CRYPT}password-crypt-salt-format $y$%.16s(not tested but I think that should work)
System crypt() using yescrypt:olcPasswordHash: {CRYPT}olcPasswordCryptSaltFormat: $y$.16s

Argon2 if the slapd module is available:moduleload argon2password-hash {ARGON2}
Argon2 if the slapd module is available:olcModuleLoad: argon2olcPasswordHash: {ARGON2}


.Net MVC3 app_offline.htm issues with css/images

Question: I'd like to use the root app_offline.htm file as a maintenance page.
Design came back with a maintenance page that will require images and css.
I added the image and ran the site, but the image won't render. I looked in firebug and saw that the image is showing a 503 error (service unavailable). This makes sense seeing as runAllManagedModulesForAllRequests="true" is in the web.config, so all requests will run through .net, hence the error.
I thought I'd be able to do this in the web.config, but no luck:
<location path="offline">
    <system.webServer>
        <modules runAllManagedModulesForAllRequests="false"/>
    </system.webServer>
</location>

Is an app_offline.htm not recommended for MVC? Is there a better alternative?
Answer: If it's not that much images in design, you can embed css and images straight into the app_offline.htm
for css just use a


soap request using sudzc for iphone

Question: I found sudzc, this is excellent for generating Documentation Example Source WSDL.
Example, I used this :
http://www.w3schools.com/webservices/tempconvert.asmx
sudzc will work for me.
What if I have five webservices? Do I need to generate each of them,
and use it in the application?
Any help ?
Thanks
Answer: yes, you will have to use the generator for each operation you want to use.

soap request using sudzc for iphone


Leaflet - Possible to go straight to node instead of popup on click?

Question: I'm using the leaflet module in drupal and would like the user to go directly to the node instead of a popup when clicking upon a marker or polygon. Is there a way to do this?
Answer: The easier way is to use the IP Geolocation Views & Maps module, which works a treat! Partial quote from its project page:

Despite what the name may suggest, IP Geolocation Views & Maps (IPGV&M) is first and foremost a mapping engine.
The module makes it very easy to create Views-based mapping solutions using the map renderer of your choice (Google, OpenLayers or Leaflet) with any location storage module of your choice, e.g.:

Get Locations,
Geofield,
Geolocation Field
Location.

This allows you to bring together modules and feature sets that without IPGV&M you would not be able to combine.
Like beautiful animated marker clustering on Google or Bing or Mapbox ... any of various map providers.
But more importantly IPGV&M adds some features you won't find as conveniently packaged elsewhere.
These include marker differentiation based on field values or ranges (2nd screenshot) with or without font icons, various centering options, super-imposing the current visitor's location, allowing multiple content types to be displayed on the same map, full screen button and mini-map inset (bottom screenshot), polygon support (Geofield), marker tags and tool tips and cross-highlighting of associated content on the page when markers are hovered (and vice versa).
Answer: Well this is not the most elegant way of achieving what I needed but it works until something better comes along. I modified a module called leaflet-views-ajax-popups in order to cannibalize the part of the code which gets the node id of the popup. Here's the replacment js;
<code> (function ($) {
 $(document).bind('leaflet.feature', function (event, lFeature, feature) {
 $(lFeature).click(function (e) {
  var data = {};
  for (var key in this._popup._contentNode.childNodes[0].attributes) {
    data[this._popup._contentNode.childNodes[0].attributes[key].name] =    this._popup._contentNode.childNodes[0].attributes[key].value;
 }
    var mytaxid = data['data-id'];
    window.location = 'taxonomy/term/' + mytaxid ;
 });
 });
 })(jQuery);
</code>
Still hoping someone can steer me to some simpler code.


How to set properties for a specific chart only using the views integration of the Charts module?

Question: I'm creating charts using the charts module and its integration with the Views module.
I want to set options for only some charts and found that in charts.api.php:
/**
 * Alter an individual chart before it is printed.
 *
 * @param $chart
 *   The chart renderable. Passed in by reference.
 * @param $chart_id
 *   The chart identifier, pulled from the $chart['#chart_id'] property (if
 *   any). Not all charts have a chart identifier.
 */
function hook_chart_alter(&$chart, $chart_id) {
  if ($chart_id === 'view_name__display_name') {
    // Individual properties may be modified.
    $chart['#title_font_size'] = 20;
  }
}

It seems perfect for what I want because it has the if ($chart_id === 'view_name__display_name') { line for specific views but I wonder if I directly add some settings code such as $chart['#title_font_size'] = 10; here (to charts.api.php) or is there any other way to do this?
I mean overriding the charts.api.php inside of the charts module is OK or do I have to write and run these codes anywhere else?
EDIT:
Based on rooby's comments, these are the two ways that I tried to set the properties for each charts (created with views module):

1. Custom Module

I created a custom module called benim.
This is the benim.info file:
name = Benim
description = Override charts properties.
package = Other
core = 7.x

And this is the benim.module file:
<?php

function benim_hook_chart_alter(&$chart, $chart_id) {
  if ($chart_id === 'chartim__block_1') {
    // Individual properties may be modified.
    $chart['#title_font_size'] = 50;
    $chart['subtitle'] = array(
    '#text' => 'Source:',
    );
    $chart['xaxis'] = array(
    '#type' => 'chart_xaxis',
    '#allowDecimals' => 'true',

    );

  }
}

function benim_hook_chart_definition_alter(&$definition, $chart, $chart_id) {
  if ($chart['#chart_library'] === 'highcharts') {
  if ($chart_id === 'chartim__block_1') {
    $definition['title']['style']['fontSize'] = 100;
  }
}
}

2. Template.php

I added the lines below to the theme's template.php.
function mytheme_hook_chart_alter(&$chart, $chart_id) {
  if ($chart_id === 'chartim__page') {
    // Individual properties may be modified.
    $chart['#title_font_size'] = 150;
    $chart['subtitle'] = array(
    '#text' => 'Source:',
    );
    $chart['xaxis'] = array(
    '#type' => 'chart_xaxis',
    '#allowDecimals' => 'false',

    );

    $chart['yaxis'] = array(
    '#type' => 'chart_yaxis',
    '#allowDecimals' => 'false',

    );

  }
}

function mytheme_hook_chart_definition_alter(&$definition, $chart, $chart_id) {
  if ($chart['#chart_library'] === 'highcharts') {
  if ($chart_id === 'chartim__page') {
    $definition['title']['style']['fontSize'] = 100;
  }
}
}

(above mytheme is the name of the actual theme)
Unfortunately, both two ways didn't work for me. I wondered if the $chart_id parameter is correct and checked for different views but the result didn't change.
Note: I also tried clearing caches, and trying inside another theme.
Comment: Hook implementations don't contain the word _hook_ in their name: Replace _hook_ with the theme/module's short name.
Comment: @Pierre.Vriens Your rejected suggested edit was changing the code shown in the question. Since you are not the OP, you cannot know if the code really used `benim_hook_chart_alter()` or `benim_chart_alter()`; therefore, you cannot change the question's code. As for code shown by the OP, the full question is based on a typo; that is why the question got closed: "This question was caused by a problem that can no longer be reproduced, was solved by a cache clear, or was a **simple typographical error**."
Answer: No, not in the charts module, in a custom module of your own.
It is also possible for you to use drupal alter hooks from your theme's template.php file however you should be careful what you put in your theme.
You should only put code relating to visuals in the theme, if you are doing more functional code it should go in a module.
A good rule of thumb is whether or not you would want to keep that functionality if you ever changed themes. If you would want to keep it then that is a possible indicator that it is functional, not visual, and should be in a module.
.api.php files are files that give developers information on the function and hooks that a module makes available to others.
It is basically just documentation so you editing it will do nothing (except for then making that documentation incorrect, which is bad if anyone else wants to use it).
Some reasons why it is generally not a good idea to modify the module itself can be found at Why don't we hack core? (it is talking about drupal core but the same goes for other contrib modules and themes).
One of the main reasons we have drupal hooks is so you don't have to modify the original module if you want to make changes.
So you would create a custom drupal module and then in that module implement the hook like this (changing MODULENAME to the name of the module and the chart ID to match the ID of your specific chart):
/**
 * Alter an individual chart before it is printed.
 *
 * @param $chart
 *   The chart renderable. Passed in by reference.
 * @param $chart_id
 *   The chart identifier, pulled from the $chart['#chart_id'] property (if
 *   any). Not all charts have a chart identifier.
 */
function MODULENAME_chart_alter(&$chart, $chart_id) {
  if ($chart_id === 'view_name__display_name') {
    // Individual properties may be modified.
    $chart['#title_font_size'] = 20;
  }
}

There are lots of other drupal module development resources besides drupal.org docs too. There are some good affordable textbooks and some paid training type websites, as well as a scattering of blog posts in random corners of the internet.
Here is a more functional example of using the definition alter hook.
/**
 * Alter an individual chart's raw library representation.
 *
 * This hook is called AFTER hook_chart_alter(), after Charts module has
 * converted the renderable into the chart definition that will be used by the
 * library. Note that the structure of $definition will differ based on the
 * charting library used. Switching charting libraries may cause your code
 * to break when using this hook.
 *
 * Even though this hook may be fragile, it may provide developers with access
 * to library-specific functionality.
 *
 * @param $definition
 *   The chart definition to be modified. The raw values are passed directly to
 *   the charting library.
 * @param $chart
 *   The chart renderable. This may be used for reference (or read to add
 *   support for new properties), but any changes to this variable will not
 *   have an effect on output.
 * @param $chart_id
 *   The chart ID, derived from the $chart['#chart_id'] property. Note that not
 *   all charts may have a $chart_id.
 */
function THEMENAME_chart_definition_alter(&$definition, $chart, $chart_id) {
  // For the portfolio charts.
  if ($chart_id == 'MY_CHART_ID') {
    $definition['legend']['borderRadius'] = 0;
    $definition['legend']['borderColor'] = NULL;
    $definition['legend']['style']['fontFamily'] = 'Helvetica,Arial,"Nimbus Sans L",sans-serif';
    $definition['legend']['backgroundColor'] = 'transparent';
    $definition['legend']['layout'] = 'vertical';
    $definition['legend']['verticalAlign'] = 'top';
    $definition['legend']['padding'] = 0;
    $definition['legend']['margin'] = 0;
    $definition['legend']['itemStyle']['color'] = '#555555';
    $definition['legend']['itemStyle']['fontSize'] = '12px';
  }
}

Comment: The function to use depends on what you want to alter. Personally I have only used hook_chart_definition_alter() before to modify things based on the highcharts API at http://api.highcharts.com/highcharts - hook_chart_alter() is more on the drupal end than the highcharts end. One thing to keep an eye out for is when you add a new hook to an already enabled module clear the cache after. Maybe add the code you have tried to your question and it might give some clues as to what is the problem.
Comment: I added a better example, which works for me from my template.php file. You can also run it from a custom module though if that fits your needs better.
Comment: That looks like it should be the correct chart ID.
Did you clear your cache after adding the function to your template.php? If you install the devel module and use the dpm() function to debug you can see what the chart_id is. You could also try without the chart ID check so it should be affecting all charts to see if your code is running at all. Sounds like your function isn't running.
Comment: Thanks for the detailed answer. I tried both custom module and template.php but unfortunately didn't get any result, nothing changed. Try to find the problem and become successful on this. (I've also tried some other functions such as hook_chart_definition_alter).
Comment: Actually what I wanted is the same: I want to modify things based on the highcharts API. I added the possible solutions you said to the question.
Comment: could you please add some piece of your code for me to check if your code works or doesn't on my website in order to understand if the problem is about me or something else? Thanks...
Comment: Thanks for the example but I'm still not able to do that. I directly edited the charts.module to check if it works and yes it's working. The problem here is my module and/or template.php file couldn't pass the values to related module/library. Maybe my **chart_id** name is wrong, I'm filling as this: $chart_id == 'chartim__block_1'; my views' name is chartim and block_1 is the name of the views block I created.
Comment: It works now, it was the problem that I misused the parameters. Parameters for chart_alter and chart_definition_alter are different. Thanks again.
Answer: Interesting question, and an even more interesting answer (from Rooby ... again! Thank you!).
Just to be aware, and to take this answer maybe even a little step further): you may want to checkout issue #2347721, titled 'Pass view info to chart (for further processing)', which I recently committed to the most current DEV version. So now you also know which view/display you're actually processing when building the chart. Challenge (for Rooby?): create another sample (variation) that illustrates a good use case for this also?
Disclosure: I'm a co-maintainer of the Charts module.


Help regarding Triggers

Question: I have a table (TableA). On this table I am creating a trigger which will insert a row into another table(TableB) for insert, update and delete actions made on TableA. My intention is to track modification on TableA.
I am having single trigger to do this.
(create trigger trig_name  before insert or update or delete on TableA... – Kind of).
Now I need what is the actual operation performed on the table A.When the trigger insert a row into TableB, I want actual operation performed on the TableA also to be inserted in a column.
Is there any possibilities to capture what operation performed on TableA with single trigger or Do I have to create separate trigger for each of the DML statement operations?
TIA.
Answer: Quoting the docs:

Detecting the DML Operation that Fired a Trigger
If more than one type of DML operation can fire a trigger (for example, ON INSERT OR DELETE OR UPDATE OF emp), the trigger body can use the conditional predicates INSERTING, DELETING, and UPDATING to check which type of statement fire the trigger.
Within the code of the trigger body, you can execute blocks of code depending on the kind of DML operation that fired the trigger:

IF INSERTING THEN ... END IF;
IF UPDATING THEN ... END IF;

Answer: You can use the following predicates in the PL/SQL:
IF INSERTING THEN ... END IF;
IF UPDATING THEN ... END IF;
IF DELETING THEN ... END IF;

Help regarding Triggers


Deeper question about Cayley's theorem

Question: Cayley's theorem states that there exists an injective homomorphism $\phi:G \rightarrow S_n$ for any finite group with $|G|=n$.
Let $\pi: \phi(G) \rightarrow \mathbb{Z}_2$ be the sign map, sending even permutations to $0$ and odd permutations to $1$. If I compose the functions to get $\pi \circ \phi$, then the kernel of the homomorphism is still a normal subgroup of $G$. So, $\ker(\pi \circ \phi) \trianglelefteq G.$
Does this normal subgroup have any significance in group theory? I'm not sure if there would be a connection to a normal subgroup of elements of even order (I can think of a counterexample to this) or if there's even any remote connection with elements of even order for this group.
I also have speculated this means that simple groups must be isomorphic to a generating set of only even permutations. The idea of the proof would be to assume that the kernel of the composition of functions is equal to the identity. Thus, the nonidentity elements of $G$ must map to odd permutations. However, multiplying two odd permutations gives an even permutation. So, there must be a nontrivial element mapping to an even permutation.
If there's anything I should consider or if there are any mistakes in my argument, I'd love to hear it.
Comment: @Lubin What about for $\phi: \mathbb{Z}_4 \rightarrow S_4$ by $\phi(x) = (1 2 3 4)^x$? This is the homomorphism into $S_4$, though set of even permutations would be the set $\langle (1 3)(2 4) \rangle$, NOT the entire set.
Comment: The cycles of $\phi(g)$ are just the right cosets $\langle g\rangle\backslash G$, so we can expect there to be an odd $\phi(g)$ (i.e. a proper kernel) precisely when there is a $g\in G$ of even order $|g|$ for which $|G|/|g|$ is odd.
Comment: I'm sorry, but I said "you should expect". I didn't say it happened all the time. But what about when $G$ is of odd order?
Comment: You should expect that the kernel would be all of $G$.
Comment: Sign representation of $G$ in terms of representation theory.
Answer: Let $G$ be of order $n=2m$, $m$ odd, and $g\in G$ of order 2. then the left multiplication by $g$ is a product of $m$ transposition, so its signature is $(-1)^m=-1$.
In general if $g$ is of order $m$, and $k= {n\over m}$ the left multiplication is a product of $k$ cycles of length $m$, so its signature is $(-1)^k$ if $m$ is even, $1$ if $m$ is odd.

Deeper question about Cayley's theorem


Chart control SmartLabelStyle disappear from time to time

Question: I have Chart control that receives real time data and displays this data on my graph, I also add a label that displays the current value:
Series seriesBps;

            if (seriesBps.Points.Count() > 300)
                seriesBps.Points.RemoveAt(0);
            seriesBps.Points.Add(wf.BitsPerSecond * 0.000001);

            foreach (DataPoint item in chart1.Series[1].Points)
            {
                item.Label = "";
                item.MarkerStyle = MarkerStyle.None;
            }

        chart1.Series[1].LegendText = chart1.Series[1].Name = (wf.BitsPerSecond * 0.000001).ToString("0.##");
        DataPoint Point1 = chart1.Series[1].Points[chart1.Series[1].Points.Count - 1];
        Point1.Label = chart1.Series[1].Name;
        chart1.Series[1].SmartLabelStyle.AllowOutsidePlotArea = LabelOutsidePlotAreaStyle.Yes;
        chart1.Series[1].SmartLabelStyle.IsMarkerOverlappingAllowed = false;
        chart1.Series[1].SmartLabelStyle.MovingDirection = LabelAlignmentStyles.BottomRight;
        chart1.Series[1].SmartLabelStyle.CalloutLineDashStyle = ChartDashStyle.DashDotDot;

And this is how it's looks like:

The problem is that every few seconds when the graphs values changed, the label disappears because it's looks like it went out of  the Chart bounds:

Can it be arranged that the label will show all the time?
Answer: try
 chart1.Series[1].SmartLabelStyle.AllowOutsidePlotArea = LabelOutsidePlotAreaStyle.No
 chart1.Series[1].SmartLabelStyle.AllowOutsidePlotArea = LabelOutsidePlotAreaStyle.Partial

or this to move the labels in left of the datapoint
 chart1.Series[1].SmartLabelStyle.MovingDirection = LabelAlignmentStyles.Top Or _
                      LabelAlignmentStyles.Left Or LabelAlignmentStyles.Right

Comment: The first behave the same, the seconds i didn't understand how to use the OR
Comment: Ok im stumped sorry. The use of `or` is to allow the labels to have choice of `LabelAlignmentStyles` rather than just set to 1 value. This cant be done for all properties but it can for `LabelAlignmentStyles`. I dont think there is a property in `Point.Label` that allows you to change label location,  so it may require the manual drawing of `label` controls and trying to place them near the end of your line
Comment: there is an option to put my label in the right side all the time without moving ?
Comment: I'm not sure, this is what smartlabels do when you set their smart alignment http://i.stack.imgur.com/GRSn8.jpg ... just quickly looking at your second chart it looks as if there might be some blank points at the end of your line since it is shorter than the first. This might mean the `label =""` so thats why you cant see it
Comment: After removed label ="" all the labels remained on the graph and not only one
Comment: no I dont mean remove `label=""` I mean check that the last point is not a blank point or contains no data. You might not be able to apply a label then
Comment: Im not looking at the section of code with `item`. Im guessing that `chart1.Series[1].Points[chart1.Series[1].Points.Count - 1];` is not a plotted point since the line looks shorter than in the top chart. Therefore there is no label to apply so thats you are not seeing a label


Como organizar meus modelos em um projeto Angular Cli?

Question: Gostaria de saber se é possível e também se é uma boa prática organizar meus modelos fora de um diretório de um componente. Por exemplo:
Gostaria de manter meus modelos dentro de um diretório chamado "models" no mesmo nível do diretório "app", dentro de "src".
Answer: Todo o código da sua aplicação deve ficar dentro da pasta src e os respectivos ao seu projeto em app.
O que eu faço nos meus projetos normalmente é criar dentro de src a seguinte estrutura:
<code>src
    /app
        /shared/models
</code>
E nessa pasta model eu coloco todos os arquivos dos models que são compartilhados por toda a aplicação.
O que você sugeriu não está totalmente errado, mas deve ficar dentro de app.


Solve homogeneous differential equation when p and q = 0

Question: I understand how to use $y = e^{rx}$ for solving homogeneous 2 order differential equation, but can't use this method somehow for $y'' = 0$.
$y'' = r^2e^{rx}$
$r^2e^{rx} = 0$
$r^2 = 0 => r = 0$
General solution of 2 order diff is $y = C_1e^{r_1x} + C_2e^{r_2x}$ We only got one $r$ which is 0, so $y = C_1e^{0x}$ => $y = C_1$
How do I get $y = c_1x + c2$ by this approach ?
Answer: Your solution $r=0$ is a twice repeated root, so the general solution is actually $$y=(c_1x+c_2)e^{rx}=(c_1x+c_2)e^{0x}=c_1x+c_2$$
You can see this normally since a (homogeneous) linear differential equation of order $2$ must have $2$ linearly independent solutions. You found one solution $y_1(x)=C_1e^{rx}=C_1$. You should think of a second solution $y_2(x)$, linearly independent from $y_1(x)$ i.e. not a constant multiple of $y_1(x)$, that you will guess. The simplest function linearly independent of $y_1(x)$ is $y_2(x)=C_2xe^{rx}$. Then $$y_2''=C_2re^{rx}(rx+2)=0$$ since $r=0$, so $y_2(x)=C_2xe^{rx}=C_2x$ is another solution. Since we can have a maximum of two linearly independent solutions to a second order linear differential equation, that tells us $y_g(x)=C_1+C_2x =c_1x+c_2$, with $C_1=c_2$ and $C_2=c_1$.
Comment: @Chemistry You can only follow that formula when $r_1$ and $r_2$ are distinct, precisely because it is then that $e^{r_1x}$ and $e^{r_2x}$ are *two* linearly independent solutions to a linear differential equation of order *two*. In your case when $r_1=r_2=0$, we see that $e^{r_1x}$ and $e^{r_2x}$ are not linearly independent of each other since they're multiples of each other (i.e. with constant $1$), so your method does not work.
Comment: If twice, then I should be getting $ y = C_1 e^{0x} + C_2e^{0x} = C_1 + C_2$. why do you bring $x$ ? I'm just following the idea that general solution to homogeneous differential is $y = C_1 e^{r_1x} + C_2e^{r_2x}$
Comment: @Chemistry no. If the general solution were $y = C_1 + C_2$ you could simply combine the two constants and write $y = C$. You need two linearly independent solutions. It can be better understood by thinking about the solution backwards: if $y'' = 0$, then $y$ is either a constant w.r.t. $x$ or a linear function of $x$.
Comment: From the point of thinking backwards, I get it why it's $c_1x + c2$, I just don't get it that by simply following $C_1e^{r_1x} + C_2e^{r_2x}$, how we end up with $c_1x + c2$
Comment: @Chemistry that's because you don't


multi stage binomial "process"

Question: I wish to model the retransmission time of a file that divided into K blocks. I know the successful blocks of first transmission obey the binomial distribution
$$
X_1 \sim \text B(K,p)
$$
, p is the successful probability of packet delivery. Then, the first retransmission(second transmission) try to complete the file delivery with retransmitting the $N_2 = K-X_1$ packets, and the number of successful packets received is $X_2$.
$$
X_2 \sim \text B(K-X_1,p)
$$
The remainder of retransmission follows:
$$
N_i = K - \sum_{m=1}^{i-1}X_m \\
X_i \sim \text B(N_i,p)
$$
We stop the file transaction when $\sum_{m=1}^L X_m = K$.

Eventually, I wish to derive the probability density function of $L$. I think the hard point to model $L$ is the parameter of $X_i$'s distribution depends on $X_{i-1}$.

I know the "multi stage binomial tree model" might be suffice for deriving the PDF of $L$. I also consider if there is a existing stochastic process models this process. But i can't find any.

Any suggestion about the theoretical pdf, stochastic process or approximation is appreciated.
Comment: After your comment, I tried the MGF. But the MGF refer to it's random variable L which is $\prod_{i=1}^L(1+P+Pe^t)^{K-\sum_{j=1}^{i-1}X_i}=
(1+P+Pe^t)^{KL- \sum_{i=1}^L \sum_{j=1}^{i-1}X_i}=
(1+P+Pe^t)^{KL-\sum_{i=1}^{L-1}(L-i)X_i}$. I don't know how to handle this MGF. @Xi'an
Comment: Neat problem: Did you have a try with the moment generating function?
Comment: note: there are mistakes in your mgf: $1+P$ should be $(1-P)$ and the product does not apply because of the dependence between the $X_i$'s, you have to use a sequence of conditional expectations.
Answer: From $$\mathbb{E}[s^{X_1}]=(sp+q)^K$$
(where $q=1-p$), it is rather straightforward to show that
$$\mathbb{E}[s^{X_1+\ldots+X_\ell}]=\left\{s(1-q^\ell)+q^\ell\right\}^K$$ Indeed, if we assume it holds for a given $\ell$ (and it does for $\ell=1$), then
\begin{align*}\mathbb{E}[s^{X_1+\ldots+X_{\ell+1}}]&=\mathbb{E}[\mathbb{E}[s^{X_1+\ldots+X_{\ell+1}}|X_1+\ldots+X_\ell]]\\ &=\mathbb{E}[s^{X_1+\ldots+X_{\ell}}(sp+q)^{K-X_1-\ldots-X_\ell}]\\
&=(sp+q)^K \left\{ \frac{s}{sp+q}\,(1-q^\ell)+q^\ell\right\}^K\\
&=\left\{s(1-q^{\ell-1})+q^{\ell+1}\right\}^K
\end{align*}
From there, it follows that, for a given $\ell$, $X_1+\ldots+X_\ell$ is distributed as a Binomial $\text{B}(K,1-q^\ell)$ random variable. Hence,
\begin{align*}\mathbb{P}(L=\ell)&=\mathbb{P}(X_1+\ldots+X_{\ell-1}<K=X_1+\ldots+X_{\ell})\\ &=\mathbb{E}[\mathbb{P}(K=X_1+\ldots+X_{\ell}|X_1+\ldots+X_{\ell-1})\mathbb{I}_{X_1+\ldots+X_{\ell-1}<K}]\\&=\mathbb{E}[p^{K-X_1-\ldots-X_{\ell-1}}\,\mathbb{I}_{X_1+\ldots+X_{\ell-1}<K}]\\&=\sum_{i=1}^{K-1} {K \choose i} (1-q^{\ell-1})^i (q^{\ell-1})^{K-i} p^{K-i}\\
&=\sum_{i=1}^{K-1} {K \choose i} (1-q^{\ell-1})^i \left[q^{\ell-1} p\right]^{K-i}\\
&=\left[1-q^{\ell-1}+q^{\ell-1} p\right]^K-(1-q^{\ell-1})^K
\end{align*}
This gives you the distribution of $L$.
As a checkup, you can run the following code
T=10^6
N=13
p=.85
ell=rep(1,T)
for (t in 1:T){
  x=rbinom(1,N,p)
  while (x<N){ ell[t]=ell[t]+1; x=x+rbinom(1,N-x,p)}}

and compare the frequencies with
probel=function(N,p,el){
 (1-(1-p)^(el-1)+p*(1-p)^(el-1))^N-(1-(1-p)^(el-1))^N}

Comment: Sorry for my bad English... I meant I am very grateful :D
Comment: Thank you for showing me so much insight of this r.v.'s distribution. I am still working for the moment generating function. With your help, I am able to continue my study. And your hint is very inspiring. I am very appriciated. ^_^

multi stage binomial "process"


Efficiently calculating totals from a file using LINQ

Question: I'm reading a file and turning each line within it into a class, let's call it Record, and returning each Record as it is read using IEnumerable<Record> and yield return.
Because of this I only start actually performing these reads whenever I do an operation on the enumeration, such as performing a sum on it or iterating through it with a foreach.
I do need to go through each record and then translate that into a database, but due to database design before my time I need the totals on each record in the database, so I need these totals before I start translating them into my database.
At the moment I have five separate .Count() or .Sum() operations on my enumeration before I start iterating the enumeration (example int i = records.Sum(r => r.SomeField) or int j = records.Count(r => r.IsSomethingTrue)). Each one of those counts or sums will loop through the entire file to calculate each one separately. I'm not really happy with this behaviour and would like to find a more efficient way of doing this.
I am using .NET 3.5 if that makes any difference.
Comment: Have you considered a stored procedure?
Comment: The totals are from a file, not from the database.
Answer: You could use your own struct to calculate a few values at the single pass through an enumerable object.
public struct ComplexAccumulator
{
    public int TotalSumField { get; set; }

    public int CountSomethingTrue { get; set; }
}

Now you can use Aggreagate extension method to accumulate values:
records.Aggregate(default(ComplexAccumulator), (a, r) => new ComplexAccumulator
{
    TotalSumFiled = a.TotalSumField + r.SumField,
    CountSomethingTrue = a.CountSomethingTrue + r.IsSomethingTrue ? 1 : 0,
});

Instead of the struct you could use suitable Tuple instance, f.e. something like Tuple<int, int, int>.
Comment: I was thinking Aggregate was the right thing to use but I wasn't sure how, I'll give this a shot, thanks.
Answer: Efficiency is not a strength of LINQ... You need to replace some LINQ things with manual loops here.
You seem to need two passes over the data. One for aggregation:
var sum = 0; //etc.
foreach (var item in items) {
 //compute all 5 aggregates here
}

And then one to translate the data:
items.Select(item => Translate(item, aggregates))

Whether you should buffer items (for example using ToList) or not depends on whether available memory can hold those items or not.
You can use Aggregate to perform all 5 aggregations in one pass but that's not better than a loop in any way. It's slower, far more code and the code arguably is illegible.
Comment: Is Aggregate that slow? You make a good point about legibility though.
Comment: @Logan slow is relative. It's 2 vcalls and one delegate call per iteration. The JIT does nothing to make this fast. All very indirect code. It depends on how slow your aggregation is. If it is just 5 additions then you can easily loose 2-3x compared to a loop. The old JIT and RyuJIT are appealingly bad with struct handling as well. Expect many loads and stores to memory. No register use.
Comment: Yeah, I don't know if the volumes I'm dealing with will take much of a hit on this, but I'm trying to account for growth as well (which is why I'm not just throwing everything into memory and working from that). I guess the loop is the better option purely from the readability standpoint. Thanks.
Comment: @Logan yeah, it's just so simple. If you want to make this an expression like an Aggregate call is (and a loop is not) then you can put it into a function.


"sock_sendmsg-error 22" error in RHEL

Question: I am using RHEL 5.10 servers ( which are in cluster using some shared services). When I restart them using "init 6" or "reboot". the servers hang while shutting down, continuously showing the below message:
sock_sendmsg-error 22

I've to get in the ilO cli mode and do a power reset after which the servers again restart properly. I don't see any significant error in /var/log/messages after that. Can someone expalin what the error means. Is it some problem with kernel level sockets. ?
Answer: 22 will be a standard errno value. These are defined in a series of (many) C-language include headers starting with errno.h. I find the easiest way of looking these up is with a tool such as cscope. In any case, on most Linux machines, 22 is the value corresponding to EINVAL, which has the standard rendering of "invalid argument".
#define EINVAL          22      /* Invalid argument */
"/usr/include/asm-generic/errno-base.h"

Since we know this to be related to the sendmsg system-call, we can look up the manual page for sendmsg(2), which just tells us that an invalid argument was passed to it, perhaps because something didn't handle an error gracefully. This can also bubble up from other error, such as when the mount command is mounting a CIFS network share and there is an error such as invalid credentials. In cases such as this, the true error may be found in the kernel log (dmesg).
I'm not sure what system component would be reporting that error though. Hopefully you'll see it in the logs also?

"sock_sendmsg-error 22" error in RHEL


Can I plug my amp directly into my audio interface?

Question: Could anyone tell me, can I plug my guitar amp directly into my audio interface (with the "line out")?
On some forums people say that you can't , on others people say you can...
If it's possible, is there things you shouldn't do to avoid any damage to the interface? (I saw somewhere you had to have the loudspeakers hooked up when you are recording... why is that ?)
Answer: If the output jack is labeled line out it means it can be plugged into any line-level input, as those found in audio interfaces, so you should be safe.
If your interface is "pro" grade, it can have Mic inputs and "Hi-Z" (or Instrument) inputs too, so check if it's the case and make sure you plug into the line inputs.
Also, keep in mind that unless the "line out" has speaker emulation (and a good one, too!), you probably won't like the sound you'll get.
As for the speaker, it should always be connectd (expecially if it's a tube amplifier) unless you wanna risk damaging the amp. Amplifier transformers need the correct load to work properly and within safe parameters.
If the volume is too much for where you're playing (and that's why you're asking about the speaker connection), you can buy an attenuator, which gives you lower volume while keeping the right load on the amplifier transformers.
Some models have an emulated line out which is usually better than the stock one if you want to use it for recordings.
Comment: If line out doesn't have speaker simulation you can use the simulator of your choosing, from basic eq'ing to free VSTs to extremely expensive premium VSTs. OTOH, if it does, it probably sucks and you are stuck with a crappy sound. I had better results by clumsily miking up my VOX Valvetronix with a $9 computer mic (in fact I got a nice sound) than I had with its, ugh, "line out".
Answer: If your amp has  a "line out" or headphones jack, then you should be able to connect that to the audio interface.  Note that usually this means that the output is low impedendence, and the amount of pre amp gain that you'll need is lower than you'd need for plugging the guitar straight in (the amplifier is providing some initial amplification).
The same holds true for the output (send) from an effects loop, the signal has been pre amplified to (approximately) line level.  Note that you would need to complete the loop in this case; basically I'm saying that you should be able to put the interface into an effects loop. If I were doing this though,
I'd start the pre-amp gain as low as possible before plugging into the interface, since this is not commonly done.
However do not plug speaker output(s) into the inputs of an audio interface -- this will surely break the amp or the interface (or both).
Comment: "However do not plug speaker output(s) into the inputs of an audio interface -- this will surely break the amp or the interface (or both)." Man, i did this one night, maybe i was luck, but my gear is fine to this day, however no one should try this at home! hahaha
Answer: You can but the sound will not be quite the same as if you record the sound of the amp with a microphone, you are loosing all the amp characteristics like, the sound of the cabinet, the extrusion of the speaker and even perhaps the feedback it gives to the guitar (like when you put your guitar close to the amp to cause an intentional feedback loop),  but you can do it and always is a good choice if you don't want or can put a mic in front of it. Even if it only have headphone out can be done although its not the most optimal option.


How to implement cross/nested random effects in lme4?

Question: I am trying to examine "homophily" in school students. That is, I am examining whether pairwise similarity in various traits correlates with closeness in social networks.
Each row of my spreadsheet contains data for following columns: child_1_id, child_2_id, social closeness of child_1_id and child_2_id, pairwise similarity in trait of interest of child_1_id and child_2_id. This repeats for all pairwise combinations of children. The simplest form of my model is therefore the following:
trait similarity ~ social closeness + (1 | child_1_id) + (1 | child_2_id)

However, multiple classrooms were included in the study. I would therefore like to nest within classrooms. Importantly, trait similarity and social closeness were only calculated for children in the same classroom as each other, and therefore child_1 and child_2 are always from the same classroom.
How do I go about nesting the crossed random effects for child id within a term for classroom?
Answer: I think you can just add a random effect (1|classroom) to your model, provided your IDs for children are uniquely coded (i.e. your children are coded 1 .. n_children rather than 1 ... n_1, 1 ... n_2, 1 ... n_3, ... where n_i is the number of children in the ith classroom)
If children were not uniquely coded you could use a random effect of the form (1|classroom) + (1|family:child_1_id) + (1|family:child_2_d)


Nested parameter expansion: Why is ${foo%"$bar"} legal, but ${$bar} not?

Question: I'll start with the two motivating examples, to give proper context for the question, and then ask the question.  First consider this example:
$ ext=.mp3
$ fname=file.mp3
$ echo ${fname%"$ext"}
file

Evidently, in parsing ${fname%"$ext"}, bash first expands $ext into .mp3, and then expands ${fname%.mp3} into file — the last step follows trivially from the definition of % expansions.  What's confusing me is the expansion of $ext...
In particular, let's compare the above with this similar example:
$ a=value
$ b=a
$ echo ${$b}
-bash: ${$b}: bad substitution

Of course, I know I could use "indirect expansion" here to achieve what I want:
$ echo ${!b}
value

But that's not relevant to my question.  I want to understand the specific bash evaluation and parsing rules that explain why ${$b} fails but ${fname%"$ext"} succeeds.
The only relevant passage I've found in man bash is this:

The order of expansions is: brace expansion; tilde expansion, parameter and variable expansion, arithmetic expansion, and command substitution (done in a left-to-right fashion); word splitting; and pathname expansion.

But I'm not seeing how the different behaviors result from these rules.
I'd like see an explanation that explains each step of the evaluation process of the two examples, and the rule underlying each step.
Answer: If you look up ${parameter%word} expansion in the bash manual you'll see that parameter and word are treated differently. word is subject to pathname expansion while parameter is not.

${parameter%word}
${parameter%%word}

Remove matching suffix pattern. The word is expanded to produce a
  pattern just as in pathname expansion. If the pattern matches a
  trailing portion of the expanded value of parameter, then the result
  of the expansion is the expanded value of parameter with the shortest
  matching pattern (the % case) or the longest matching pattern (the
  %% case) deleted. If parameter is @ or *, the pattern removal
  operation is applied to each positional parameter in turn, and the
  expansion is the resultant list. If parameter is an array variable
  subscripted with @ or *, the pattern removal operation is applied to
  each member of the array in turn, and the expansion is the resultant
  list.

That seems like it would explain it. But it doesn't. Pathname expansion only means globbing and pattern matching with *, ?, and the like. It doesn't include variable expansion.
The key is to read up. There's a preamble that applies to the above:

In each of the cases below, word is subject to tilde expansion, parameter expansion, command substitution, and arithmetic expansion.

In totality, word is subject to all of these expansions. Key to this question: $ext is expanded via recursive parameter expansion.
I say "recursive" because it can in fact be nested arbitrarily deep. To wit:
$ echo ${fname%.mp3}
file
$ echo ${fname%"$ext"}
file
$ echo ${fname%"${ext%"$empty"}"}
file
$ echo ${fname%"${ext%"${empty%""}"}"}
file

Comment: No, I don't. I don't know why `${$name}` isn't allowed. My guess is it's a consequence of history and I don't know much about how shell syntax evolved over time. Pure speculation: since `%` is a newer feature perhaps the shell designers were free to do fancy things, whereas they were constrained by history (the POSIX standard?) on the left-hand side.
Comment: Excellent answer!  So the recursion is the exception rather than the rule -- a special feature limited to a few specific sub-cases of parameter expansion.  Any idea why this is the case (ie, the design considerations motivating this)?


Como ativar o autofocus com jquery numa div?

Question: Como ativar o autofocus com jquery numa div? Quero fazer um autofocus em um input assim que o usuário fizer  tal ação...
Comment: QUE DELICIAAAAAAAAAAAAAAAAAAAAAAAAA VALEUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUU
Comment: O autofoco seria para dar foco ao carregar a página. Se é após uma ação, basta você dar o foco no campo fazendo [`$("seu campo").focus()`](https://api.jquery.com/focus/)
Comment: Como complemento ao que já foi respondido pelo @AndersonCarlosWoss e ainda que não focando a tag, pode fazer o mesmo só com html utilizando o atributo `autofocus`, que irá funcionar como o focus quando abre a página.
Answer: Basta você utilizar a função focus do jQuery quando você deseja dar o foco no campo. Por exemplo, dar o foco em um campo de texto ao clicar no botão:

$(() => {
  $("#btn").on("click", event => {
    $("#nome").focus();
    console.log("O campo está em foco.");
  });
});

<input id="nome" type="text">
<button id="btn">Foco</button>


mouseover event propagation issue - Manually propagate

Question: I am implementing an User Interface for a project I'm working on and can be found here : Toobrok
Each time the mouse of the user enters a div, a class is added to this div to highlight it, I use the stopPropagation() method to restrict the highlighting to the div whose z-index is higher (the top div in the z axis).
However, sometimes, my user needs to select an element hidden by another one, when the dimensions of the 2 elements are different, and if the bottom div is larger, he can find some points of the bottom div not hidden by the top one, but when the dimensions are the same, I would like the user to be able to press a key to change the depth (on the z-axis) of his selection.
The relevant code is given below (in CoffeeScript), but a javascript solution would also help me:
Ui.bind = (elements, index) ->
  ids = Ui.getIdSelector(elements)
  $(ids).attr("centroid", index)
  $(ids).mouseover (event) ->
    event.stopPropagation()
    Ui.highlight $(ids)
  $(ids).mouseout (event) ->
    event.stopPropagation()
    Ui.resetHighlight $(ids)

I hope the question is clear and looking forward to your answer.
This is an example of HTML to consider :
<!DOCTYPE html>

    <title> Sample page </title>

Some text...

  </body

And the related css :
#container {
  height: 200px;
  width: 500px;
}

#child1 {
  height: 90%;
  width: 90%;
}

When the mouse enters the child1 element, this element is highlighted, I want the container element to highlight when the user press a specific key.
I could use the JQuery parent() function to select that element on this example, but I am not sure it is a good solution, sometimes, the parent can have a size of 0px and and then a mouseover on this element would not be consistent. I want to select the element normally selected by Javascript if I do not use the stopPropagation() event.
I actually just found something that might help :
How to undo event.stopPropagation in jQuery?
But I cannot use that in my case... Because my condition is another user action, and I cannot synchronously wait for an user to do something.
Comment: Correct if I'm wrong, but you want to change z-index on key press? And can you please provide some css and html?
Comment: I don't want to change the z-index of a div on keypress but to change the z-index of the mouseovered element (Changing may not be the correct verb because if the z-index is the same, I still want to go from one div to another)
I did not provide any HTML or CSS because this code has been written to write on unknown webpages. But I will try to write an example
Comment: Maybe you can increase z-index for some value on mouse in and decrease it for same value on mouse out.
Comment: Let me make sure I understand:
1. You currently highlight an element on mouseover, and de-highlight it on mouseout.
2. There can be overlapping elements, so you want to allow someone to press a key so that it will highlight a different element
3. Your code is meant to run on unknown webpages, where the parent element may have size 0 (i.e. just a placeholder for structure purposes) and therefore should *not* be selected

Did I understand you correctly?
Comment: You perfectly understood ! The javascript propagation does not take into account placeholder elements, I think, and I want to do the same, the mouseover reacts on several elements and I want to manually decide which one should received the fired event.
Comment: @Oxynum: Since it's the children overlapping, propagation is not your problem. Propagation works to parents, not overlapping items. The solution by Artem sounds as the correct approach.
Answer: I started writing code but then decided to leave implementation to you. Here is the text explanation:

At some point of time (probably when user press button to cycle through all hovered elements) you have to find all candidates for highlighting. There is no other way to do it rather than manually loop through all your elements and check if mouse position is inside their bound rect. You can get mouse coordinates from argument in mouseover callback. Save all these hovered elements in some array.
Next, you have to manually choose which element to highlight. Just highlight the first element in saved array and move the element to the end of array. You also may want to increase this element z-index and add callback for mouseout to this element.

Hope it helps, feel free to ask if you need more details.
Comment: It helps, I guess I have to record all the elements in an array and loop through them. I'm gonna try that approach soon and tell you how it goes.
Comment: @Oxynum hey bro, friendly reminder about expiring bounty
Answer: You could use the CSS property pointer-events to make the child insensitive. Then events will be targeted to the element displayed below. For simple highlighting you should use pure CSS, however, jQuery can be helpful not to highlight the parent element as well while child is hovered without Ctrl.
Some example (also uploaded to JSFiddle, click into the output pane to make it responsive for keyboard events):

Some text...

div { border:1px dashed red; } /* for demo */

.container
{ height: 200px;
  width: 500px;
}

.child
{ height: 90%;
  width: 90%;
}

.insensitive
{ pointer-events:none;
}

.container:hover:not(.no-hilight),
.child:hover
{ background-color:yellow;
}

/* other color for demo */
.child:hover{ background-color:green; }

// make events passthrough child when <Ctrl> is held down
$(document).on('keydown keyup', function(ev) {
    if (ev.key === 'Control') // for performance
        $('.child')[ev.ctrlKey?'addClass':'removeClass']('insensitive');
});

// don't hilight container when child is hovered
$('.child').on('mouseover', function(ev)
{
  $('.container').addClass('no-hilight');
});

// never suppress hilight when container is hovered directly
$('.container').on('mouseover', function(ev)
{ if(ev.target === ev.currentTarget)
    $('.container').removeClass('no-hilight');
});

// just test which element a click is targeted to
$(document).on('click', function(ev)
{ console.log('click:', ev.target);
});

Comment: Using CSS to force propagation was novel for me.  In my context, I was using Recharts Label components, but their Tooltip implementation doesn't hook to attached Labels, so the tooltips weren't opening when hovering the Label overlapping the Scatter point.  Adding `pointer-events: none` to the Label `style` prop completely addressed the issue.
Comment: @bsplosion It's not a propagation force but a kind of "event transparency". It is as the so styled element wasn't there.
Answer: var preId = 0;
function makeBlack(id)
{
    if(id)
    {
        $('#'+id).css('border-color','black');
    }
}
function makered(id)
{
    $('#'+id).css('border-color','red');
}
$(document).ready(function(){

$('div').mouseout(function() {
    var currentid = this.id;
    makeBlack(currentid);
    preId = currentid;

});
$('div').mouseleave(function() {
    var currentid = this.id;
    makeBlack(currentid);
    preId = currentid;

});
$('div').mouseover(function() {
    var currentid = this.id;
    makeBlack(currentid);
    makered(preId);
    preId = currentid;

});
$('div').mouseenter(function() {
    var currentid = this.id;
    makered(currentid);
    preId = currentid;
});

});
Comment: I do not think you understood the question, it does not solve my problem.
Answer: Have you tried something like this for the CSS?
#container.hover{
  height: 200px;
  width: 500px;
  //add a background-color to that element since its a div element
  //background-color: (colour)
}

i should hope that the div element would automatically highlight the container div with whichever color you have selected


Optimal Stopping Theory: Secretary problem with recall, known n, 100% chance of solicting success.

Question: I'm trying to find an optimal item in a list. Evaluating these items is very time-consuming, and I want to go fast. I know how many items there are, and I can choose one at any time.
Given some threshold d in (0, 1], how can I calculate how many items I have to evaluate such that the best item already evaluated is the best with probability > d?
Can this bound be changed if I use a very fast heuristic to order items from "probably good" to "probably not good"?
A paper or book discussing this in detail would be great.
Answer: Assuming candidates arrive in a random order then $\lceil dn \rceil$, i.e. rounding up $dn$, seems an obvious answer since the probability the best is in the first $\lceil dn \rceil$ is $$\dfrac{\lceil dn \rceil}{n} \ge d$$
with equality if $dn$ is an integer. If you want strict inequality then $\lfloor dn \rfloor +1$
Comment: Well, don't I feel silly now. The thought even briefly flared up as I typed the question, but after close to an hour of searching, I guess my brain refused this simple answer and convinced itself, there would be a more complicated stochastical method behind it. Of course, you are right. Thanks.


How to move "description" below the "label" for a field in a form?

Question: Can I user form_alter to move move "description" below the "label" for a field in a form?
Let´s say I want to move the "description" of the "body" field for the basic page content type.
Answer: Have a look at Label help module. It just creates a second help field that will appear directly below the form element's label.
It is a simple way to turn around the problem.
Or try something like
jQuery(document).ready(function ($) {

  // move the help text from below the input field to directly below the field label

  $('.form-item .description').each(function () {  // description is the help text
    var desc = $(this);
    var label = desc.siblings('label:first');
     if (label.length) {
       desc.insertAfter(label);
     }
  })
  // the help text is tangled up in the text format stuff on a filtered text field
  $('.text-format-wrapper .description').each(function () {
    var desc = $(this);
    var label = desc.siblings('.form-item').find('label:first');
     if (label.length) {
        desc.insertAfter(label);
     }
  })
});
(thanks to El bandito !)
Comment: Even when I could do it in the other way, the http://drupal.org/project/label_help does the job.
Answer: Drupal 7
The module Form element layout solves this both at API level and through the Field settings UI.
As a developer you would use the FAPI attribute #description_display and set it before if you want it between the #title and #children, i.e. after the label and before the input element(s):
$form['example'] = array(
  '#type' => 'textfield',
  '#title' => t("Example input"),
  '#description' => t("Example description of what this element does."),
  '#description_display' => 'before',
);

And as a site builder you would just configure your field settings and toggle the description position.
Note: This module will use replacement themes for various parts of Drupal that renders #title and #description, so if your theme already has overridden some of these, they won't "take" anymore and you will have to override the themes provided by Form element layout instead.
Drupal 8
At API level this is already possible using the same FAPI attribute as above, #description_display. In addition to the values before and after it also supports invisible, just like #title_display.
Field UI wise, we're still waiting for issue #2318757.
Answer: You can't move it, but you can always work around things in Drupal.
A hook_form_alter() or better hook_form_FORM_ID_alter() (for a specific form) would be needed to solve your problem.
Inside the form alter, you can use the following code to place the description in different positions. The example is just for the body field, but you can apply the same logic to other fields as well.
// Get the language of the field
$lang = $form['body']['#language'];
// Check if a description exists
if (!empty($form['body'][$lang][0]['#description'])) {
  $body_field = &$form['body'][$lang][0];

  // Create new description markup and delete the default description
  $description = '
'. $body_field['#description'] .'
';
  $body_field['#description'] = '';

  // Place description before the field (between label and field)
  $body_field['#field_prefix'] = empty($body_field['#field_prefix'])
                                 ? $description
                                 : $description . $body_field['#field_prefix'];
}

And of course, you'll need to add the proper CSS for the new description markup.
Answer: Welcome to the debate. it has been going on for some time.
Check out this discussion for D8: Make position of #description configurable and this: Form Field Description should be between Label and Field. This will give you a perspective on the 5 years I have been watching this. The former has patches to address this, but that means hacking core, unless you wish to create a contributed module. There also seem to be options for moving the description using template.php.
I will leave it to you to join these discussions, and make a decision.
Comment: I see there are a lot of words in this subject. I'll take a look at it. Thanks.
Answer: This can be done with hook_form_alter() and #field_prefix. For example, we can take the description of the body field for the basic page content type, and move it directly below the label:
/**
 * Implements hook_form_alter().
 */
function my_module_form_alter(&$form, &$form_state, &$form_id) {
  if ($form_id == 'page_node_form') {
    // Move the body's description below the label.
    $language = $form['body']['#language'];
    $form['body'][$language][0]['#field_prefix'] = $form['body'][$language][0]['#description'];
    $form['body'][$language][0]['#description'] = '';
  }
}

Comment: I copied this code into a custom module and it does not work very good unless I remove the line $language = $form['body']['#language']; and remove this in de form structure. Is there a general way to do this for all fields?
Comment: I'd recommend using `dpm()` or xDebug to inspect the `$form` object, that way you can identify when/where/if there is a default language for the entire form. Although considered bad practice, if you know your language code is always `und`, then you can use that in place of `$language`.
Answer: Here's a generic way using jQuery
'.form-group p.help-block'

is the child element is the text you want to move.
'.form-group label'

is the parent element - this where you want to put the text.
This will move each child element within it's own parent element.
Works for any elements you want to move.
$('.form-group p.help-block').each(function() {
    $(this).insertAfter($(this).parent().find('.form-group label'));

Answer: This isn't a very Drupally solution, but it was an easy front-end fix.  Styles were designed to work with the Olivero 9.5.2 theme.  It uses jQuery to move the elements around in the DOM after the page has been loaded (for text fields and fieldgroups so far)
This moves the descriptions up under the labels:
$=jQuery; // lazy hack to keep from typing 'jQuery' repeatedly

// Move the field descriptions just below the label
$(".form-item .form-item__description").each(function(){
  $(this).insertAfter($(this).closest('.form-item').find(".form-item__label:first"));
});

// Move fieldset descriptions to the top of the fieldset contents
$('.fieldset').each(function(){
   $(this).find('.fieldset__description').prependTo($(this).find('.fieldset__wrapper'));
});

Style to taste.  I moved the help text and field labels together to flow better with this CSS:    /* Fieldgroup label */
.fieldset__description {
background-color: #ddd;
}
/* Fieldgroup Help Text */
.fieldset__description {
    /* margin-top: 0.5625rem; */
    margin-bottom: 0.5625rem;
    font-size: 0.8125rem;
    /* line-height: 1.125rem; */
    padding: 0.1rem 1.25rem;
    margin: -1.1rem -1.1rem auto -1.1rem;
    border-radius: 0 0 0.5rem 0.5rem;
}

/* Form Field Labels */
.form-item__label {
    background-color: #5d7585;
    color: #fff;
    padding: 0 10px;
}

/* Form Field Help Text */
.form-item__description {
    max-width: none;
    background-color: #eee;
    padding: 0.5rem;
    border-radius: 0 0 1rem 1rem;
    margin-top: -0.55rem;
}

This ends up giving a display like this:


How can I set env vars when using webpack?

Question: I'm using nvm, webpack and yarn to run a React app locally (not a create-react-app app). When I attempt to use environment variables in the terminal session, they are not picked up by the node process.
Steps taken:
In a single terminal session:

export FOO=bar
yarn start
(in app, console.log(process.env.FOO))
result = FOO is undefined
Answer: Figured it out! Added this to the webpack config file:
    plugins: [
      new webpack.EnvironmentPlugin(['FOO']),
    ],

make sure you have exported the var in the same terminal you will use to run yarn...
export FOO=bar

then you will be able to access it within your app as process.env.FOO
Docs are here:
https://webpack.js.org/plugins/environment-plugin/


R: How to create a function from a model?

Question: I am using an automatic model selection procedure, "step". The model of depart (the biggest possible) is a polynom, say of the 4th degree.
Depart<-lm(y~x+I(x^2)+I(x^3)+I(x^4))

Final<-step(Depart)

I need to transform the Final model to a corresponding function. How can i do this?
Answer: Do you mean something like this:
f<-function(newdata)predict(Final,data.frame(x=newdata))
?
Comment: @Roah Did you try the answer? Because that's exactly what it will give you (you won't see the coefficients, but why do you care about the internals of the function?
Comment: No, i wish to construct a function of one variable. Something like "ff<-function(x) 3.23+2.78x-3.45x^4".
Comment: @Roah - Could you explain in what way the function I suggested does not do what you expect? It certainly accepts scalars so you can call it with a single value. Is the return value not what you are expecting?
Comment: Sorry, aix! I was too bothered by the internal structure of the algorithm... And it is very simple! Thanks a lot, because i was going to parse the output...


System.Web.Mvc.SelectListItem cannot be used as a parameter value

Question: I am using mvc 5 for which i am problem in insertion for dropdownlist selected list
My View:

    @Html.LabelFor(m => m.NatureofLeave, new { @class = "control-label col-sm-6" })

        @Html.DropDownListFor(m => m.NatureofLeave, ViewBag.EmployeeLeave as IEnumerable<SelectListItem>, "-Select-")
        @Html.ValidationMessageFor(m => m.NatureofLeave, "", new { @style = "color:red;" })

My Model:
[Display(Name = "Type of Leave")]
public List<SelectListItem> NatureofLeave { get; set; }

My Controller:
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult Leaves(EmployeeLeave objEmpLeave)
{
    objEmpLeave.NatureofLeave = BindDataFromDatabaseToLeave();

    var selectitem = objEmpLeave.NatureofLeave.Find(p => p.Value == objEmpLeave.NatureId.ToString());

    if (selectitem != null)
    {
        selectitem.Selected = true;
        ViewBag.Message = "NatureofLeave " + selectitem.Text;
    }
    if (string.IsNullOrEmpty(objEmpLeave.StartDate.ToString()))
    {
        ModelState.AddModelError("Error", "Please provide start date");
    }
    else if (string.IsNullOrEmpty(objEmpLeave.EndDate.ToString()))
    {
        ModelState.AddModelError("Error", "End Date is calculated by startdate... So, make sure start date is not empty!");
    }
    else if (string.IsNullOrEmpty(objEmpLeave.NatureofLeave.ToString()))
    {
        ModelState.AddModelError("Error", "Select one");
    }
    else if (string.IsNullOrEmpty(objEmpLeave.Reason))
    {
        ModelState.AddModelError("Error", "Reason cannot be empty");
    }

    else
    {
        objEmpLeave.UserId = Convert.ToInt32(Session["userId"]);
        objEmpLeave.UserName = Convert.ToString(Session["name"]);

        int leaveID = objIAccountData.InsertLeave(objEmpLeave);

        if (leaveID > 0)
        {
            TempData["msg"] = "";
        }

        else
        {
            TempData["msg"] = "";
        }
    }
    return View(objEmpLeave);
}

I am using Dapper ORM so i will give you the repository.
My Repository:
using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["MyString"].ToString()))
{
    var param = new DynamicParameters();
    param.Add("@UserId", objEmployeeLeave.UserId);
    param.Add("@UserName", objEmployeeLeave.UserName);
    param.Add("@StartDate", objEmployeeLeave.StartDate);
    param.Add("@EndDate", objEmployeeLeave.EndDate);
    param.Add("@LeavesAvailed", objEmployeeLeave.LeavesAvailed);
    param.Add("@NatureofLeave", objEmployeeLeave.NatureofLeave);
    param.Add("@Reason", objEmployeeLeave.Reason);

    param.Add("@UserIdOut", dbType: DbType.Int32, direction: ParameterDirection.Output);

    con.Open();
    con.Execute("sprocInsertLeaves", param, null, 0, CommandType.StoredProcedure);
    int UserIdOut = param.Get<int>("UserIdOut");
    con.Close();
    return UserIdOut;
}

Actually, the problem is in the repository located at the dropdownlist
param.Add("@NatureofLeave", objEmployeeLeave.NatureofLeave);
So, anyone can solve this problem....
Thanks in advance
Comment: `List` is a collection, so that you may need iterate through to get its text/value first (only recognized `struct`-based value types & `string` allowed to use as parameter value).
Comment: You view code makes no sense. A `` posts back a single value (it cannot be bound to a `List)`. Your `NatureofLeave` property needs to be `int` or `string` or whatever the type is that you use for the option values.
Comment: @Stephen Muecke, Hello sir, can it possible to have int or string for a dropdownlist.... Can you explain me
Comment: Of course (and it needs to be). The `IEnumerable` property is for the 2nd parameter of the `DropDownListFor()` method - i.e. the the property which displays the options (which in your case is `ViewBag.EmployeeLeave`)
Comment: @Stephen Muecke, I can;t understand sir
Comment: Sorry I Can't..
Answer: Based on my understanding
First you need to fill the NatureofLeave not the EmployeeLeave
Second in case you have Model in the page you need no ViewBag
Third you are not filling the ViewBag with EmployeeLeave
This Code:
return View(objEmpLeave);

is filling the model and not the ViewBag
why not to use below if you are declaring the model at the TOP of the View Page since the Model would be EmployeeLeave:
@Html.DropDownListFor(m => m.NatureofLeave, Model.NatureofLeave, "-Select-")

Here better to Use:
ConfigurationManager.ConnectionStrings["MyString"].ConnectionString

Since you are using:
using (SqlConnection con =
new SqlConnection(
ConfigurationManager.ConnectionStrings["MyString"].ToString()))

No need at all to:
con.Close();

since dispose will close and clean since dispose is calling close inside it
Last Thing it's recommended to:
Try not to use ViewBag unless you are forced to
For inserting Multiple Data:
Read how to work with Tables Relation One (Named Parent) => To Many (Named Child)
To Insert In Parent Then Another Command to Insert in Child


discord.py trying to set up a moderation log channel

Question: So I'm trying to set up a log channel where it will post a message in that whenever someone gets kicked. At the moment I'm storing it in a json file, but i cant get it tow work. Does anyone have the code? Here's mine:
with open('log_channels.json', 'r') as f:
      log_channels = json.load(f)

@client.command()
@commands.has_permissions(administrator = True)
async def modlog(ctx, channel = None):
  log_channels[str(ctx.guild.id)] = channel.split()
  with open('log_channels.json', 'w') as f:
    json.dump(log_channels, f)
  await ctx.send(f'Mod log set to {channel}')

@client.command()
@commands.has_permissions(kick_members = True)
async def kick(ctx, member : discord.Member, *, reason = None):
 await member.kick(reason = reason)
 await ctx.send(embed=discord.Embed(title=f'{member} has been kicked.', color= 0xFF8633))
 guild = ctx.guild
 log_channels.get((guild.id) ('0'))
 print (log_channels)
 channel = client.get_channel(log_channels)
 await channel.send(f"test")

Comment: What do you mean by you can't get it to work, what happens? any errors?
Comment: Yeah, discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: 'int' object is not callable
Comment: And what line does it print for, you should provide the whole traceback in the question itself. btw read https://stackoverflow.com/help/how-to-ask
Answer: Your error comes from this line:
log_channels.get((guild.id) ('0'))

And more precisely, from (guild.id) ('0'), which is equivalent to 123456789012345678('0') and is impossible.
What you probably meant to do is this:
@client.command()
@commands.has_permissions(kick_members = True)
async def kick(ctx, member : discord.Member, *, reason = None):
    await member.kick(reason = reason)
    await ctx.send(embed=discord.Embed(title=f'{member} has been kicked.', color= 0xFF8633))

    channel_id = log_channels.get(str(ctx.guild.id), '0')
    channel = client.get_channel(channel_id)

    await channel.send(f"test")

NB: json dict keys must be strings, so you need to get str(ctx.guild.id).
Also, if log_channel equals '0', channel will be None and channel.send() will raise an error.
What I would recommend doing is this:
@client.command()
@commands.has_permissions(kick_members = True)
async def kick(ctx, member : discord.Member, *, reason = None):
    await member.kick(reason = reason)
    await ctx.send(embed=discord.Embed(title=f'{member} has been kicked.', color= 0xFF8633))

    if str(ctx.guild.id) in logs_channels:
        channel = client.get_channel(log_channels[str(ctx.guild.id)])
        await channel.send(f"test")
    else:
        # Not mandatory, you can remove the else statement if you want
        print('No log channel')

Comment: It came up with the error: discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: unhashable type: 'list'. Would there be something wrong with how I stored the json data?
Comment: Could you include your json file structure in your question?
Comment: Why would `log_channels[str(ctx.guild.id)]` be a list? Do you have multiple log channels?
Comment: Do you know how to remove symbols from a number value?


My Ibanez TMB100 sounds input cut in and out and fuzzes

Question: For some reason after not playing my Ibanez TMB100 bass, the sound cuts on and off most especially playing the lower strings. I checked the jack cable but with a different one it doesn't fix anything.
Could it be the 9V battery? I bought it a few months ago and it was all working fine since yesterday. No drop or shock whatsoever.
It's having the same issue with a little Orange Amp and even more so with an iRig HD2 connected to my mac.
Video with sound
Answer: If you've left the jack in, the battery is probably below 9v, and it might have been borderline before. Worth replacing, and also use switch cleaner when plugging in all the jacks to their sockets. Move the jacks in and out a good few times, as dirty contacts will cause such effects.
Comment: Good! Just remember to unplug the bass after every session! And keep a 9v battery in the bass case, just in case, for next time..
Comment: that was definitely that! Works fine now. Thank you again!
Comment: Eureka, that makes total sense as sometimes it's left in! Probably not wise though. Thanks for this enlightening. I'll replace the 9V battery tomorrow and see if it fixes it.
Answer: I guess you might have a loose contact somewhere in there, and the vibrations caused by the low strings are just enough to occasionally let you loose contact. You might try to remove the pickguard and to carefully look if there is a loose solder connection somewhere, or if moving any of the cable causes that problem. You might also try if tapping or shaking the bass with some force does also cause this problem.


Showing $\pi(ax)/\pi(bx) \sim a/b$ as $x \to \infty$

Question: I'm having a bit of a problem with exercise 4.12 in Apostol's "Introduction to Analytic Number Theory". I don't think it's supposed to be a very hard exercise, it's the first one in its section (they're usually a bit like warm-ups). I'm supposed to show that

If $a>0$ and $b>0$, then $\pi(ax)/\pi(bx) \sim a/b$ as $x \to \infty$.

It also says I'm allowed to use the prime number theorem. Is it just something like (a rough sketch):
$$\frac{\pi(ax)}{\pi(bx)} \sim \frac{ax \log bx}{bx \log ax} \sim \frac{a}{b}, \quad \text{since the logs $\to 1$ as $x \to \infty$?}$$
I don't know, maybe I'm heading in the wrong direction... It would be very nice if someone could show me how to do this properly!
Comment: Looks good to me, although instead of saying "the logs go to 1" I would say the ratio of the logs goes to 1.
Comment: @Gerry: Oh, ok, I thought I was a long way from being done! Thanks!
Answer: All you're missing is the use of $\text{log}(bx) = \text{log}(b) + \text{log}(x)$, as the fraction then ~$\frac{ax\text{log}(x)}{bx\text{log}(x)}$ ~ $\frac{a}{b}$.
Answer: You have $\frac{ax \log bx}{bx \log ax} = \frac ab \frac{\log x+\log b}{\log x+\log a}$.
Since $\log x\to\infty$, you have
$$\lim\limits_{x\to\infty} \frac{\log x+\log b}{\log x+\log a}=1.$$
(The constants $\log a$ and $\log b$ are "small" compared to $\log x$.)
Comment: Of course! Thank you!
Answer: It might be interesting to note that the initial statement is what guarantees that the fractions of the form $p/q$ with $p,q$ primes, form a dense subset of $ [0,\infty).$


gem --version different to sudo gem --version :(

Question: I'm a bit of a Linux noob trying to get ruby, rails, mysql and sqlite all playing nicely on ubuntu 10. I am getting errors, and I realized that the versions are different for sudo versus normal user!
mpw@ubuntu:~/.rvm/gems/ruby-1.9.2-p0$ gem --version
1.3.7
mpw@ubuntu:~/.rvm/gems/ruby-1.9.2-p0$ sudo gem --version
1.3.5

I have used RVM to install it, but it seems that I have conflicting versions. How to fix?
Comment: One of the nice things about RVM is that you will most likely *never* need to run gem as the root user, as all your gems are installed within `~/.rvm`.
Comment: I recommend reading the first two entries in the RVM FAQ: http://rvm.beginrescueend.com/support/faq/
Answer: sudo gem --version most likely is using the system gem i.e the one you get when you do rvm system. This is because sudo changes user to root and you probably didn't do sudo rvm use 1.9.2 or something similar. Try doing sudo which gem and which gem to confirm this.
You can update the version used by root by doing sudo gem update --system. However note that you are still most likley using different gem paths when using sudo gem and gem if you are not using the system gem executable by default i.e rvm use system.
Answer: I did the same installation mistake before, but following these instructions worked. http://ascarter.net/2010/05/10/rails-development-on-ubuntu-10.04.html
Comment: Speaking from experience, it's better to just use RVM and save yourself all the trouble with the Ubuntu packages. Chances are you'd want to run several versions of Ruby anyway, some of them more up-to-date than the ones in the Ubuntu repos.
Answer: Please try a
sudo which gem

resp
which gem

to get the information which gem you are using.
I second the opinion of the answer above that most probably you are using different gem versions and paths.


Calculating Residues using L'Hopital?

Question: I am given that the complex function $$f(z)=\frac{(e^{z-1}-1)(\cos(z)-1)}{z^3(z-1)^2}$$ has 2 simple poles, one at $z=0$ and another at $z=1$, and asked to calculate the Residues of the function at the singularities. I know that the residue of a pole $z_0$ of $f(z)$ with order $n$ is given by the formula $\frac{1}{(n-1)!}\lim_{z\rightarrow z_0}(z-z_0)^nf(z)$ and that sometimes using L'Hopital's rule is necessary to calculate the values, however, with the poles in this equation, using L'Hopital's rule seems to make it more difficult.
So far, I've done the following:
$$\text{Res}(f,0)=\lim_{z\rightarrow 0}zf(z)=\lim_{z\rightarrow 0}\frac{(e^{z-1}-1)(\cos(z)-1)}{z^2(z-1)^2}=\lim_{z\rightarrow 0}\frac{(e^{z-1}-1)}{(z-1)^2}\cdot \lim_{z\rightarrow 0}\frac{\cos(z)-1}{z^2}\\=(e^{-1}-1)\lim_{z\rightarrow 0}\frac{\cos(z)-1}{z^2}.$$
From here, I'm not sure how to continue. I checked the answer according to the mark scheme and from this step, the marker jumps to $\text{Res}(f,0)=(e^{-1}-1)\cdot(\frac{-1}{2})$. I can't see where the $\frac{-1}{2}$ has come from.
This happens in a similar way with the residue at $z=1$.
$$\text{Res}(f,1)=\lim_{z\rightarrow 1}(z-1)f(z)=\lim_{z\rightarrow 1}\frac{(e^{z-1}-1)(\cos(z)-1)}{z^3(z-1)}=\lim_{z\rightarrow 1}\frac{e^{z-1}-1}{z-1}\cdot\lim_{z\rightarrow 1}\frac{\cos(z)-1}{z^2}\\=(\cos(1) -1)\cdot\lim_{z\rightarrow 1}\frac{e^{z-1}-1}{z-1}.$$
Again, the marker jumps from this step to $Res(f,1)=(\cos(1)-1))\cdot 1$.
If anyone can help me see how to go from my working out to the answer, that would be much appreciated.
Thank you.
Comment: Your calculations for the residue of $f$ are wrong. You are not applying the formula you presented, and it is not correct either. Another option is using series expansion.
Answer: Hint. Once that we note that both poles are of order $1$ (simple poles) then your computations are correct. What you need now is that
$$\cos(z)=1-\frac{z^2}{2}+o(z^2)\quad\mbox{and}\quad e^{z-1}=1+(z-1)+o(z-1).$$
Or equivalently, by L'Hopital's rule,
$$\lim_{z\rightarrow 0}\frac{\cos(z)-1}{z^2}=\lim_{z\rightarrow 0}\frac{-\sin(z)}{2z}=\lim_{z\rightarrow 0}\frac{-\cos(z)}{2}=-\frac{1}{2}
\quad\mbox{and}\quad\lim_{z\rightarrow 1}\frac{e^{z-1}-1}{z-1}=\lim_{z\rightarrow 1}\frac{e^{z-1}}{1}=1.$$
Comment: I'm not familiar with the $o(z)$ notation. Can you elaborate further about what you mean by it?
Comment: Ah I see what I was doing now. Thank you for your help!
Answer: Hint: If $f$ has a simple pole at $a,$ then
$$\text { Res }(f,a) = \lim_{z\to a}(z-a)f(z).$$
In our case, at $0,$ we have
$$\text { Res }(f,0) = \lim_{z\to 0}zf(z) = \lim_{z\to 0}\frac{(e^{z-1}-1)(\cos z-1)}{z^2(z-1)^2} = \frac{e^{-1}-1}{1^2}\lim_{z\to 0}\frac{\cos z-1}{z^2}.$$
That last limit should look familiar from good old calculus.

Calculating Residues using L'Hopital?


with or without 'return' in javascript

Question: I am solving a leetcode question. But I realized 'return' can make different output. The first code was accepted but the second one is not accepted.
function canJump(nums){
  let reachable = 0;

  for(let i=0; i < nums.length; i++){
    if(reachable < i) return false;
    reachable = Math.max(reachable, i + nums[i]);
  }
  return true;

function canJump(nums){
  let reachable = 0;

  for(let i=0; i < nums.length; i++){
    if(reachable < i) false;
    reachable = Math.max(reachable, i + nums[i]);
  }
  return true;

what is exactly the role of return in the javascript, and why does it make different output?
Comment: `return` stops the execution of a function and optionally *return*s a value - actually it always *return*s a value; but `return` === `return undefined` [documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/return)
Comment: What is the expected behavior of `if(reachable < i) false;`? Why did you write it there? Are you trying to learn a programming language by guessing without a text book? That won't work.
Answer: if(reachable < i) return false;
Your function canJump returns false if your condition  reachable < i is true, meaning this code
reachable = Math.max(reachable, i + nums[i]);
does not get executed
Where in the second case
if(reachable < i) false;  you simple print false to the console or you are tying to I am assuming
Comment: `if(reachable < i) false;` doesn't print anything.
Comment: if my condition is true, it means the updating reachable value is running
`var canJump = function(nums) {
  let reachable = 0;

  for(let i = 0; i < nums.length; i++){
    if(reachable < i){
      return false;
    } else {
      reachable = Math.max(reachable, i + nums[i]);
    }
  }
  return true;
};`

cuz this looks like this actually

with or without 'return' in javascript


Python interpreters uses up to 130% of my CPU. How is that possible?

Question: I am currently doing some I/O intensive load-testing using python. All my program does is to send HTTP requests as fast as possible to my target server.
To manage this, I use up to 20 threads as I'm essentially bound to I/O and remote server limitations.
According to 'top', CPython uses a peak of 130% CPU on my dual core computer.
How is that possible ? I thought the GIL prevented this ? Or is it the way Linux 'counts' the resources consumed by each applications ?
Comment: I don't know about python, but I've certainly frequently seen the linux System Monitor reporting CPU usage of > 100%, all the way up to 180%. No idea why however.
Comment: The GIL is released on I/O calls.
Comment: I know the total 'available percentage' is 100*'Core count'. So that > 100% implies that your application runs on multiple cores. But I did not knew that the GIL was released on I/O tasks. Still, I did not know HTTP lib was multithreaded.
Answer: 100 percent in top refer to a single core.  On a dual-core machine, you have up to 200 per cent available.
A single single-threaded process can only make use of a single core, so it is limited to 100 percent.  Since your process has several threads, nothing is stopping it from making use of both cores.
The GIL only prevents pure-Python code from being executed concurrently.  Many library calls (including most I/O stuff) release the GIL, so no problem here as well.  Contrary to much of the FUD on the internet, the GIL rarely reduces real-world performance, and if it does, there are usually better solutions to the problem than using threads.
Comment: You're mixing up processors and cores!
Comment: Isn't that a very odd way of defining the CPU usage percentage? Any idea how this works with hyperthreading? My computer has 4 hyperthreaded cores, but I never see a reported usage percentage above ~180%.
Comment: With the differences in AMD/Intel Cores/Processors, superscalar, hyperthreading, Linux threads/processes, Windows threads/processes and scheduling. I challenge anyone to keep track of exactly 'how concurrent will my code be?'
Answer: That is possible in situations when used C-extension library call releases GIL and does some further processing in the background.
Answer: If you find this irritating, set your preferences (specifically, the preferences of your System Monitor or equivalent tool) to enable "Solaris Mode," which calculates CPU% as a proportion of total processing power, not the proportion of a single core's processing power.
Comment: It's not. I was wondering how python could use more than one core at a time but this was because I misunderstood the role of the GIL.