List of all active modules used in a site

Question: Is there a way of having a list of all the used (active) modules on a site?
I am in the process of documenting a site and I would like to list all the active modules. I know I can take them from admin/modules, but there must be another way.
Answer: You can use drush pm-list --type=Module --status=enabled command for getting a list of all installed modules.
If you want to exclude the core modules use drush pm-list --type=Module --no-core   --status=enabled
Comment: As mentionned [on a related post](https://drupal.stackexchange.com/a/83725/85848) you may list all of them for a multi-site environment with **@sites** by doing `drush @sites pml --no-core --type=module --status="enabled" -y` and filter on say some_module using grep ` | grep some_module`
Comment: In case you only need the machinne_names without formating (may be usefull for scripting purpose..) you can use the --field option like so:

drush pm-list --type=Module --no-core --status=enabled --field name
Answer: The two options I use are Drush and a custom script.
For Drush, you can use drush pm-list:
$ drush help pm-list
Show a list of available extensions (modules and themes).

Options:
 --type                                    Filter by extension type. Choices:
                                           module, theme.
 --status                                  Filter by extension status. Choices:
                                           enabled, disable and/or 'not
                                           installed'. You can use multiple
                                           comma separated values. (i.e.
                                           --status="disabled,not installed").
 --package                                 Filter by project packages. You can
                                           use multiple comma separated values.
                                           (i.e. --package="Core -
                                           required,Other").
 --core                                    Filter out extensions that are not
                                           in drupal core.
 --no-core                                 Filter out extensions that are
                                           provided by drupal core.
 --pipe                                    Returns a space delimited list of
                                           the names of the resulting
                                           extensions.

Aliases: pml

I also wrote this script for Drupal 6.  You need to edit the bootstrap for Drupal 7, and you may also want to tweak the path checking.  I put this in a file called modules.php in my DOCROOT and add access restriction around it to prevent it from being called from the wild.
<?php
include_once './includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
header('Content-Type: text/plain');

$files = drupal_system_listing('/\.module$/', 'modules', 'name', 0);

system_get_files_database($files, 'module');

ksort($files);

$core_installed = array();
$core_enabled = array();
$core_disabled = array();

$contrib_installed = array();
$contrib_enabled = array();
$contrib_disabled = array();

foreach ($files as $info) {
  $filename = $info->filename;
  $name = $info->name;
  $status = $info->status;

  $contrib = strpos($filename, "sites/all/modules/") === 0;

  if ($contrib) {
    $contrib_installed[] = $name;
    if ($status) $contrib_enabled[] = $name;
    else $contrib_disabled[] = $name;
  } else {
    $core_installed[] = $name;
    if ($status) $core_enabled[] = $name;
    else $core_disabled[] = $name;
  }
}

print "Installed Core Modules: " . join(", ", $core_installed) . "\n\n";
print "Enabled Core Modules: " . join(", ", $core_enabled) . "\n\n";
print "Disabled Core Modules: " . join(", ", $core_disabled) . "\n\n";

print "Installed Contrib Modules: " . join(", ", $contrib_installed) . "\n\n";
print "Enabled Contrib Modules: " . join(", ", $contrib_enabled) . "\n\n";
print "Disabled Contrib Modules: " . join(", ", $contrib_disabled) . "\n\n";

This script can be called with drush using: drush scr modules.php
Answer: The Enabled Modules (enabled_modules) module provides lists of all enabled modules on a website.
Or,
You can use this API function module_list to get all enabled modules.
Answer: Yes, check the Module Filter module: It's excellent administrator helper that makes managing modules much easier.

The modules list page can become quite big when dealing with a fairly large site or even just a dev site meant for testing new and various modules being considered. What this module aims to accomplish is the ability to quickly find the module you are looking for without having to rely on the browsers search feature which more times than not shows you the module name in the 'Required by' or 'Depends on' sections of the various modules or even some other location on the page like a menu item.
When tabs is enabled via the Module Filter's settings page, a new module layout theme is implemented. This tab layout provides a tab for each package as well as a tab that will show every module alphabetically. The filter textfield is available on each tab but currently doesn't support autocomplete.
Answer: The simplest way I've found is a database query you could put in a custom module or Drush script to output it in a format you want.
$enabled_modules = db_query("SELECT name FROM {system} WHERE type = 'module' AND status = 1")->fetchCol('name'); print implode("\n", $enabled_modules);
Answer: Drush make has a primitive makefile generation capability. To use it, simply change your directory to the Drupal installation from which you would like to generate the file, and run the following command:
drush generate-makefile /path/to/make-file.make
You get make-file.make with a list of modules. Then you can load these modules in other project. Read http://www.drush.org/en/master/make/#usage
Answer: If you don't have commandline access to run drush, you might be looking for something you can do from the Web UI.  The best solution I could find was browsing to the Modules page and then running this command in the console:
jQuery('table.sticky-enabled input[checked=checked]')
  .closest('tr')
  .find('td label strong')
  .each(function() {
    console.log(jQuery(this).text());
})

This will print all the enabled modules in the console, where you can copy paste them anywhere you'd like.
Answer: Install and enable the Forena module (disclosure I'm a co-maintainer). Users with role "administrator" will then be able to navigate to the delivered (sample) report located at reports/drupaladmin.enabled_contributions, which will give you the list this question is about.
Here is how the specification (.FRX file, an XHTML document) to create the report looks like:
<?xml version="1.0"?>
<!DOCTYPE root [
<!ENTITY nbsp " ">
]>

<title>Enabled Modules and Themes</title>
<frx:category>Drupal Administration</frx:category>
<frx:options hidden="0" />
<frx:parameters>
</frx:parameters>
<frx:docgen>
</frx:docgen>

          name
          owner
          weight

          {name}
          {owner}
          {weight}

And here is how the data block (SQL statement) referred to in the report looks like:
--ACCESS=access administration pages
SELECT name, owner, weight FROM {system}
WHERE status=1 AND 'module'=type
ORDER BY name

That's really "it".
PS: feel free to tune (adapt) the .FRX file and/or the data block to fit your own needs.
Comment: `AND 'module'=type`?! Should be `AND type = 'module'`
Comment: @ajmedway you're probably right, why not "suggest an edit"? I'd be happy to approve it ...
Comment: It's not a big deal I suppose - the clause works. It's just not conventional to have the column name on the right-hand side of the expression with the value on the left.
Answer: <?php
$files = system_rebuild_module_data();
$modules_list = [];

foreach ($files as $filename => $file) {
  // Hidden modules and Themes will be excluded.
  if (!empty($file->info['hidden']) || $file->type != 'module') {
    continue;
  }

  // Get module type.
  $type = 'Contrib';
  if ($file->info['package'] == 'Core') {
    $type = 'Core';
  }
  elseif (strpos($file->uri, "sites/all/modules/custom/") !== false) {
    $type = 'Custom';
  }

  // Check module installed or not.
  if ($file->status) {
    $modules_list[$type]['installed'][] = $file->name;
  }
  else {
    $modules_list[$type]['disabled'][] = $file->name;
  }

}

foreach ($modules_list as $type => $module_info) {
  print $type . " Modules:\n\n";
  print "Enabled " . $type . " Modules: " . count($module_info['installed']) . "\n\n";
  print "Disabled " . $type . " Modules: " . count($module_info['disabled']) . "\n\n";
}

The above code will help to get the modules installed in Drupal 7 website.
Answer: For those without drush: go to modules page, with module filter enabled (not absolutely necessary, but good for formatting).
Then show source page, copy modules html inside "<"table>" to "<"/table>. Paste into gedit, wrap some html around it (html, body), and you'll have a html page, including indication of unused/disabled modules (showing check box unchecked) which can be important when rebuilding a site (insofar as the disabled modules might be needed, or can be installed -> uninstalled for the sake of cleaning up the database)
Answer: Schema module is one option while Views can do the trick too although without the additional Views System module, which i found buggy, you dont get version numbers.
Comment: The OP needs the list of the enabled modules, not their schema version.


Hit count/ number of page visits in D7

Question: How to implement a hit counter for all 'Article' type nodes? I want to display number of times (could be unique) a node was visited - perhaps within the teaser and at the bottom of the node.
Answer: In Drupal, you already have that module. You just need to activate Statistic module and set the rights permissions to anonymous users. And maybe you might modify your node.tpl.php to show count information.
Also, this module provides you blocks that show the most viewed nodes in the day, all the time or right now.

Hit count/ number of page visits in D7


How to update header text in hook_views_pre_render

Question: I have a view with a header of type "Global: Unfiltered text" that contains the string "Number of drivers: ".
In hook_views_pre_render I count the total number of drivers in each row, and now I want to append this number to the string in my view header.
I did a print_r on the $view object in hook_views_pre_render and found 59 instances of that string.
If it was only a few I would just try replacing each one until it had the desired result - but 59?!?! Too much recursion...
So how do I find which value to update in order to update the text in my view header?
Answer: Well the important thing is to narrow down the particular view display you want to affect. Then you can look at the header text later. I have the following similiar code ... you should be able to use views_pre_render fine, I don't use that here:
function MYMODULE_views_post_execute(&$view) {
  if ($view->name == 'migration_audits') {
    $drupal_nids = array();
    if (count($view->result)) {
      foreach ($view->result as $i => $node) {
        $drupal_nids []= $node->nid;
      }
    }
   $sql = " ... ";
   $result = db_query($sql, array(':drupal_nids' => $drupal_nids));
    $output = '';
    foreach ($result as $course) {
      #dpm($course);
      $title = html_entity_decode($course->course_title, ENT_COMPAT, 'UTF-8');
      $instructors = html_entity_decode($course->instructor, ENT_COMPAT, 'UTF-8');
      $output .= "
$course->quarter $course->year - $title Instructors: $instructors
";
    }

    $my_values = "
$output
";
    $view->display['page']->handler->handlers['header']['area_1']->options['content'] = $my_values;
    $view->display['page']->handler->handlers['header']['area_1']->options['empty'] = 0;
  }
}

You can also do like $view->display[$view->current_display] usually as a safe none hard coded approach. Note that the global header regions are given names such as area_1, area_2 etc as a convention by Views. I also tell Views the area is now not empty.
Comment: I was unable to update the header value using  $view->display['page']->handler->handlers['header']['area_1']->options['content'] = $my_values; this code


Find whether one mean is very different from all others in multiple measurements

Question: I have many data frames like the one reproduced below in R. I am trying to find cases where one group only is very different from the other groups (I have a variable number of groups for the different data frames). I have tried with ANOVA, but this test only tells me if the group means are different from each other, and almost all are, but what I am looking for is either a test or a measure that can point to whether each individual with one measure per group varies a lot by one group more than the others, some kind of across individual variability. Maybe I can try with repeated measures ANOVA with unbalanced data (I have missing values)? Is this the right way to do this?
<code>df = structure(list(groups = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L), .Label = c("group1", "group2", "group3"), class = "factor"), individuals = structure(c(1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L, 11L, 12L, 13L, 14L, 15L, 16L, 17L, 18L, 19L, 20L, 21L, 22L, 23L, 24L, 25L, 26L, 27L, 28L, 29L, 30L, 31L, 32L, 33L, 34L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L, 11L, 12L, 13L, 14L, 15L, 16L, 17L, 18L, 19L, 20L, 21L, 22L, 23L, 24L, 25L, 26L, 27L, 28L, 29L, 30L, 31L, 32L, 33L, 34L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L, 11L, 12L, 13L, 14L, 15L, 16L, 17L, 18L, 19L, 20L, 21L, 22L, 23L, 24L, 25L, 26L, 27L, 28L, 29L, 30L, 31L, 32L, 33L, 34L), .Label = c("sample1", "sample2", "sample3", "sample4", "sample5", "sample6", "sample7", "sample8", "sample9", "sample10", "sample11", "sample12", "sample13", "sample14", "sample15", "sample16", "sample17", "sample18", "sample19", "sample20", "sample21", "sample22", "sample23", "sample24", "sample25", "sample26", "sample27", "sample28", "sample29", "sample30", "sample31", "sample32", "sample33", "sample34"), class = "factor"), value = c(0, 0.126889234269648, 0.0568617212177722, 0.0655431535336275, 0, 0, 0.0567384158931187, 0.0109376655462734, 0, 0.0948086895930572, 0, 0, 0.0824709304159648, 0, 0, 0, 0, 0, 0.033917835818341, 0.0198035710833954, 0.133552284941515, 0.0664567537955113, 0.0430308231270825, 0.0160783942164045, 0.0738182676544177, 0.120422772617204, 0.135233112827437, 0.0860623347815552, 0.0200020675534846, 0, 0.0973088048201884, 0, 0, 0.038283321330165, 0.225376778959931, 0.137536577951645, 0.426342384989027, 0, 0.337720200488891, 0.384254666977513, 0.0108438100713879, 0.278754009620225, 0.381097277894091, 0.154981762820021, 0.0864810371628134, 0.218313535529244, 0.202077489447883, 0.117036020922844, 0.129779767219537, 0, 0.559959304303877, 0.240102470306958, 0.252798090888197, 0.100823988780093, 0.126391112137011, 0.108138613814024, 0.0692924355684719, 0.459841817208745, 0.138288519068394, 0.113182370152051, 0.0525657185927877, 0.177169361598713, 0.355934492361351, 0.186605323013182, 0.148750791970728, 0, 0.155418848968847, 0.0600295032575727, 0.774623221040069, 0.735574187778708, 0.5167958937932, 0.934456846466373, 0.662279799511109, 0.615745333022487, 0.932417774035493, 0.710308324833502, 0.618902722105909, 0.750209547586922, 0.913518962837187, 0.781686464470756, 0.715451580136152, 0.882963979077156, 0.870220232780463, 1, 0.440040695696123, 0.759897529693041, 0.713284073293462, 0.879372440136512, 0.740056602921473, 0.825404632390465, 0.887676741304446, 0.524079788574851, 0.787893213277188, 0.766394857230745, 0.812201168579775, 0.736768303619732, 0.624063440085165, 0.813394676986818, 0.720479745676339, 1, 0.786220846027069, 0.901687175412262)), .Names = c("groups", "individuals", "value"), row.names = c(2L, 6L, 10L, 14L, 18L, 22L, 26L, 30L, 34L, 38L, 42L, 46L, 50L, 54L, 58L, 62L, 66L, 70L, 74L, 78L, 82L, 86L, 90L, 94L, 98L, 102L, 106L, 110L, 114L, 118L, 122L, 126L, 130L, 134L, 1L, 5L, 9L, 13L, 17L, 21L, 25L, 29L, 33L, 37L, 41L, 45L, 49L, 53L, 57L, 61L, 65L, 69L, 73L, 77L, 81L, 85L, 89L, 93L, 97L, 101L, 105L, 109L, 113L, 117L, 121L, 125L, 129L, 133L, 3L, 7L, 11L, 15L, 19L, 23L, 27L, 31L, 35L, 39L, 43L, 47L, 51L, 55L, 59L, 63L, 67L, 71L, 75L, 79L, 83L, 87L, 91L, 95L, 99L, 103L, 107L, 111L, 115L, 119L, 123L, 127L, 131L, 135L), class = "data.frame")
</code>
Any help is very much appreciated!
Thanks in advance,
Francesca
Comment: Could you clarify:  "...whether each individual with one measure per group varies a lot by one group more than the others, some kind of across individual variability."
Comment: Hi Rolando, sorry for the unclear statement, I would like to know whether there is one group mean that is significantly different from the others, something like what Joshua suggested but I don't think this works because I need to account for the repeated measurements on the same individuals and I cannot assume a linear model (so I can't use ANOVA and neither mixed models).  If I just use this TukeyHSD(aov(value~groups, data=df)) the p-values are significant for group2 against 3, which is not what the plot shows: plot(value ~ groups, data=df)..
Answer: Check out post-hoc comparisons (Tukey's HSD is one): http://www.statmethods.net/stats/anova.html
Comment: Thanks very much Joshua, I didn't know about the Turkey's HSD method, but it is not working with either of the ANOVA approaches I am trying probably because I am confused about the initial ANOVA model.. If I use this: TukeyHSD(aov(value~groups*individuals, data=df)) I get all NaN, or if I use this: TukeyHSD(aov(value~groups+Error(individuals/groups)), data=df) I get an erorr message.. Am I missing something in the ANOVA model maybe? thanks v much for your help!


If $\vert{z_{1}+ \cdots + z_{n}}\vert$ = $\vert{z_{1}}\vert + \cdots + \vert{z_{n}}\vert$ then $z_{j} = c_{j}z_{1}$

Question: Could someone give me just one suggestion to solve this problem?

Let $z_{1}, \ldots z_{n} \in \mathbb{C}$, with $z_{1}\neq 0$. Prove that if
  $\vert{z_{1}+ \cdots + z_{n}}\vert$ =
  $\vert{z_{1}}\vert + \cdots  + \vert{z_{n}}\vert$ then $z_{j} = c_{j}z_{1}$, where
  $c_{j}\geqslant 0 $, $j=1,\ldots n $
Comment: Induction? Have you tried it?
Comment: You're right, sometimes I forget that usually this type of problem is solved by induction, thanks :)
Answer: Using  $|z|^2 = z z^*$ we have
$$
\vert{z_{1}+ \cdots + z_{n}}\vert^2 = (z_{1}+ \cdots + z_{n})(z_{1}^*+ \cdots + z_{n}^*) \\
= \sum_{i} |z_{i}|^2 +   \sum_{i > j} (z_i z_j^* +z_j z_i^* )\\
= \sum_{i} |z_{i}|^2 +  2 \sum_{i > j} \Re (z_i z_j^*) = \sum_{i} |z_{i}|^2 +  2 \sum_{i > j} |z_i||z_j| \cos(\phi_i - \phi_j)
$$
which must, according to the question, be equal to
$$
(\vert{z_{1}}\vert + \cdots + \vert{z_{n}}\vert)^2 = \sum_{i} |z_{i}|^2 +  2 \sum_{i > j} |z_i||z_j|
$$
Since all terms in the second expression are positive and since $\cos(\phi_i - \phi_j) \le 1$, we must have  $\phi_i = \phi_j$ for all $(i,j)$. Hence all $z_j$ must have the same phase angle.  This is equivalent to  saying $z_{j} = c_{j}z_{1}$ with real positive constants $c_{j}$.
Comment: Wow, what an elegant solution !, thank you very much.
Answer: Here's the base case.
If
$|(a+bi)+(c+di)|
=|a+bi|+|c+di|
$
then,
$\sqrt{(a+c)^2+(b+d)^2}
=\sqrt{a^2+b^2}+\sqrt{c^2+d^2}
$.
Squaring,
$(a+c)^2+(b+d)^2
=a^2+b^2+c^2+d^2+2\sqrt{(a^2+b^2)(c^2+d^2)}
$
or
$2ac+2bd
=2\sqrt{(a^2+b^2)(c^2+d^2)}
$.
Dividing by 2
and squaring again,
$a^2c^2+2abcd+b^2d^2
=a^2c^2+a^2d^2+b^2c^2+b^2d^2
$
or
$0
=a^2d^2+b^2c^2-2abcd
=(ad-bc)^2
$
so
$ad=bc$.
Now it becomes the cases
depending on
which, if any,
of $b$ abd $d$ are zero.
If $b\ne 0, d\ne 0$,
then
$a/b = c/d$.
Letting
$r = a/b$,
then
$a = rb, c = rd$
so
$a+ib
=b(r+i)
$
and
$c+id
= d(r+i)
$
so
$c+id
= (d/b)b(r+i)
=(d/b)(a+ib)
$.
I'll let you work out the
other cases.
Comment: I'm sure. There are a few ways to do this, and I just wanted to come up with a very elementary one.
Answer: Let $P(n)$ mean that the result if true for $\le n$ variables. $P(1)$ is clear.
It is straightforward to show that $|1+w| = 1+|w|$ iff $w\ge 0$.
For $P(2)$, if $z_1 \neq 0$ then $|1+ {z_2 \over z_1}| = 1+ | {z_2 \over z_1}|$ and hence $P(2)$ is true by the preceding remark.
Suppose $P(n)$ is true and $|z_1+z_2+\cdots+ z_n + z_{n+1}| = |z_1|+ |z_2|+ \cdots + |z_n| + |z_{n+1}|$.
If $z_1 \neq 0$ we can divide through to get
$|1+ {z_2 \over z_1}+\cdots + {z_{n+1} \over z_1}| = 1+ |{z_2 \over z_1}|+\cdots + |{z_{n+1} \over z_1}|$.
To reduce clutter let $w_k = {z_k \over z_1}$.
Since
$|1+w_2+\cdots+  w_{n+1}| \le 1 + |w_2+\cdots+ w_{n+1}| \le 1 + |w_2| + \cdots + |w_{n+1}|$ we have
$|w_2+\cdots+ w_{n+1}| = |w_2| + \cdots + |w_{n+1}|$ from which we
see that $P(n+1)$ is true.


Convert a LAN port to WAN port

Question: I have D-Link DIR-600M N-Modem. A day ago the WAN port got damaged due to lightning but the other ports still work. I can connect to the modem but the WAN port does not respond.
Is there any way I can configure one of the LAN port out of the 4 switch ports to work as WAN port?
My I.P provider provides a static IP address. I also use the modem as a WiFi hotspot.
Answer: No, you can't
The WAN port on that device is a routed port.  It can have a different network address than your LAN network address and the LAN traffic would be routed through the WAN port to get to your ISP.
Unfortunately there are no Layer 3 ports on your switch side of the router.
You asked.

Is there any way I can configure one of the LAN port out of the 4 ports to work as WAN port?

No, there is not a way to configure one of your LAN switch port as a WAN port for your device.

Convert a LAN port to WAN port


How to determine the cause for "BUS-Error"

Question: I'm working on a variscite board with a yocto distribution and python 2.7.3.
I get sometimes a Bus error message from the python interpreter.
My program runs normally at least some hours or days before the error ocours.
But when I get it once, I get it directly when I try to restart my program.
I have to reboot before the system works again.
My program uses only a serial port, a bit usb communication and some tcp sockets.
I can switch to another hardware and get the same problems.
I also used the python selftest with
python -c "from test import testall"
And I get errors for these two tests

test_getattr (test.test_builtin.BuiltinTest) ... ERROR test_nameprep
  (test.test_codecs.NameprepTest) ... ERROR

And the selftest stops always at

test_callback_register_double (ctypes.test.test_callbacks.SampleCallbacksTestCase) ... Segmentation
  fault

But when the systems runs some hours the selftests stops earlier at

ctypes.macholib.dyld
  Bus error

I checked the RAM with memtester, it seems to be okay.
How I can find the cause for the problems?
Comment: Usually a bus error on modern systems running linux come from attempting to perform unaligned memory access. Which *usually* happens when a C programmer thinks they're being clever by casting some arbitrary pointer to a larger than `char` type, e.g. being lazy about serializing/deserializing to/from a file or socket read/write buffer.  Is your entire program actually written in Python, or is Python just being used as a test framework?  Can you just attach a debugger to the process and backtrace when you hit the bus error?
Comment: memtester was a good idea, but you may want to check kernel messages (`dmesg`). Last (and first) time I get a "bus error" a couple of weeks ago was while running some git commands, but it may have been anything since the root cause was clearly my hard drive dying as kernel traces showed, so I'd say this may be your flash as well.
Answer: Bus errors are generally caused by applications trying to access memory that hardware cannot physically address. In your case there is a segmentation fault which may cause dereferencing a bad pointer or something similar which leads to accessing a memory address which physically is not addressable. I'd start by root causing the segmentation fault first as the bus error is the secondary symptom.
Answer: A year later I found the indirect cause for the problems.
I wrote a crc16 module which used:
from ctypes import c_ushort
...
value = c_ushort(crcValue >>8 ) ...

In case of a BUS-Error this was the problematic part.
I don't assume that the c_ushort() function itself causes the problem, it's only the function which shows that there is something broken.
The problem gone after upgrading the system to Linux version 3.14.38-6QP+g8740b9f (test@Yocto) (gcc version 4.9.2 (GCC) )


JavaScript average of values inside an array

Question: The JSON:
[{"id":"1","user":"001","answer":"1,1,3,2,2,1,3,2"},
{"id":"2","user":"002","answer":"2,3,3,2,1,1,3,2"},
{"id":"3","user":"003","answer":"3,5,3,5,3,1,3,2"}]

The JavaScript:
jQuery.ajax({
    url: "file.json",
    type: "POST",
    dataType: "json",
    async: false,
    success: function (data) {
    var arr = [];
    for (i = 0; i < data.length; i++) {
        arr.push(data[i].answer);
    }
    console.log(arr);
});

What I'm trying to do is make an average of each value from the 3 answers, which in case will give these 8 averages:
2,3,3,3,2,1,3,2

Comment: How are you trying? Can we see an attempt?
Comment: I'd consider showing that code in your post very useful. It doesn't need to be correct, but it shows you really have tried something, and also most likely makes the goal more clear. Unless I haven't misunderstood your question, some answerers seem to have, despite of some very beautiful code in answers.
Comment: The reason you're getting numbers like this `["123","123456","123456789"]` is that you're adding strings, so they add like characters next to each other. To add them mathematically as values, you need to convert them to numbers first.
Comment: I was making a split, with an each, and putting in array again, which was returning in front, not over numbers like ["123","123456","123456789"]. I dont considered useful posting this :/
Comment: Can you share input and output?
Comment: I am trying to keep the average of 8 values splitted, just like is in the question.  All the answers are really awesome but their average is showing only 3 value, as average of them. I really did not sleep tonight.
Comment: That was not clear from your original question. See my updated answer for how to calculate the average of each value from all answers (8 averages) instead of the average of the values of each answer (3 averages).
Comment: Thank you very much @RacilHilan !
Answer:

const arrAvg = arr => arr.reduce((a,b) => a + b, 0) / arr.length;
console.log(arrAvg([1,2,3,4,5]));
Answer: You may use:

Array.prototype.map()
Array.prototype.reduce()
String.prototype.split()
Arrow functions

Working Example:

let data = [{"id":"1","user":"001","answer":"1,1,3,2,2,1,3,2"},
            {"id":"2","user":"002","answer":"2,3,3,2,1,1,3,2"},
            {"id":"3","user":"003","answer":"3,5,3,5,3,1,3,2"}];

let result = data.map(o => {
  /* Split the string into array using , delimiter */
  let a = o["answer"].split(",");
  /*
   * Return average of array by first creating sum using .reduce() and
   * then dividing by number of array elements.
   */
  return a.reduce((a,c) => (Number(c) + a), 0) / a.length;
});

console.log(result);
Answer: create a new array from the answer then sum all the values and divide by its size

var res = [{
    "id": "1",
    "user": "001",
    "answer": "1,1,3,2,2,1,3,2"
  },
  {
    "id": "2",
    "user": "002",
    "answer": "2,3,3,2,1,1,3,2"
  },
  {
    "id": "3",
    "user": "003",
    "answer": "3,5,3,5,3,1,3,2"
  }
];
res.forEach(function(item) {
  //creating array from the string
  var imtArray = item.answer.split(',');
  //summing the element
  var avg = imtArray.reduce(function(p, q) {
    // converting string to number
    return +p + +q
  })
  console.log(avg / imtArray.length)

})
Answer: You're getting the answer, but now you need to split it by commas and parse it to a number. This gives you an array for each answer, now you can simply iterate through each one and add the numbers then divide them by their count  (i.e. array length) to calculate the average.
Note: the values in the answers are strings, so make sure you convert them to numbers before you add them together, otherwise you will be adding them together as characters.

var data = [{"id":"1","user":"001","answer":"1,1,3,2,2,1,3,2"},
            {"id":"2","user":"002","answer":"2,3,3,2,1,1,3,2"},
            {"id":"3","user":"003","answer":"3,5,3,5,3,1,3,2"}]

var arr = [];
for (var i = 0; i < data.length; i++) {
  var d = data[i].answer.split(",");
  var sum = 0;
  for (var j = 0; j < d.length; j++) {
    sum += parseInt(d[j]);
  }
  arr.push(sum / d.length);
}
console.log(arr);

It seems from your comments that instead of the average of values in each of the three answers, you actually want the average of each value from the three answers. Similar to the code above, you just need to make a little change. You'll have to iterate and add the values of each answer first, then iterate again and calculate the averages:

var data = [{"id":"1","user":"001","answer":"1,1,3,2,2,1,3,2"},
            {"id":"2","user":"002","answer":"2,3,3,2,1,1,3,2"},
            {"id":"3","user":"003","answer":"3,5,3,5,3,1,3,2"}]

var arr = [];
for (var i = 0; i < data.length; i++) {
  var d = data[i].answer.split(",");
  for (var j = 0; j < d.length; j++) {
    d[j] = parseInt(d[j]);
  }
  if (arr.length == 0)
    arr = d;
  else {
    for (var j = 0; j < d.length; j++) {
      arr[j] += d[j];
    }
  }
}
for (var i = 0; i < arr.length; i++) {
  arr[i] = arr[i] / data.length;
}
console.log(arr);

Note: This assumes that each answer has the exact same number of values.
Comment: Serious, thank you very much! I was losing my hair and my health to this. God bless you!
Comment: This is a really unnecessarily complicated answer for something made in 2018. It also gives a lot of bad practices such as using `var`
Comment: @Treycos What does 2018 have anything to do with the answer? The answer was based on the question. If you feel that it was "unnecessarily complicated" and you have a better answer, why don't you post it instead of downvoting a correct and accepted answer almost a year later. And since when was using `var` a bad practice? There is nothing wrong with `var` if used correctly.
Comment: This answer is written using JavaScript practices from more than 5 years ago. Why would voting be based on the date the answer was posted ? Using `var` is an extremely bad practice to adopt when starting to code in JS because they aren't respecting any scope and are equivalent of global variables no matter where they are declared in your code. Also, the variables names make the code unreadable. Yes, I do have a better answer, the one right below, a few lines, easily readable, clear, this is the correct answer. If you do care about developers starting out with JS, I recommend deleting yours.
Comment: @Treycos Did you notice that the answer below was posted a few minutes before mine, yet was not the accepted answer? There was a reason. Sometimes the shortest answer is not the correct one for the question because it could be a homework and the teacher wants the students to learn the basics, like loops and conditions. Your comment about globals and `var` is too general. We know when to use them and when not. Again, the answer was based on the question, so understand before you comment. It's not a generic answer or a guide on how to code. There is a detailed explanation to learn from.


Expectation of joint distribution of uniform random variables

Question: Can you provide an example of a joint distribution of $X,Y$ exchangeable random variables for which $\operatorname{E}[X/Y]<\infty$ with $X,Y\sim U(0,1)$ and $P(X=Y)=0$.
I've tried to find one but i think that $\operatorname{E}[X/Y]$ exists only if $P(X=Y)=1$ otherwise the integral diverges and the expectation does not exist.
Comment: If one drops the requirement of exchangeability, then this does it:
$$\begin{align}
X \sim {} &\operatorname{Uniform}(0,1) \\[10pt]
Y = {} & \begin{cases} 2X & \text{if } 2X<1, \\ 2X-1 & \text{otherwise.} \end{cases}
\end{align}$$
Comment: @MichaelHardy In your example, $Y$ is entirely a function of $X$ and other conditions are satisifed. But I get $E[X/Y]=\int ^{1/2} _0 \dfrac {x}{2x}dx + \int ^{1} _{1/2} \dfrac {x}{2x-1}dx$, and the second term is still unbound, or my calculation not correct?
Comment: @novavita : Sorry -- I should have interchanged $Y$ and $X.$ As it is, you can say that $\operatorname{E}(Y/X) < \infty. \qquad$
Comment: @MichaelHardy yeah, now it works. excellent idea!
Answer: \begin{align}
X \sim {} &\operatorname{Uniform}(0,1) \\[10pt]
Y = {} &
\begin{cases} \frac 3 2 - X & \text{if } \frac 1 2 < X< 1 \\[10pt]
\frac 3 4 - X & \text{if } \frac 1 4 < X < \frac 1 2 \\[10pt]
\frac 3 8 - X & \text{if } \frac 1 8 < X < \frac 1 4 \\[10pt]
\text{and so on.}
\end{cases}
\end{align}
Then $Y$ also has the same uniform distribution as $X,$ and the distribution of $(Y,X)$ is the same as that of $(X,Y)$ (exchangeability) and the values of $X/Y$ and $Y/X$ remain between $1/2$ and $2$ and so have finite expectation, and $\Pr(X=Y)=0.$


MySQL Stored Procedure - Nested loop at fault?

Question: I have a medium sized stored procedure going on here below. My problem is that it doesn't do anything and I have no idea why.
1.) First of all, the code:
<code>    DROP PROCEDURE IF EXISTS deleteabundant_fixshared_shiftResources;
    DELIMITER //
    CREATE PROCEDURE deleteabundant_fixshared_shiftResources ()
    BEGIN
      DECLARE finish_flag BOOLEAN DEFAULT FALSE;
      DECLARE id INT(11);
      DECLARE startTime DATETIME;
      DECLARE endTime DATETIME;
      DECLARE shid INT(11);
      DECLARE resid INT(11);

      DECLARE id_inner INT(11);
      DECLARE startTime_inner DATETIME;
      DECLARE endTime_inner DATETIME;
      DECLARE shid_inner INT(11);
      DECLARE resid_inner INT(11);
      DECLARE cr130 CURSOR FOR SELECT shift_resource_id, start_date, end_date, shift_id, resource_id FROM temp_shift_resource;
      DECLARE cr131 CURSOR FOR SELECT shift_resource_id, start_date, end_date, shift_id, resource_id FROM temp_shift_resource;
        DECLARE CONTINUE HANDLER  FOR NOT FOUND SET finish_flag = TRUE;

    START TRANSACTION;

    OPEN cr130;
    OPEN cr131;
        OUTERLOOP: LOOP
        FETCH cr130 into id, startTime, endTime, shid, resid;
        IF finish_flag THEN LEAVE OUTERLOOP; END IF;
            INNERLOOP: LOOP
            FETCH cr131 INTO id_inner, startTime_inner, endTime_inner, shid_inner, resid_inner;
        IF finish_flag THEN LEAVE INNERLOOP; END IF;
        IF (id!=id_inner) THEN
        IF (resid=resid_inner AND shid_inner!=9) THEN

     -- logic to determine if the dates are wrong:
            IF (startTime<=startTime_inner AND endTime>=endTime_inner) THEN
                INSERT INTO repairchange ( shift_resource_id, changetype, shift_id, resource_id, start_date, end_date )
                                  VALUES ( id_inner, "FD", shid_inner, resid_inner, startTime_inner, endTime_inner );
                DELETE FROM temp_shift_resource WHERE shift_resource_id = id_inner;
            ELSEIF (endTime>=endTime_inner AND startTime<=endTime_inner) THEN
                INSERT INTO repairchange ( shift_resource_id, changetype, shift_id, resource_id, start_date, end_date )
                                  VALUES ( id_inner, "FU", shid_inner, resid_inner, startTime_inner, endTime_inner );
                UPDATE temp_shift_resource set endTime_inner=(startTime - INTERVAL 1 DAY) where shift_resource_id = id_inner;
            ELSEIF (startTime<=startTime_inner AND endTime>=startTime_inner) THEN
                INSERT INTO repairchange ( shift_resource_id, changetype, shift_id, resource_id, start_date, end_date )
                                  VALUES ( id_inner, "FU", shid_inner, resid_inner, startTime_inner, endTime_inner );
                UPDATE temp_shift_resource set startTime_inner=(endTime + INTERVAL 1 DAY) where shift_resource_id = id_inner;
            END IF;
    END IF;
    END IF;
            END LOOP INNERLOOP;
    SET finish_flag = FALSE;
      END LOOP OUTERLOOP;
      CLOSE cr130;
      CLOSE cr131;

    COMMIT;

    END //
    DELIMITER ;

    call deleteabundant_fixshared_shiftResources();
</code>
2.) Description of what I want to do:
Basically, I have a table full of workshifts. Due to code bugs, some of these shifts have a wrong date assigned to them, and I have to fix the database.

I have to run through the whole table, and compare the rows that are assigned to the same resource_id, which represents a person. So if a person has two shifts that look like (2016-05-10 to 2016-05-20) and (2016-05-15 to 2016-05-23) for example, I have to fix it so that one of them will be trimmed to (2016-05-10 to 2016-05-14) and (2016-05-15 to 2016-05-23).
A shift that is a nightshift, marked as shift_id=9, must not be modified at all.
I insert rows into the repairchange table if a change or a deletion has been made

3.) The procedure runs, but does nothing. I have examples in the database for wrong rows, one example is the one I wrote above. I suspect it is the nested loop, because I want to loop and fetch through the same table, but I haven't found anything on that.
I got the message
0 row(s) affected, 1 warning(s): 1329 No data - zero rows fetched, selected, or processed
but I have seen this before and my stored procedures have worked even though they output this warning.
Any ideas or tips are welcome. Thank you for your time!
Comment: Little update: I added a line "select * from temp_shift_resource;" in the LOOPINNER, it ran quite some times, so it seems the loops are working, but the fetching might not?
Comment: Little update 2: Added DATE(startTime) around so only dates would be compared, shouldnt bother the result though.
Answer: I figured it out, after quite some debugging:
I opened the cursors before both of the loops. This meant that after the first walk-through of the inner loop, the cursor was standing at +1 of the LAST row of the table, and when the new outer loop iteration started the second inner loop iteration, the cursor was still at the end position.
Thus it did not run. I replaced the inner-cursor opening and closing into the outer loop, and now it works properly.


Trying to sell the most batches of animals using linear programming

Question: I'm trying to sell the most batches of animals...
Let's say I have 200 dogs, 100 cats, and 100 ferrets.
Person A will give me $10 for a batch of: (1 dog, 1 cat, and 10 ferret).
Person B will give me $10 for a batch of: (1 dog, 20 cats, and 1 ferret).
Person C will give me $10 for a batch of: (20 dogs, 1 cat, and 1 ferret).

For person A, I can sell 10 batches (10 dogs, 10 cats, and 100 ferrets).
For person B, I can sell 5 batches (5 dogs, 100 cats, 5 ferrets).
For person C, I can sell 10 batches (200 dogs, 10 cats, and 10 ferrets).

Meaning, if I sell only to A, I'll get \$100, person B: \$50, person C: \$100.
BUT! I can actually sell more batches i.e. 9 batches to A and 9 batches to C.
If I sell 9 batches to person A (I'll use 9 dogs, 9 cats, and 90 ferrets), then I can also sell 9 batches to person C (using 18 dogs, 9 cats, and 9 ferrets).
I sell A:9 and C:9, I get the best income and most batches sold.
This is probably extremely simple in terms of optimization and a simple matrix, but it's been a while since algebra.
I obviously don't want to try every possible combination and see which gives me the most money.
Question: Assuming that each batch always has the same income, is there a way to find out which combination of batches A/B/C will give the highest yield?
Comment: I hope you don't mind - I added the tag linear-programming to this question. This is actually what you are trying to do. You are correct that it's fairly straightforward once you know what term to google.
Comment: Here's [the first hit on youtube](https://www.youtube.com/watch?v=-32jcGMpD2Q) for "linear programming." It's only 15 minutes and seems to cover all the information you'd need for this sort of problem.
Comment: @NoseKnowsAll I figured it's extremely simple, but it's been too long since I was in school.  If someone could just point me to a wiki or any kind of article with something related, I'm sure I could piece it together.  Maybe lol
Answer: I still suggest watching the tutorial video I linked in the comments to understand how linear programming works. That being said, you can formulate your problem as trying to maximize
$$Profit=10A+10B+10C$$
subject to the constraints on your number of dogs to sell ($A+B+20C \leq 200$), number of cats to sell ($A+20B+C \leq 100$), number of ferrets to sell ($10A+B+C \leq 100$), and that the number of batches sold must be positive ($A\geq0$, $B\geq0$, and $C\geq0$).
Linear programming tells us that the maximum occurs on a point at the endpoints of the polyhedron formed by all of our constraints. Integer programming tells us that the maximum will be an integer point inside the endpoints (if they're not already integers). Thus, we only have to check a few endpoints.
In your case:
$$\begin{aligned}
(A,B,C) = (0,0,0)&\text{ yields Profit}=\$0\\
(A,B,C) = (10,0,0)&\text{ yields Profit}=\$100\\
(A,B,C) = (0,5,0)&\text{ yields Profit}=\$50\\
(A,B,C) = (0,0,10)&\text{ yields Profit}=\$100\\
(A,B,C) = (9.5,4.5,0)&\text{ yields Profit}=\$130\\
(A,B,C) = (9.0,0,9.5)&\text{ yields Profit}=\$180\\
(A,B,C) = (0,4.5,9.7)&\text{ yields Profit}=\$130\\
(A,B,C) = (8.7,4.1,9.4)&\text{ yields Profit}=\$210\\
\end{aligned}$$
Therefore, selling 8 batches to person A, 4 batches to person B, and 9 batches to person C will yield \$210, only requiring 192 dogs, 97 cats, and 93 ferrets.
Comment: Yep. I already watched it and was trying to work out the math. Now I have to find how to get polyhedron intersections.  ps. It's hard to sell 4.5 cats and 9.7 ferrets... but some might try ;)
Comment: I'll be honest, I just typed `Solve[{a+b+20c==200,a+20b+c==100,10a+b+c==100}]//N` into WolframAlpha so that I wouldn't have to deal with the messy math myself!
Comment: @David The first solution is from selling to none of the buyers. The next 3 are from selling to one of the buyers. The next 3 are selling to 2 of the buyers. The last one is from selling to all 3 of the buyers. For instance, if I plan to buy 0 from person C then my equations become $A+B\leq200$, $A+20B\leq100$,$10A+B\leq100$. Noting that the inequality $A+B\leq200$ adds nothing compared to the other two inequalities, I used `Solve[{a+20b==100,10a+b==100}]//N` with WolframAlpha. It's a lot easier to draw the systems of inequalities out and find the intersection points that way...
Comment: Solving systems of equations is much easier.  I have no problems with that. How did you arrive at the 9.5, 4.5, 0; 9.0, 0, 9.5; and 0, 4.5, 9.7 test points?  They don't appear to be solutions to the s.o.e.  Wolfram only gives a single set of points, since it's a linear set. Not sure how the others were generated.
Comment: Got it! Thanks for your explanation.
Answer: Let the integer decision variables $x_1, x_2, x_3 \geq 0$ denote the number of batches of animals sold to customers $A$, $B$ and $C$, respectively. Since we have a finite number of dogs, cats and ferrets, we have three inequality constraints
$$\begin{array}{cc} x_1 + x_2 + 20 x_3 \leq 200\\ x_1 + 20 x_2 + x_3 \leq 100\\ 10 x_1 + x_2 + x_3 \leq 100\end{array}$$
Each batch that is sold brings in $\$10$. Hence, the total revenue is $10 x_1 + 10 x_2 + 10 x_3$. Assuming that our goal is to maximize revenue, we have the following integer linear program
$$\begin{array}{ll} \text{maximize} & 10 x_1 + 10 x_2 + 10 x_3\\ \text{subject to} & x_1 + x_2 + 20 x_3 \leq 200\\ & x_1 + 20 x_2 + x_3 \leq 100\\ & 10 x_1 + x_2 + x_3 \leq 100\\ & x_1, x_2, x_3 \geq 0\\ & x_1, x_2, x_3 \in \mathbb{Z}\end{array}$$
Observing the inequality constraints, we conclude that
$$x_1 \leq 10 \qquad \qquad x_2 \leq 5 \qquad \qquad x_3 \leq 10$$
Hence, the feasible region is a subset of
$$\{0,1,\dots,10\} \times \{0,1,\dots,5\} \times \{0,1,\dots,10\}$$
whose cardinality is only $(1+5) \cdot (1+10)^2 = 726$. One can use brute force to find the optimal solution. Using Haskell,
λ let triples =  [ (x1,x2,x3) | x1 <- [0,1..10], x2 <- [0,1..5], x3 <- [0,1..10] ]
λ let f (x1,x2,x3) = 10 * (x1 + x2 + x3)
λ let g1 (x1,x2,x3) = (x1 + x2 + 20*x3 <= 200)
λ let g2 (x1,x2,x3) = (x1 + 20*x2 + x3 <= 100)
λ let g3 (x1,x2,x3) = (10*x1 + x2 + x3 <= 100)
λ let triples' = filter g1 triples
λ let triples'' = filter g2 triples'
λ let triples''' = filter g3 triples''
λ maximum $ map f triples'''
210
λ filter (\(x1,x2,x3)->(f (x1,x2,x3) == 210)) triples'''
[(8,4,9)]

The optimal sale is $(8,4,9)$, which yields a revenue of $\$210$.
Comment: Thanks. I like how you explained it, but I'm avoiding brute force. It only works for smaller quantities. If I have more dogs/cats/ferrets, it becomes unfeasible.
Comment: @David It's not merely a matter of how many animals you have, it's also how many customers you have. You can obviously use a linear programming solver, obtain the LP solution over the reals, and then round the solution to an integer solution.
Comment: Yep, but I'm trying to understand it fundamentally and not rely on compumagic. :)


Linking child view controllers to a parent view controller within storyboard

Question: Can you associate child view controllers to a custom container view controller in Storyboard?
I can link child view controllers to a tab view controller, and I can link one view controller to a navigation controller.
What must I do to the container VC to accept child VCs?
Answer: As something of a combo of Caleb and Matt's answers, I did:
-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    if ([segue.identifier isEqualToString:@"cpdc_check_embed"]) {
        self.checkVC = segue.destinationViewController;
    }
}

...where checkVC is a property on the container controller:
@property (weak,nonatomic) PXPCheckViewController * checkVC;

You just have to set your embed segue's Storyboard ID to whatever you want (in this case, cpdc_check_embed):

...and then check the identifier in -prepareForSegue:sender:.
Still not an outlet, but cleaner than Matt's (IMHO) and more specific than Caleb's, and you still get a nice-looking storyboard:
Comment: How can you get 2 segues from the same container? I am trying to add a second embeded view controller but as soon as I click embed type, the previos segue goes away and I am left with only 1 segue.
Comment: You're using an embed segue, which is an iOS 6 feature. My question dates from November 2011. :-p
Comment: Now that iOS 6 has been released, this is the correct answer.
Comment: @awolf I'm afraid you're right. I guess "correct answers" can evolve too… I changed the flag, causing Matt's rep to return to 666 (coincidence? :-p ).
Comment: Yep. Just realized I'm letting the cat out of the bag a little. Tried to install to a client's 5.1.1 phone; no dice.
Answer: The storyboard deals with built-in container view controllers very nicely, displaying segues to child/root view controllers so that relationships are clearly shown. It is also nice how the children and parent view controllers are separated into different scenes.
If you want to achieve this effect in your own project, then there is a trick that is not perfect but very straightforward. In my example, suppose I have a container view controller that acts like a tab bar controller with only two tabs, 'left' and 'right'. I want to have a scene represent the parent view controller, and two separate scenes represent both the 'left' child view controller and the 'right' child view controller.
Even though it is impossible, it would be nice if I could create IBOutlets from the container view controller to its children in different scenes, and then when my container view controller is displayed set up the parent/child relationships according to the rules described the UIViewController documentation. If we had references to our 'left' and 'right' child view controllers, then we could set up the relationships no problem.
The standard solution to this referencing problem is to create references to child view controllers by dragging in Object outlets into the container view controller's scene, and then specifying their class type as being instances of the child view controller classes.
In order to keep children separated in different scenes like Apple's built-in containers, however, we will use a different trick. First, suppose we have the following properties declared in our container class, ContainerViewController:
@property (nonatomic, strong, readwrite) UIViewController *leftViewController;
@property (nonatomic, strong, readwrite) UIViewController *rightViewController;

In our storyboard, select the scene representing the 'left' view controller. In the attributes inspector, set the view controller's identifier property to "cvc_leftViewController" ("cvc_" refers to ContainerViewController, but really the identifier can be anything you want). Do the same for the right view controller's scene, setting it's identifier to "cvc_rightViewController".
Now insert the following code into ContainerViewController's viewDidLoad method:
if (self.storyboard) {
    _leftViewController = [self.storyboard instantiateViewControllerWithIdentifier:@"cvc_leftViewController"];
    _rightViewController = [self.storyboard instantiateViewControllerWithIdentifier:@"cvc_rightViewController"];
}

When ContainerViewController is loaded from the storyboard, it will go grab the 'left' and 'right' view controllers from their respective scenes and set references to them via its properties. Now that you have control of the child view controller instances, you can set up the parent/child relationships however you like. To learn how to do that properly refer to the UIViewController documentation.
This trick is not perfect, and has many caveats, but if you are careful you can make it work nicely for your project.
Edit: Although this is completely unnecessary and doesn't mean anything, if you really really want to have the storyboard display connections from your container to your child view controllers just like Apple's built-in containers, just use my method above and then set up segues directly between the container scene to the child scenes, and simply never perform those segues. Now everything will work correctly and look pretty too.
Comment: +1 Sounds like a good technique, and you're right that it mimics the way Apple's container view controllers work in storyboards. The main drawback compared to creating the child view controllers in the same scene as the container is that you can't make connections between scenes. So, if you want to set a child controller's delegate to the parent controller, you have to do that in code -- you can't just drag a connection.
Comment: True. Also, I always get a bit nervous basing connections off of identifier strings rather than the feeling of stability that comes with outlets.
Comment: Cool hack! I'll use it in my existing iOS 5 apps like now. My project's going to be much simpler. Apple solved my problem for iOS 6 (with view controller container views right in Storyboard/IB), but that's for new apps or when I decide to abandon iOS 5 in 2-3 years for existing apps.
Answer:
Can you associate child view controllers to a custom container view
  controller in Storyboard?

I think what you're asking here is how to connect a view controller in one scene to an outlet of a view controller in a different scene. I don't believe that's possible, perhaps because the storyboard machinery may not have all the scenes in a storyboard loaded at the same time.
You're probably asking this because you want to pass some information from one view controller to another as you segue from one scene to the next. The way to do this when you're working with storyboards is to override -prepareForSegue:sender: in one or both view controllers affected by the segue. The UIStoryboardSegue object provided in the segue parameter has sourceViewController and destinationViewController properties, and also an identifier property. You can use these properties to identify the segue that's about to transfer data between the view controllers.
Ray Wenderlich's blog has a nice two-part tutorial on using storyboards that may help you:

Part 1 covers setting up a storyboard project, adding scenes, and creating segues.
Part 2 deals with using segues to transition between scenes, including the prepareForSeque method mentioned above.

iOS 5 allows multiple view controllers to be active in the same scene (although one should still be in charge), so a single scene in your storyboard might have several controllers. You can use outlets to connect these controllers to each other, and you can configure those connections the same way you did in IB: control-drag from one controller to another in the same scene. The usual outlet list will pop open to let you choose which outlet to connect.
Comment: In that case, just drag a NSObject from the library into the dock for the scene that you want to contain the child view controller. Set the object's type to your view controller class. After that, you can control-drag to make connections to or from other objects, including other view controllers in the scene. What you can't do, as explained above, is to make connections between objects (view controllers or otherwise) in different scenes.
Comment: No, I mean using two view controllers at the same time. A _container_ view controller containing itself multiple _child_ view controllers. Something like the split view controller, which contains a master view controller and a detail view controller, but children of the split view controller (the parent VC).
Comment: So, unlike Apple's container view controllers, all view controllers (child and parents) must be inside the same scene if I want to display them simultaneously. Well, it does the job and that is all I wanted. Thank you!
Comment: @Randy: See my answer for an alternate solution that might be closer to what you are looking for.
Answer: The key to using multiple controllers in one scene (what I believe you are after here) is using the mysterious Object from the Objects list in IB to represent the other view controller and hooking up its outlets.
This answer How to create custom view controller container using storyboard in iOS 5 should help I hope. The answer also provides a working example app which is very helpful.
Answer: The problem with @Ben's (otherwise reasonable) answer is that it only works at one level of nesting.  Beyond that, it would required that every subsequent VC is customized to save the nesting view controller in prepareForSegue.
To solve this, I spent too much time exploring an NSObject based index that that you could add to the Storyboard, bind to a scene, and which would then register it's parent VC in a global index, based on type and restorationId.  That works / can work, but is too much effort in the end, and still requires the two step process of visually binding, and programmatically looking up.
For me, the simplest and most general solution is to lazily descend the view controller hierarchy
In my simple test project, I added the following lines to viewDidLoad:
    self.left.data = [
        "Zombie ipsum reversus ab viral inferno, nam rick grimes malum cerebro.",
        "De carne lumbering animata corpora quaeritis." ]

where left is defined as:
lazy var left:CollectionViewController = { [unowned self] in
    return self.childViewControllerWithId("Left") as! CollectionViewController }()

and childViewControllerWithId is defined as:
extension UIViewController {
    func childViewControllerWithId(rid:String) -> UIViewController? {

        // check immediate child controllers
        for vc in self.childViewControllers as! [UIViewController] {
            if vc.restorationIdentifier == rid { return vc }
        }

        // check nested controllers
        for vc in self.childViewControllers as! [UIViewController] {
            if let vc = vc.childViewControllerWithId(rid) {
                return vc
            }
        }

        assert(false, "check your assumptions")
        return nil
    }
}

Note that you could do other find variants based on type, if need be.  Also note that the above requires that you define the restoration id in the Storyboard file.  If you did not have repeated instances of the same view controller, then using type would be easier.
And to state what is hopefully obvious, you don't need to implement prepareForSegue, nor do you have to use the lazy loading, you just have to call find(...).


Muting a hidden Youtube iframe .. button onclick in JS not working

Question: I am making a fun little website with a video and music. I made the video in iMovie and then put in on youtube. In the past when I have worked with iMovie, it makes you purchase music before adding it to the video. I thought I would get around this by including two iframes in my html- one for the music from youtube and one for the iMovie. I have them both on autoplay when the site loads, and the music iframe is hidden. Since it is hidden, I cannot see the volume controls.
I want an option to mute the music, so thought I would add a button in the html, and do an onclick (and a function in JS) but I can't get anything to work. the code is below. any advice? I've tried many, many things. thanks!
HTML:
<!doctype html>

    <title>AKO</title>
    <link href="https://fonts.googleapis.com/css?family=Lobster|Permanent+Marker" rel="stylesheet">

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
    <link rel="stylesheet" type="text/css" href="styles.css">

AKO

Scooter

        <button id="muteButton" class="glyphicon glyphicon-volume-off" onclick="myFunction()" style="float:right;"></button>

                SPORTS

                Scooter

                Skate

                Surf

                AKO

                About

                Athletes

                CONTACT

                Email email@example.com

                Phone 1-800-999-9999

                Location OB, SD, CA

JavaScript:
alert("hi!");

var music = document.getElementById('janesMusic');
var button = document.getElementById('muteButton');

function myFunction() {
    var media = document.getElementById('janesMusic');
    media.volume = 0; /*set volume to zero|takes values btw 0-1*/
    media.pause(); /*pause the audio/video*/
}

Answer: Legal
Had a bit of research for a moment and found out that what you want to do (hidden YouTube Player, only play the audio part...) would be against the terms of service of the YouTube API.
You can find them in the I. Additional Prohibitions part of the YouTube API Developer Policies.

separate, isolate, or modify the audio or video components of any YouTube audiovisual content made available as part of, or in connection with, YouTube API Services. For example, you must not apply alternate audio tracks to videos;
promote separately the audio or video components of any YouTube audiovisual content made available as part of, or in connection with, the YouTube API Services;
create, include, or promote features that play content, including audio or video components, from a background player, meaning a player that is not displayed in the page, tab, or screen that the user is viewing;

You could also look here: Webmasters question

Example
When I tried to show the video in a smaller player. This (self-explaining message) showed up in the following screenshot:

You could probably work around this, but I can definitely not recommend this.

What you could do
Now, if I were you, I'd get the music from another source. Cause it's against their terms of service and it would be immensely inefficient to stream the video just for the audio part.
I would just place an audio file in the same workspace and get it from there.
<audio id="music" controls>
  <source src="audio/music.mp3" type="audio/mpeg">
Your browser does not support the audio element.
</audio>

Then you should be able to mute your audio content with XXX.muted = true.
It's the same for audio and video content.
var audio = document.getElementById("music");
audio.muted = true; //audio.muted = false; to unmute

Recommended to read: W3Schools HTML5 Audio
I'm sorry I couldn't help you with your initial question but I hope this helps.
Comment: @CodingK8 Hope I could help :)


Jenkins Pipeline Syntax - Need to get Parameters for Job from wget

Question: Im new to Jenkins Pipeline , Groovy syntax etc.

I have a Jenkins job that takes 5 parameters.
I want to schedule a pipeline that checks for listings via WGET ( format is csv - i can switch to JSON output also ) and the csv is one row with 5 parameters listed
a,b,c,d,e
I need to parse that list and pass the parameters to the
JOB "IF" there are rows , if not , skip and complete the pipeline.

I have searched and basically got as far as this for testing...:
pipeline {

environment {
 testVar='foo'}

agent any

stages {
    stage('Example Build') {

        steps {
            echo 'Hello World'

            script {

       sh "RESULT=\$(wget -qO- https://www.url.com/getlist)"
       sh "echo \$RESULT"
      //variable define based on parse of CSV???
    }

        }
    }
    stage('Example Deploy') {
        when {

            expression { testVar=='foo' }
        }
        steps {
            echo 'Deploying'
   build job: 'Testing', parameters:
  [
  string(name: 's_e', value: 'u'),
  string(name: 't_e', value: 't'),
  string(name: 's_s', value: 'DS'),
  string(name: 't_s', value: 'SH'),
  string(name: 'efg', value: 'TEST')
  ]

        }
    }
}}

Obviously i have more work to do around parse of RESULT (but I am not sure how I can achieve this in Pipeline).
I then need to check for RESULT empty or not , then pass variables to the Build.
Comment: Could you please try: `def out = sh(script: 'wget -qO- https://www.url.com/getlist', returnStdout: true)` ?
Comment: Thanks Opal , where would be best to place that?
Comment: Try just after `echo Hello World`. Not sure if it works ;)
Comment: Have added after where i had RESULT defined and hasnt errored but a little unsure what to do with it next :)
Comment: `echo` it for instance. And if displays expected output go with parsing.
Comment: Thanks , had tried but not returning. I see your concept though of returning true if im getting values
Answer: I opted for a different option.
Instead I now have a Jenkins Job where I use the "Trigger/Call Builds on other Projects"
Before thats added as a build step , i have some code to get the WGET CSV information.
RESULT=$(wget -qO- https://url.com/getlist)

if [ -z "$RESULT" ]
then

echo "Nothing to do"
# exit 1

else

echo "$RESULT"

s_env_upper=$(echo $RESULT | awk -F',' '{print $1}')
t_env_upper=$(echo $RESULT | awk -F',' '{print $2}')
s_env=$(echo $s_env_upper| tr [A-Z] [a-z])
t_env=$(echo $t_env_upper| tr [A-Z] [a-z])

echo "s_env=$s_env" > params.cfg
echo "t_env=$t_env" >> params.cfg

fi

Hope this helps someone else... i was breaking my heart trying to get pipeline to do the work and answer was simpler.


What are new tasks in data mining?

Question: Beside five "classical" data mining tasks

regression and classification
association rules
clustering
outlier detection
dimension reduction and visuzalization,

I recently found sources regarding some new ones including

contrast and change mining
graph mining
opinion mining

Are there any other new tasks that I should know?
Thank you in advance.
Answer: From a very broad sense of Data Mining and mixing slightly tasks and methods, these are my two cents...
Sentiment Analysis (although you have said opinion mining)
Relational Classification
Relationship Extraction (Knowledge Discovery)
Recommendation
Time-Aware Information Retrieval
Time-Aware Prediction (Series Prediction)
Summarisation
Personalisation
In general, a good idea is to find a conference related to the topic you want to observe (KDD for Data Mining for instance) and see the sessions per topic they have in order to discover new tasks/applications.
Regards,

What are new tasks in data mining?


Ajax não funciona quando vem de um select do formulário

Question: Quando o  #sectionChooser vem do Ajax o  não funciona o select #bairros para colocar a #rua, onde estaria o problema?
Html

                            Planos

              <select name="Planos" id="sectionChooser" class="form-control valid" aria-invalid="false">

              <option value="">Selecione</option>
    <option value="1">Diamante</option><option value="2">Ouro</option><option value="3">Prata</option><option value="4">Light</option><option value="5">Free</option><option value="19">Link</option>
              </select>

                                    Diamante

                        Bairro
                        <select class="form-control valid" name="bairro" id="bairro3" required="" aria-invalid="false">
    <option value="">Selecione</option>
<option value="1">teste bairro</option><option value="2">teste bairro 2 3</option><option value="3">ação bairros</option><option value="4">Centro</option>

    </select>

                        Rua

<select class="form-control" name="rua" id="rua" required="">

    </select>

estou tentando assim, mais ainda não deu
$(document).ready(function(){

    $(document).on('change', '#sectionChooser', function(){
        var myID = $(this).val();
        $('.panel').each(function(){
            myID === $(this).attr('id') ? $(this).show() : $(this).hide();
            console.log("ok");
        });
    })

    $(document).on('change', '#bairro', function(){
        var bairroID = $(this).val();

        if(bairroID){
            $.ajax({
                type:'POST',
                url:'ajax_data2.php',
                data:'bairro_id='+bairroID,
                success:function(html){
                    $('#rua').html(html);
                    console.log("ok");
                }
            });
        }else{
            $('#rua').html('<option value="">Select categoria first</option>');

        }
    });

});

Comment: Esse #sectionChooser vem do Ajax?
Comment: sim vem do ajax, ainda nao deu certo
Comment: Passe seu html também para que possamos simular seu problema.
Comment: coloquei na resposta
Comment: Não vá alterando a pergunta conforme as respostas. Senão a gente perde como estava.
Comment: Onde tem `elemento` é apenas um exemplo... no lugar de `elemento` vc coloca o seletor... veja a resposta.
Comment: vc não precisa alterar nada no seu código, apenas os dois eventos que coloquei na resposta.
Answer: O problema é que está selecionando o id errado: em vez de #bairro, o correto seria #bairro3, veja:
                                                  id correto
                                                       ↓
<select class="form-control valid" name="bairro" id="bairro3" required="" aria-invalid="false">

Ao usar Ajax, em vez de usar eventos .change, use .on:
$(document).on('change', '#sectionChooser', function(){

e
$(document).on('change', '#bairro', function(){

Assim não terá problemas de delegação com elementos inseridos de forma dinâmica na página.
O código deve ficar assim:
$(document).ready(function(){

    $(document).on('change', '#sectionChooser', function(){
        var myID = $(this).val();
        $('.panel').each(function(){
            myID === $(this).attr('id') ? $(this).show() : $(this).hide();
        });
    })

    $(document).on('change', '#bairro3', function(){
        var bairroID = $(this).val();

        if(bairroID){
            $.ajax({
                type:'POST',
                url:'ajax_data2.php',
                data:'bairro_id='+bairroID,
                success:function(html){
                    $('#rua').html(html);
                }
            });
        }else{
            $('#rua').html('<option value="">Select categoria first</option>');

        }
    });

});

Comment: O problema é que o id é `#bairro3` e não `#bairro`
Comment: ainda não deu certo amigo, estranho que não retorna nenhum erro no console
Comment: coloque um `console.log("ok");` dentro dos eventos para ver se pelo menos está pegando o click.
Comment: aqui sim  $(document).on('change', '#sectionChooser', function(){ mais aqui   $(document).on('change', '#bairro', function(){ nao
Comment: olha a minha pergunta q editei com os console.log("ok");
Comment: Coloque logo após a abertura do evento para ver se o click é escutado, e não lá no meio.
Comment: fiz assim $(document).on('change', '#bairro', function(){
  console.log("ok"); e não retornou nada ainda, apenas no $(document).on('change', '#sectionChooser', function(){  retorna "ok"
Comment: arrumei o html na  pergunta e coloquei os bairros  e rua
Comment: hmm entendi, vou ver o que faço, obrigado
Comment: Mas ele deveria pegar o id Bairro3 aqui $(document).on('change', '#bairro', function(){
        var bairroID = $(this).val(); mas mesmo assim nao funciona
Comment: Vamos [continuar esta discussão no chat](https://chat.stackexchange.com/rooms/77229/discussion-between-wagner-martins-bodyboard-and-dvd).
Answer: Para pegar a <option> selecionada:
$('#sectionChooser option:selected').val();

Comment: ainda não deu certo amigo
Comment: Então o erro não está ai, porque assim vc pega o option selecionado, pode dar um alert pra vc ver o value.
Comment: oha como eu fiz na resposta, coloquei o html também


php não consegue copiar arquivo remoto, mas faz download pelo browser

Question: Olá. Este arquivo:
http://www1.caixa.gov.br/loterias/_arquivos/loterias/D_megase.zip
Consigo baixar pelo navegador, mas não consigo copiar direto para meu servidor usando PHP. Já testei todas as maneiras possíveis (copy(), file_gets_content(), fopen(), curl(), etc) e não há meio de fazer dar certo. Como devo fazer?
Comment: qual é o erro que acontece quando tenta no PHP?
Comment: Qual é o erro? Você precisa nos informar o sintomas para darmos o diagnóstico
Comment: Opa. Normalmente o erro retornado é:
Warning: copy(http://www1.caixa.gov.br/loterias/_arquivos/loterias/D_megase.zip): failed to open stream: Redirection limit reached, aborting in /home/megas028/public_html/teste/atualizar_resultados.php on line 43
failed to copy http://www1.caixa.gov.br/loterias/_arquivos/loterias/D_megase.zip...
Answer: O que se passa é o seguinte:

Como se pode ver pela imagem o servidor implementa um cookie (security=true) e deve redirecionar para o mesmo url, se tiver o cookie autoriza download, senão fica em loop de redirecionamento até 'ver' o cookie na requisição. Soponho que era isso que estava a faltar na sua requisição. Tente com curl o seguinte:
$curl = curl_init();
curl_setopt($curl, CURLOPT_RETURNTRANSFER, True);
curl_setopt($curl, CURLOPT_HTTPHEADER, array("Cookie: security=true"));
curl_setopt($curl, CURLOPT_URL, 'http://www1.caixa.gov.br/loterias/_arquivos/loterias/D_megase.zip');
curl_setopt($curl,CURLOPT_USERAGENT,'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.7; rv:7.0.1) Gecko/20100101 Firefox/7.0.1');
$return = curl_exec($curl);
curl_close($curl);
file_put_contents('file.zip', $return);

Como pode ver desta maneira enviamos também o cookie, que era o necessário para que o servidor autoriza-se o download do ficheiro.
Aqui tem o a mesma requisição com file_get_contents:
$opts = array(
    'http' => array(
        'method'=>"GET",
        'header' => array(
            'Cookie: security=true'."\r\n",
            'User-Agent' => "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.7; rv:7.0.1) Gecko/20100101 Firefox/7.0.1",
        )
    ),
);
$context = stream_context_create($opts);
file_put_contents('file.zip', file_get_contents('http://www1.caixa.gov.br/loterias/_arquivos/loterias/D_megase.zip', false, $context));

Comment: Exato @WallaceMaxters como eu desconfiava. Ora tente `$ curl -vL http://www1.caixa.gov.br/loterias/_arquivos/loterias/D_megase.zip"` ... Aí fica num loop de redirecionamento.... Depois faça `$ curl -vL http://www1.caixa.gov.br/loterias/_arquivos/loterias/D_megase.zip -b security=true` (envie o cookie com a requisição), aqui já tem acesso ao ficheiro
Comment: Resolvido! Valeu! Deixa eu estudar esse código direito, que perdi a manhã num monte de variedade e nada funcionou. Só esse!
Comment: @JoãoGurgel você preferiu usar o `curl`. Eu tava querendo descobrir porque as outras funções se comportam assim :\
Comment: @WallaceMaxters, acho que faltava mandar o cookie com a requisição, user agent (não tenho a certeza quanto a este ultimo mas pelo sim pelo não mais vale mandar)
Comment: @Miguel também estou desconfiando que seja isso. Parece que a url redireciona pra ela mesma.Talvez nesse meio processo haja uma verificação de alguma header que faltou.
Comment: Exato @WallaceMaxters , deve redirecionar para ela mesma e só autoriza quando vir o cookie
Answer: A pergunta é antiga, mas a solução é nova (10/12/2019):
$VContext = stream_context_create(["http" => ['method' => 'GET', 'header' => ['Cookie: security=true'."\r\n", 'User-Agent' => $_SERVER['HTTP_USER_AGENT']]]]);

$VMegaSena = "http://loterias.caixa.gov.br/wps/portal/loterias/landing/megasena/!ut/p/a1/04_Sj9CPykssy0xPLMnMz0vMAfGjzOLNDH0MPAzcDbwMPI0sDBxNXAOMwrzCjA0sjIEKIoEKnN0dPUzMfQwMDEwsjAw8XZw8XMwtfQ0MPM2I02-AAzgaENIfrh-FqsQ9wNnUwNHfxcnSwBgIDUyhCvA5EawAjxsKckMjDDI9FQE-F4ca/dl5/d5/L2dBISEvZ0FBIS9nQSEh/pw/Z7_HGK818G0KO6H80AU71KG7J0072/res/id=buscaResultado";

$VResultado = @file_get_contents($VMegaSena, false, $VContext);

if ($VResultado !== false)
   $VResultado = json_decode($VResultado);

var_dump($VResultado);


C++ ofstream equivalent to Win32 CreateFile with CREATE_NEW

Question: In an application I want to be sure that I am writing a brand new (binary) file. In Win32 programming I know I can do this with CreateFile using CREATE_NEW, but I can't work out a pure C++ standard way.

Creates a new file, only if it does not already exist.
  If the specified file exists, the function fails and the last-error code is set to ERROR_FILE_EXISTS (80).
  If the specified file does not exist and is a valid path to a writable location, a new file is created.

I tried using std::ios::out | std::ios::binary | std::ios::ate then seeing if tellp gave me the start of the file or not, but apart from the obvious case that this would still overwrite an empty file, it also seems to truncate a non-empty file anyway as if I used std::ios::trunc...
This was on VS2013, although I assume this is not a compiler/library bug.
Comment: iostream users have muddled through this for the past 16 years, probably by first trying to open the file to check if it already exists.  Closest you could get with the CRT is _open() with the _O_CREAT and _O_EXCL mode flags.
Answer: The C++ standard doesn't have an API guaranteeing a new file. When opening an existing file in write-only mode without specifying std::ios_base::app it is truncated (independent on whether std::ios_base::trunc is used). I don't know about Windows but on POSIX this would retain the original inode and processes already having opened the file can still access it.
If it is sufficient to get an open and empty file rather than a new one, omiting std::ios_base::in and std::ios_base::app should do the trick (note that opening an std::fstream or an std::ifstream implicitly adds std::ios_base::in).


Apache 2.4 REMOTE_USER lowercase

Question: I'm dealing with a legacy system that uses Apache with mod_auth_basic and mod_authnz_ldap for authentication and authorization in given directories and those directories with an .htaccess file. The authenticated user is then provided to various CGI scripts.
I would like to force all usernames to lowercase within the Apache httpd.conf config file, if possible. This would allow me to skip updating tens of old CGI files to force the username to lowercase (where it is eventually used), by updating one configuration file and restarting the server.
The directory full of CGI scripts that I want to provide a lowercase username to is already protected by AuthType Basic followed by AuthBasicProvider ldap followed by an AuthLDAPURL specific to my case. This authentication works.
I initially tried using mod_rewrite, not realizing until later that mod_rewrite is primarily for rewriting URLs.
Is this possible to do? Am I missing something that would allow me to force the username to lowercase via mod_auth_basic or mod_authnz_ldap?
Answer: Based on https://stackoverflow.com/a/31242711/773806 I was able to resolve this question.

I first ensured that mod_perl 2 was installed in all relevant environments.
I then added the following to my httpd.conf file:

PerlRequire /etc/httpd/scripts/startup.pl
PerlHeaderParserHandler MyApache2::ConvertUserToLowercase

I created the directories /etc/httpd/scripts and /etc/httpd/scripts/MyApache2.
Within /etc/httpd/scripts I created the file startup.pl with the following contents:

use lib qw(/etc/httpd/scripts/);
1;

Within /etc/httpd/scripts/MyApache2 I created the file ConvertUserToLowercase.pm and added the following contents:

package MyApache2::ConvertUserToLowercase;

use strict;
use warnings FATAL => 'all';

use APR::Base64;
use Apache2::Access;
use Apache2::Const -compile => qw(OK DECLINED HTTP_UNAUTHORIZED);
use Apache2::RequestRec;
use APR::Table ();

sub handler {
    my $request = shift;
    my ($code, $password) = $request->get_basic_auth_pw();
    if ($code == Apache2::Const::OK) {
        my $user = lc $request->user;
        my $auth_header = APR::Base64::encode("$user:$password");
        $request->headers_in->{'Authorization'} = "Basic $auth_header";
    }
    return Apache2::Const::OK;
}

1;

Ensure that all files are readable by Apache.
The server configuration was then tested with httpd -t and restarted with sudo systemctl restart httpd.

Apache 2.4 REMOTE_USER lowercase


Como inserir uma lista de dados usando o volley

Question: Minha aplicação grava todos as informações de posições dentro da tabela posicoesdados.
Essa tabela tem uma coluna chamada "ENVIADO".
Eu tenho que fazer um select retornando todas as posições que não foram enviadas e mandar para um webserver, após enviar e o resultado for OK, eu preciso setar o flag para TRUE, enviado.
Tenho 2 problemas.
1 - Usando o volley, ele envia somente a ultima posição, pois quando faço:
for (DadosPosicao dadosposicao : dadosposicoes) {
    params.put(Constantes.KEY_DISPOSITIVO, app.getSistema().getDispositivoID());
    params.put(Constantes.KEY_LATITUDE, String.valueOf(dadosposicao.getLatitude()));
    params.put(Constantes.KEY_LONGITUDE, String.valueOf(dadosposicao.getLatitude()));
    params.put(Constantes.KEY_DTLOG, Funcoes.formatarDataHora(dadosposicao.getDtlog(), "yyyy-MM-dd HH:mm:ss"));
    params.put(Constantes.KEY_DTRECEBIMENTO, Funcoes.formatarDataHora(dadosposicao.getDtRecebimento(), "yyyy-MM-dd HH:mm:ss"));
    params.put(Constantes.KEY_PANICO, String.valueOf(dadosposicao.getPanico() ? 1 : 0));
    params.put(Constantes.KEY_VELOCIDADE, String.valueOf(dadosposicao.getVelocidade()));
    params.put(Constantes.KEY_HODOMETRO, String.valueOf(dadosposicao.getHodometro()));
    params.put(Constantes.KEY_DIRECAO, String.valueOf(dadosposicao.getDirecao()));

}

Eu entendi que ele sobrepoe as minhas KEY. :(
2 - Como eu sei que aquela posição foi enviada com sucesso para poder mudar o flag pra true?
Hoje tenho o seguinte:
public void EnviarPosicoes() {

    if (isOnline()) {
        LocalDao<DadosPosicao> dadosPosicaoDao = LocalFactoryDB.getDao(this, DadosPosicao.class);

        final List<DadosPosicao> dadosposicoes = ((DadosPosicaoLocalDao) (dadosPosicaoDao))
                .selectDadosPosicaoNaoEnviados();

        if (dadosposicoes.size() > 0) {
            StringRequest postRequest = new StringRequest(Request.Method.POST, servidor,
                    new Response.Listener<String>() {
                        @Override
                        public void onResponse(String response) {
                            Log.i("mrcsistemas", response);
                        }
                    },
                    new Response.ErrorListener() {
                        @Override
                        public void onErrorResponse(VolleyError error) {
                            error.printStackTrace();
                        }
                    }
            ) {
                @Override
                protected Map<String, String> getParams() {
                    Map<String, String> params = new HashMap<>();

                    Log.i(Constantes.TAG, app.getSistema().getDispositivoID());

                    for (DadosPosicao dadosposicao : dadosposicoes) {
                        params.put(Constantes.KEY_DISPOSITIVO, app.getSistema().getDispositivoID());
                        params.put(Constantes.KEY_LATITUDE, String.valueOf(dadosposicao.getLatitude()));
                        params.put(Constantes.KEY_LONGITUDE, String.valueOf(dadosposicao.getLatitude()));
                        params.put(Constantes.KEY_DTLOG, Funcoes.formatarDataHora(dadosposicao.getDtlog(), "yyyy-MM-dd HH:mm:ss"));
                        params.put(Constantes.KEY_DTRECEBIMENTO, Funcoes.formatarDataHora(dadosposicao.getDtRecebimento(), "yyyy-MM-dd HH:mm:ss"));
                        params.put(Constantes.KEY_PANICO, String.valueOf(dadosposicao.getPanico() ? 1 : 0));
                        params.put(Constantes.KEY_VELOCIDADE, String.valueOf(dadosposicao.getVelocidade()));
                        params.put(Constantes.KEY_HODOMETRO, String.valueOf(dadosposicao.getHodometro()));
                        params.put(Constantes.KEY_DIRECAO, String.valueOf(dadosposicao.getDirecao()));

                    }

                    return params;
                }
            };

            Volley.newRequestQueue(this).add(postRequest);

        }
    }
}

Minha duvida, qual a meneira correta de fazer para enviar a minha lista de aproximadamente 10 posições?
Como sei que a posição foi enviada com sucesso?
Answer: Estão sobrepondo sim sua key, no caso você pode tentar enviar da seguinte forma.
for(int i =0;i<dadosposicoes.lenght;i++){
params.put(Constantes.KEY_LATITUDE+i, dadosposicoes.get(i).getLatitude());
//outros params...}

para recuperar é so voce fazer um for e pegar por posicao.
o correto mesmo seria você trabalhar com JSON, a lib volley da suporte. seus dados em JSON seria algo bem semelhante a isso:
{
"dados": [
    {
        "dispositivo_id":"xxx-yyy",
        "Latitude":"xxxx",
        "longitude":"xxxx",
        "data_recebimento":"xxxx",
        "panico":"xxxx",
        "velocidade":"xxxx",
        "hodometro":"xxxx",
        "direcao":"xxxx"
    },
    {
        "dispositivo_id":"xxx-yyy",
        "Latitude":"xxxx",
        "longitude":"xxxx",
        "data_recebimento":"xxxx",
        "panico":"xxxx",
        "velocidade":"xxxx",
        "hodometro":"xxxx",
        "direcao":"xxxx"
    },
    {
        "dispositivo_id":"xxx-yyy",
        "Latitude":"xxxx",
        "longitude":"xxxx",
        "data_recebimento":"xxxx",
        "panico":"xxxx",
        "velocidade":"xxxx",
        "hodometro":"xxxx",
        "direcao":"xxxx"
    }
]

}
claro é só uma dica.
Comment: Obrigado pela dica, estou usando cakephp para ser o webserver.


Organizar tabs no pyqt4

Question: Boa tarde pessoal!
Qual comando utilizo para "quebrar" a linha de tabs? Gostaria que aparecessem, por exemplo, 3 tabs em uma linha e 3 tabs logo abaixo dela. O esqueleto que tenho referente as tabs é:
    # layout tab
    tabs = qg.QTabWidget()

    # Create tabs
    tab1    = qg.QWidget()
    tab2    = qg.QWidget()
    tab3    = qg.QWidget()
    tab4    = qg.QWidget()
    tab5    = qg.QWidget()
    tab6    = qg.QWidget()

    tabs.addTab(tab1,"Properties")
    tabs.addTab(tab2,"Nodes")
    tabs.addTab(tab3,"Bars")
    tabs.addTab(tab4,"Restrains")
    tabs.addTab(tab5,"Nodal Loads")
    tabs.addTab(tab6,"Dist.Loads")

Comment: Não faz esta atrocidade: http://hallofshame.gp.co.at/tabs.htm
Answer: O QT não tem esse objeto, então, você teria que fazer manualmente:
Crie um layout vertical, coloque um QStackedWidget e vários QTabBars. Você vai ter que manualmente definir métodos pra garantir que só uma aba esteja selecionada em todas as QTabBar e mostrar o conteúdo correto no QStackedWidget.
Dito isso, recomendo que repense a utilização desse tipo de diálogo, que é terrível! Pensa numa janela ruim de mexer:

Organizar tabs no pyqt4


Can I put batch api callbacks in an include file?

Question: I have a .module file that is getting quite lengthy, and I added some batch functionality to it. I put the form and batch callbacks in a separate .inc file, and added the appropriate file directive to the menu array.
I was able to get the form submission to work, but the batch api threw the error Warning: call_user_func_array() expects parameter 1 to be a valid callback, function '_my_batch_callback' not found or invalid function name in _batch_process(). I got this error until I moved the batch callbacks into the .module file.
Is it possible to put the batch callbacks into a separate include file? Or have I just done something wrong?
Answer: Actually, there is a file directive in the batch array. I found it was necessary to include drupal_get_path to fully reference the file's path.
'file' => drupal_get_path('module', 'MY_MODULE') . '/includes/my-batch.inc'


Cannot setup a reverse proxy with Nginx

Question: I'm trying to display my NodeJS application when the user type a specific domain. I already pointed the domain on the server, then I've installed Nginx and I have created a configuration file into:
/etc/nginx/conf.d/myapp.conf

this have the following content:
server {
        listen 80;
        server_name myapp.it www.myapp.it;

        location / {
                proxy_set_header X-Forwarded-For $remote_addr;
                proxy_set_header Host $http_host;
                proxy_pass http://localhost:4568;
        }
}

I restarted Nginx and I executed this command: nginx -t but I got:
nginx: [warn] conflicting server name "myapp.it" on 0.0.0.0:80, ignored
nginx: [warn] conflicting server name "www.myapp.it" on 0.0.0.0:80, ignored

when I visit the domain I get 403 Forbidden, that's because Letsencrypt cannot register a certificate for the conflict above. What I did wrong?
Comment: Use `nginx -T` (uppercase `T`) to view the entire configuration across all included files and identify where the conflicting `server_name` is coming from. Has your editor left a backup file in the `conf.d` directory perhaps.
Answer: You should put the site config files in /etc/nginx/sites-enabled.
To solve your problem, check if you have a default site config in /etc/nginx/sites-enabled and delete it. Then, move your myapp.conf file to /etc/nginx/sites-enabled and restart nginx.
Comment: I don't know very much about node js apps. If each of them listens in different ports then you could add multiple locations entries in the site config, each with a different port. You sure can also add a new site config file for each app. It's up to you.
Comment: You're right! What if I have multiple node js app? Should I create a new conf each time?

Cannot setup a reverse proxy with Nginx


Cannot open office documents using msLaunchUri from Edge

Question: I am trying to create a document explorer targeted for Edge. For that purpose I am using the msLaunchUri method as follows:
navigator.msLaunchUri('ms-word:ofe|u|http://docServerPath/someFolder/document.docx', function() { console.log("success")}, function() { console.log("error")});

However, the document is never opened. I've tried with different types of office documents, but the outcome is always the same. Is there a way to either fix this or to open the documents in a different way?
I am using Win10 and Edge 42.17134.1.0 (EdgeHTML 17.17134).
Comment: Do you try to execute the code from a user interaction or some other way? Browsers have mechanisms to try to prevent opening things when that was not requested by a user interaction.
Answer: Since I don't have the Edge 42 version environment, I have tested your code using Edge 44.18362.1.0 version and Edge 41.16299.1004.0 version, they all will open the documents,
I suggest you check this thread, perhaps the issue is relate to the following registry keys, you could try to remove it.
HKEY_CURRENT_USER\Software\Classes\myprotocol
HKEY_CURRENT_USER\Software\Microsoft\Internet Explorer\ProtocolExecute\myprotocol

If still not working, please try to reset the browser setting. Also, you could try to upgrade the browser version.


How to merge multiple fields into one, across multiple content types?

Question: I'm updating some old Drupal 7 sites, and I need to merge a number of fields across multiple content types.
For example, I have the field_article_body, field_page_body, and field_event_body fields that needs to be merged into the core body field, or the field_article_image, field_page_image, and field_event_image fields that need to be merged into the field_image field.
I am hoping there is some solution which can assist me in combining these fields, or alternatively some SQL magic which an expert can help me with.
Do you have any idea?
Answer: By using Views (to build a list of nodes to be updated) and a combination of Rules and VBO (to mass update such lists) you should be able to perform the merge of those fields.
Refer to my answer to "How to bulk update select list fields?" for an example with way more details about that, which is about a variation of your scenario (ie change the value of an existing field, while you want to "copy" the value of an existing field to the value of a new field).
For your case, this example of a Rules Component (in Rules export format) should be close to one of the Rules Components you'd need for your "field_image":
<code>{ "rules_set_an_initial_value_for_image_field" : {
    "LABEL" : "Set an initial value for image field",
    "PLUGIN" : "rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "USES VARIABLES" : { "node" : { "label" : "Node", "type" : "node" } },
    "IF" : [
      { "entity_has_field" : { "entity" : [ "node" ], "field" : "field_article_image" } }
    ],
    "DO" : [
      { "data_set" : { "data" : [ "node:field-image" ], "value" : [ "field_article_image" ] } }
    ]
  }
}
</code>
Note: by using an approach with modules such as above (instead of SQL magic), you do have the advantage that all possible relatic magic will happen automagically and behind the scenes (eg: create a new revision of such nodes). And it avoids your Drupal database gets corrupted because "you forgot some table".
Comment: Merci (oeps: thank you) @MrPaulDriver, for the accept, and +1 ... About the video in the linked answer: it can also be found at "[Using Rules components with VBO](http://drupal.placeto.be/tutorial/using-rules-components-with-vbo)", where it is located including the correct [attribution](http://creativecommons.org/licenses/by-nc-sa/3.0/) to famous "Johan Falk" (together with dozens of similar links to other commonly known videos from the same author, about Views, Flag, etc).
Comment: Thank you. This was just the answer was looking for. The video mentioned in your linked answer has moved to https://drupalize.me/videos/using-rules-components-vbo?p=1157


c:out JSTL tag doesn't work for me

Question: I've just recently been trying to get into JSTL and I'm experiencing some problems with it..
This is a tag in my hello.JSP:

Greetings, it is now <c:out value="${now}"/>

And it's supposed to display the current time, but the output that I do get is:
Greetings, it is now ${now}

The tag is written from a SpringSource tutorial so it should be correct, but the logic seems to be skipped... don't know why this is.
I have the jstl.jar in a reference library and
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>

is implemented in a separate JSP-file header that is included in the hello.JSP file.
If you haven't guessed I'm a total noob in this environment so the solution may be very simple. If anyone could give me some pointers on what the problem might be I would greatly appreciate it!
Best regards
-Max
Answer: In JSTL, now is not a predefined variable.
In the SpringSource docs you are reading you might have missed where they assigned the variable now a value like new Date(), most likely in a <c:set> tag.  I'm sure you'll find it.
Comment: wow... I feel pretty stupid.. it turned out that in the tutorial they first showed how to display the value of a variable in a view, the c:out tag. The logic behind which declared what "now" was came a bit after.. =P
So you're right Ray, I had just missed it. I wished they would have presented it in the other order though. =)
Comment: Agreed that the tutorial is out of order.  No need to feel stupid about that one.

c:out JSTL tag doesn't work for me


Network connection on Linux

Question: A general question about network connection on Linux : once a network connection goes into time_wait, is it still tied to the process ? Does it still use resources like say filehandle ?
Reason I ask is because once it goes into time_wait, lsof does not report it anymore. I guess that means that the network connection is no longer tied to the process and hence does not count against filehandle limit. Would like to confirm though.
Answer: Your guess is correct. If a connection enters the TIME_WAIT state, it means that the local side has closed the socket, therefore it has already stopped keeping the file descriptor in use.
It does, however, consume entries in the kernel TCP state table. There are a few tunables that you can look up in the tcp(7) man page. If you are only worried about the file descriptor count limit for a single process, however, it does not matter.
Please note that there is a duplicate question here, but I believe that the answer is incorrect.

Network connection on Linux


Asturias Playing Open B

Question: I learning Asturias in this piece we have to play open B after every base notes.
So currently my base notes sounds fine but playing open B is seems to be quite challenging. I am alternating between M and I fingers, alternation is also works fine.
But in between playing the open B notes are seems to be missing i.e my finger just touches the string so any advice or exercise  which may help me ?
Answer: You did not mention which hand is touching and muting the open B string. If you are right handed and it is your right hand make sure you use free strokes and not rest strokes to pluck the strings. If it is your left hand you have to focus on maintaining the curvature of your fingers so the fleshy part of the fingers near the palm don't come too close to the fingerboard. Also it is very important you hold the instrument in the proper way, between the legs with a footstool for your left leg. Practice slowly, focusing on letting the open B string ring true. Here is a video of the piece being played that has very good camera angles. It may help you to watch and make comparisons between you and her. I hope this is helpful to you.

Asturias Playing Open B


ModuleNotFoundError: No module named 'playsound' what to do?

Question: I've been editing this mp3 player, but this error keeps apearing
from tkinter import *
from tkinter import messagebox
import playsound

#making the window
window = Tk()
window.title("button")
window.geometry("350x450+500+200")

#making the song fuction
def song():
    playsound ("lights.mp3")

# making texbox
def InitialMessage():
    name = name_Tf.get()
    mood = mood_Tf.get()

    #mood happy
    if mood == "happy":
        return messagebox.showinfo("message",
                                    f"""Hi! {name}, wellcome.
    may I intrest you with some music?""",
         #making the song executer
         button1 = Button(messagebox,
                        text="yes",
                        command=song,
                        font= ("Comic Sans", 15 )))

I don't have python 2 on the pc anymore, I uninstalled it, I have tried reinstaling playsound, as well as change the interpreter to the recomended, I dunno what to do anymore, please help
Comment: Which command do you type in order to run the script?
Comment: ...and how did you install playsound? Which commands? And are you using a virtual environment? Because the same Python you use to install playsound should be the same Python you use to run your app.
Comment: I'm using the comand prompt of windows for both
Answer: Try importing playsound with PIP

pip install playsound

And include in your code
from playsound import playsound
playsound('/path/to/a/sound/file/you/want/to/play.mp3')