text:
Q: Unable to start passenger watchdog but passenger installed I want to setup nginx with passenger support on ubuntu 12.04 VM (vagrant box). Therefore I created the following chef cookbook recipe (https://github.com/i42n/wrapper-nginx-passenger/blob/master/recipes/default.rb):
#
# Cookbook Name:: wrapper-nginx-passenger
# Recipe:: default
#
# Copyright 2014, YOUR_COMPANY_NAME
#
# All rights reserved - Do Not Redistribute

apt_repository 'nginx-passenger' do
  uri          'https://oss-binaries.phusionpassenger.com/apt/passenger'
  distribution node['lsb']['codename']
  components   ['main']
  keyserver    'keyserver.ubuntu.com'
  key          '561F9B9CAC40B2F7'
end

# install nginx which contains passenger support
package "nginx-extras"
package "passenger"

# define nginx service as the nginx::passenger recipe restarts the service
# and fails if the service does not exist
service 'nginx' do
  supports :status => true, :restart => true, :reload => true
  action   :start
end

# installs the passenger gem
include_recipe "nginx::passenger"

# create server config template in nginx config directory
template "/etc/nginx/sites-available/plantasy" do
  source "plantasy.erb"
  mode 0644
  owner "root"
  group "root"
end

# symlink the config to the active sites directory
link "/etc/nginx/sites-enabled/plantasy" do
  to "/etc/nginx/sites-available/plantasy"
end

It follows the passenger installation guide from here: https://www.phusionpassenger.com/documentation/Users%20guide%20Nginx.html#install_add_apt_repo
However if I try to start nginx I get the following error:
vagrant@vagrant:/etc/nginx/conf.d$ sudo service nginx restart
 * Restarting nginx nginx
nginx: [alert] Unable to start the Phusion Passenger watchdog because its executable (/usr/local/rvm/rubies/ruby-2.1.2/lib/ruby/gems/2.1.0/gems/passenger-4.0.45/buildout/agents/PassengerWatchdog) does not exist. This probably means that your Phusion Passenger installation is broken or incomplete, or that your 'passenger_root' directive is set to the wrong value. Please reinstall Phusion Passenger or fix your 'passenger_root' directive, whichever is applicable. (-1: Unknown error)
   ...done.

This actually seems a common error if nginx has not been compiled correctly with passenger support. However if I check the nginx modules my nginx does have passenger support:
vagrant@vagrant:~$ nginx -V
nginx version: nginx/1.6.0
TLS SNI support enabled
configure arguments: --with-cc-opt= --with-ld-opt= --prefix=/usr/share/nginx --conf-path=/etc/nginx/nginx.conf --http-log-path=/var/log/nginx/access.log --error-log-path=/var/log/nginx/error.log --lock-path=/var/lock/nginx.lock --pid-path=/var/run/nginx.pid --http-client-body-temp-path=/var/lib/nginx/body --http-fastcgi-temp-path=/var/lib/nginx/fastcgi --http-proxy-temp-path=/var/lib/nginx/proxy --http-scgi-temp-path=/var/lib/nginx/scgi --http-uwsgi-temp-path=/var/lib/nginx/uwsgi --with-debug --with-ipv6 --with-http_ssl_module --with-http_stub_status_module --with-http_realip_module --with-http_addition_module --with-http_dav_module --with-http_flv_module --with-http_geoip_module --with-http_gzip_static_module --with-http_image_filter_module --with-http_mp4_module --with-http_perl_module --with-http_random_index_module --with-http_realip_module --with-http_secure_link_module --with-http_spdy_module --with-http_stub_status_module --with-http_ssl_module --with-http_sub_module --with-http_xslt_module --with-ipv6 --with-mail --with-mail_ssl_module --add-module=/tmp/buildd/nginx-1.6.0/debian/modules/headers-more-nginx-module --add-module=/tmp/buildd/nginx-1.6.0/debian/modules/nginx-auth-pam --add-module=/tmp/buildd/nginx-1.6.0/debian/modules/nginx-cache-purge --add-module=/tmp/buildd/nginx-1.6.0/debian/modules/nginx-dav-ext-module --add-module=/tmp/buildd/nginx-1.6.0/debian/modules/nginx-development-kit --add-module=/tmp/buildd/nginx-1.6.0/debian/modules/nginx-echo --add-module=/tmp/buildd/nginx-1.6.0/debian/modules/ngx-fancyindex --add-module=/tmp/buildd/nginx-1.6.0/debian/modules/nginx-http-push --add-module=/tmp/buildd/nginx-1.6.0/debian/modules/nginx-lua --add-module=/tmp/buildd/nginx-1.6.0/debian/modules/nginx-upload-progress --add-module=/tmp/buildd/nginx-1.6.0/debian/modules/nginx-upstream-fair --add-module=/tmp/buildd/nginx-1.6.0/debian/modules/ngx_http_substitutions_filter_module --add-module=/tmp/buildd/nginx-1.6.0/debian/modules/passenger/ext/nginx

The error is actually correct. The file/folder passenger is looking for on nginx startup is not present:
vagrant@vagrant:/etc/nginx/conf.d$ ls -l /usr/local/rvm/rubies/ruby-2.1.2/lib/ruby/gems/2.1.0/gems/passenger-4.0.45
total 196
-rw-r--r--  1 vagrant root 80232 Jul  7 13:38 CHANGELOG
-rw-r--r--  1 vagrant root 15919 Jul  7 13:38 CONTRIBUTING.md
-rw-r--r--  1 vagrant root  1035 Jul  7 13:38 CONTRIBUTORS
-rw-r--r--  1 vagrant root   363 Jul  7 13:38 INSTALL.md
-rw-r--r--  1 vagrant root  1056 Jul  7 13:38 LICENSE
-rw-r--r--  1 vagrant root  2880 Jul  7 13:38 README.md
-rw-r--r--  1 vagrant root  1814 Jul  7 13:38 Rakefile
-rw-r--r--  1 vagrant root  2345 Jul  7 13:38 Vagrantfile
drwxr-xr-x  2 vagrant root  4096 Jul  7 13:38 bin
drwxr-xr-x  2 vagrant root  4096 Jul  7 13:38 build
-rwxr-xr-x  1 vagrant root   287 Jul  7 13:38 configure
drwxr-xr-x  4 vagrant root  4096 Jul  7 13:38 debian.template
drwxr-xr-x  4 vagrant root  4096 Jul  7 13:38 dev
drwxr-xr-x  5 vagrant root  4096 Jul  7 13:38 doc
drwxr-xr-x  2 vagrant root  4096 Jul  7 13:38 download_cache
drwxr-xr-x 10 vagrant root  4096 Jul  7 13:38 ext
drwxr-xr-x  3 vagrant root  4096 Jul  7 13:38 helper-scripts
drwxr-xr-x  3 vagrant root  4096 Jul  7 13:38 lib
drwxr-xr-x  2 vagrant root  4096 Jul  7 13:38 man
drwxr-xr-x  3 vagrant root  4096 Jul  7 13:38 node_lib
-rw-r--r--  1 vagrant root  6514 Jul  7 13:38 npm-shrinkwrap.json
-rw-r--r--  1 vagrant root   722 Jul  7 13:38 package.json
-rw-r--r--  1 vagrant root  1243 Jul  7 13:38 passenger.gemspec
drwxr-xr-x  4 vagrant root  4096 Jul  7 13:38 resources
drwxr-xr-x  2 vagrant root  4096 Jul  7 13:38 rpm
drwxr-xr-x 10 vagrant root  4096 Jul  7 13:38 test

I have a default nginx.conf and /etc/nginx/conf.d/passenger.conf looks like this:
vagrant@vagrant:/etc/nginx/conf.d$ cat /etc/nginx/conf.d/passenger.conf
passenger_root /usr/local/rvm/rubies/ruby-2.1.2/lib/ruby/gems/2.1.0/gems/passenger-4.0.45;
passenger_ruby /usr/local/rvm/rubies/ruby-2.1.2/bin/ruby;
passenger_max_pool_size 6;
passenger_spawn_method smart-lv2;
passenger_buffer_response on;
passenger_min_instances 1;
passenger_max_instances_per_app 0;
passenger_pool_idle_time 300;
passenger_max_requests 0;

If I remove the passenger.conf nginx starts without errors and serves the default test page fine. As expectable passenger does not work.
My passenger app nginx config looks like this:
vagrant@vagrant:~$ cat /etc/nginx/sites-enabled/plantasy
# Only for development purposes.
# For production environment, set it accordingly (i.e. production)
# Remove this line when you upload an actual application.
# For * TESTING * purposes only.
passenger_app_env development;

server {
  listen 8080;
  server_name example.com;
  passenger_enabled on;
  passenger_ruby /usr/local/rvm/rubies/ruby-2.1.2/bin/ruby;
  root /home/vagrant/app/public;
}

If I try to access this page, I get a 403:
vagrant@vagrant:~$ curl localhost:8080

<title>403 Forbidden</title>

403 Forbidden

nginx/1.6.0

Ruby is installed correctly:
vagrant@vagrant:~$ ruby -v
ruby 2.1.2p95 (2014-05-08 revision 45877) [x86_64-linux]

Also the passenger gem is installed.
vagrant@vagrant:~$ gem list passenger

*** LOCAL GEMS ***

passenger (4.0.45)

I really do not know what's wrong. I checked out this thread but as you can see above, I have nginx present with passenger support. It's just the passenger binary missing?
Any ideas how to fix this?
And before anyone suggests it: I do not want to compile nginx myself. I want to use the version from the apt repository as it speeds up performance on vagrant VM setup very much.

A: Your passenger_root directive is incorrect. You can discover the correct value for it by following the guide here:
https://www.phusionpassenger.com/documentation/Users%20guide%20Nginx.html#inserting_passenger_root_for_apt

A: Check passenger-install-nginx-module is properly installed.
By 'which passenger-install-nginx-module'
if not installed, try with:
rvmsudo passenger-install-nginx-module

This is for rvm users. Will solve problem


text:
Q: maximal vectors $\mathcal{H}$ stands for an  Hilbert space over $\mathbb{K}=\mathbb{R}$ or $\mathbb{C}$, with inner product $\langle{\cdot}| {\cdot}\rangle$ and the norm $\|{\cdot}\|$ and let $\mathcal{B}(\mathcal{H})$ the algebra of all bounded linear operators from $\mathcal{H}$ to $\mathcal{H}$.
I look for an example of maximal vector $x\in \mathcal{H}$ for  $T\in\mathcal{B}(\mathcal{H})$ i.e. a vector $x$ satisfying $\|x\|=1$ and $\|Tx\|=\|T\|$.

A: consider the simple example where $T$ is the identity operator.
Then every vector that satisfies $\| x\|=1$ is a maximal vector, because the operator norm of the identity operator is $1$.

A: Take the  shift operator $S:l^2 \rightarrow l^2$ such that $S(x_1,x_2....)=(0,x_1,x_2...).$
Then $||S||_2=1$ and $||Se_1||_2=1$ a where $e_1=(1,0..0...)$ and $||e_1||_2=1$
Also you can take shift the operator $T:l^2 \rightarrow l^2$ such that $T(x_1,x_2...)=(x_2,x_3....)$ and the vector $e_2=(0,1,0..0..)$
Now in the finite dimensional case take the hilbert space $\mathbb{R}^2$ with the usual inner product and the bounded linear operator $T:\mathbb{R}^2 \rightarrow \mathbb{R}^2$ such that $T(a,b)=(a,0)$
You can easily prove that $||T||_2=1$ and $||Te_1||_2=1$ where $e_1=(1,0)$ and $||e_1||_2=1$
Hope this helps.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Toggling panel visibility isn't working when they are stacked I have a form that has two views. These views are controlled by radio buttons on top of the form.
Here is the program:
http://dl.dropbox.com/u/41629841/DataCalculator/DataCalc1.PNG
Notice how the Radio button for Number Converter is selected.
Here is what it looks like when you select the Text Converter radio button:
http://dl.dropbox.com/u/41629841/DataCalculator/DataCalc2.PNG
That isn't right. I have it set to hide the panel containing the number converter and show the one containing the text converter when you click that one. It hides the number converter but doesn't show the text converter.
Here is a picture of the text converter panel:
http://dl.dropbox.com/u/41629841/DataCalculator/DataCalc4.PNG
Here is the relevant code:
Private Sub frmCalculator_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
    rdoNumberConverter.Checked = True
End Sub

Private Sub rdoTextConverter_Click(sender As Object, e As System.EventArgs) Handles rdoTextConverter.Click
    pnlTextConverter.Visible = True
    pnlNumberConverter.Visible = False
End Sub

Private Sub rdoNumberConverter_Click(sender As Object, e As System.EventArgs) Handles rdoNumberConverter.Click
    pnlNumberConverter.Visible = True
    pnlTextConverter.Visible = False
End Sub

Everything seems right and I can't figure out why the text converter doesn't show up. I've determined that it has something to do with the fact that both of the panels are right on top of each other because when I move them apart, the visibility toggling works perfectly.
Here are the supporting pictures:
http://dl.dropbox.com/u/41629841/DataCalculator/DataCalc5.PNG
http://dl.dropbox.com/u/41629841/DataCalculator/DataCalc6.PNG
So how do I make it work when they are on top of each other?
I tried using BringToFront() and SendToBack() to make sure the visible panel is in the front and it didn't make a difference.

A: Make sure the TextConverter panel isn't "inside" the NumberConverter panel.
From the designer, move them into different places so that they do not overlap at all.
Then in code, move them into place:
textConverterPanel.Location = numConvertPanel.Location

Your visible, not visible toggling should work then.

A: The issue is the panels becoming embedded, as pointed out by @LarsTech.  This occurs if you use the GUI to move them to the same location.
If you want to overlap them at design time, create the second panel in a different location.  Then in the Properties of the panel in the final location, copy the Location, and paste it into the Location property of the second panel.  This will move it to the proper location in the Designer without embedding one into another.  This can be repeated for as many additional panels as needed.


text: Q: WooCommerce Print Order Confirmation PDF Our business uses the Name Your Price tool in WooCommerce to allow our customers to pay their invoices. However, there is no way for them to print an order confirmation or some kind of receipt on the front-end of our site. I have a plugin that sends this link to our customer's email and allows us to print in the admin dashboard, but I'd also like to include it as a button or link on the front-end too. Is this possible?


text:
Q: Cannot load media and I get "PHP Warning: Invalid argument supplied for foreach(" if I don't have active debug mode, I can't see any media in back end (in Media menu or even as in created gallery in a post editor). When I turn on debug mode:
define('WP_DEBUG', true);

// Enable Debug logging to the /wp-content/debug.log file
define('WP_DEBUG_LOG', true);

// Disable display of errors and warnings
define('WP_DEBUG_DISPLAY', false);
@ini_set('display_errors',0);if ( !defined('ABSPATH') )
    define('ABSPATH', dirname(__FILE__) . '/');

I've got following error. But system file plugin.php ends at line 992 or so. Any ideas what can cause this problem and how to solve it? Thanks a lot, it's my custom theme.
[29-Apr-2015 22:23:50 UTC] PHP Warning:  Invalid argument supplied for foreach() in /data/web/virtuals/51889/virtual/www/domains/demo.kybernaut.cz/detsky-svet-masa/wp-admin/includes/plugin.php on line 1422
[29-Apr-2015 22:23:50 UTC] PHP Warning:  Invalid argument supplied for foreach() in /data/web/virtuals/51889/virtual/www/domains/demo.kybernaut.cz/detsky-svet-masa/wp-admin/includes/plugin.php on line 1422
[29-Apr-2015 22:23:50 UTC] PHP Warning:  Invalid argument supplied for foreach() in /data/web/virtuals/51889/virtual/www/domains/demo.kybernaut.cz/detsky-svet-masa/wp-admin/includes/plugin.php on line 1422
[29-Apr-2015 22:23:51 UTC] PHP Warning:  Invalid argument supplied for foreach() in /data/web/virtuals/51889/virtual/www/domains/demo.kybernaut.cz/detsky-svet-masa/wp-admin/includes/plugin.php on line 1422
[29-Apr-2015 22:23:51 UTC] PHP Warning:  Invalid argument supplied for foreach() in /data/web/virtuals/51889/virtual/www/domains/demo.kybernaut.cz/detsky-svet-masa/wp-admin/includes/plugin.php on line 1422
[29-Apr-2015 22:23:51 UTC] PHP Warning:  Invalid argument supplied for foreach() in /data/web/virtuals/51889/virtual/www/domains/demo.kybernaut.cz/detsky-svet-masa/wp-admin/includes/plugin.php on line 1422

It looks like this part is causing troubles:
//remove from menu
function remove_posts_menu() {
    remove_menu_page('edit.php');
    remove_menu_page('edit.php?post_type=page');
    remove_menu_page('edit-comments.php' );
}
add_action('admin_init', 'remove_posts_menu');

A: @TheDeadMedic was right, in my second code snippet, admin_init should be admin_menu. That solved my problem, thanks a lot to all of you!
Corrected code:
//remove from menu
function remove_posts_menu() {
    remove_menu_page('edit.php');
    remove_menu_page('edit.php?post_type=page');
    remove_menu_page('edit-comments.php' );
}
add_action('admin_menu', 'remove_posts_menu');


text:
Q: Make PHP array from numerical data in MySQL table and multiply it Good day,
I'm a noob at PHP and MySQl. Looking to be pointed in the right direction.
I have a MySql table with 5 columns. Each column represents a specific set of data. All numerical.
I want to write PHP code which takes each value in a single column and puts it into an array that I can then modify.
I don't know how to get each column as a separate array. Should I get an array of all the rows and then do something extra to separate each of the 5 numbers in each row into 5 separate arrays?
**

require_once 'login.php';

    echo $db;
    $conn = mysqli_connect($hn,$un,$pw,$db);
    if (!$conn) {
        echo "Error: Unable to connect to MySQL." . PHP_EOL;
        echo "Debugging errno: " . mysqli_connect_errno() . PHP_EOL;
        echo "Debugging error: " . mysqli_connect_error() . PHP_EOL;
    exit;
      }

$query = "SELECT xox FROM tablex WHERE id = '1'";
$result = $conn->query($query);
if(!$result) die ("Database access failed: " . $conn->error);

$rows = mysqli_fetch_row($result);

while($rows){
    echo $rows['index'];

}

echo $rows[0];

?>

A: $statement = **yourDatabaseConnection**->query('SELECT column1 FROM table');
$datas = $statement->fetch();

$datas will be an array of your column1 datas

A: Try reviewing the php documentation, here is a good place to start...php:mysql_fetch_row
Take a look at the example below, if is not what you looking for, please edit your question and provide the approach you are taking (your code) so that we have a better understanding where you are having issues.

<?php
$result = mysql_query("SELECT id,email FROM people WHERE id = '42'");
if (!$result) {
    echo 'Could not run query: ' . mysql_error();
    exit;
}
$row = mysql_fetch_row($result);

echo $row[0]; // 42
echo $row[1]; // the email value
?>


text:
Q: How to send an email automatically to user when we enter them in DE We want to send an email automatically to users when we enter them in DE.
We tried to do it using triggered send but unable to do like how and where should we write the logic.


text:
Q: how to avoid parent view controller rotating I have parent viewcontroller - in portrait.
I have child viewcontroller - in landscape.
When child viewcontroller is dismissed parent viewcontroller remains in landscape- which it should not do. Please advice :=)
These are the settings:
deployment info
My app delegate
-(UIInterfaceOrientationMask)application:(UIApplication *)application    supportedInterfaceOrientationsForWindow:(UIWindow *)window {
   UIViewController* topVC = [self getTopController];
     if ([topVC isKindOfClass: [childVideoViewController class]]) {
         return UIInterfaceOrientationMaskLandscape;
     }
     return UIInterfaceOrientationMaskPortrait;
}

-(UIViewController*) getTopController{ UIViewController *topViewController =      [UIApplication sharedApplication].keyWindow.rootViewController;

    while (topViewController.presentedViewController) {
        topViewController = topViewController.presentedViewController;
    }
    return topViewController;
}

A: When You back from child view controller you should call
Create a method in your child view controller and implement this
- (void)setScreenOrientation:(UIInterfaceOrientation)orientation
{
UIDeviceOrientation deviceOrientation = (UIDeviceOrientation) orientation;
[[UIDevice currentDevice] setValue: [NSNumber numberWithInteger: deviceOrientation] forKey:@"orientation"];
}

Call this from child view before dismiss:
    [self setScreenOrientation:UIInterfaceOrientationPortrait];

    [self dismissViewControllerAnimated:YES completion:nil];


text:
Q: Javascript code killing my websites Google Page Speed Score The following code is somehow making my Google Page Speed Score drop by 10 points. It resides in the footer of a WordPress website between script tags with no enqueuing. The code makes the navigation behave more like a burger menu on mobile device.
<script>
(function() {
var $j = jQuery.noConflict();
$j(document).ready(function() {
  $j('body').addClass('js');
  var $menu = $j('#menu'),
    $menulink = $j('.menu-link');

$menulink.click(function() {
  $menulink.toggleClass('active');
  $menu.toggleClass('active');
  return false;
});});

})();
 </script>

Can anyone see any glaring errors with the code or are there any other recommendations.


text:
Q: How to get values from first column of excel file as array? Hi I want to get values from first column of excel file as array.
Already I wrote this code-
import os
import pandas as pd

for file in os.listdir("./python_files"):
    if file.endswith(".xlsx"):
        df = pd.read_excel(os.path.join("./python_files", file))
        print(df.iloc[:,1])

What i got in output now
0       172081
1       163314
2       173547
3       284221
4       283170
         ...
3582    163304
3583    160560
3584    166961
3585    161098
3586    162499
Name: Organization CRD#, Length: 3587, dtype: int64

What I whish to get
172081
163314
173547
284221
283170
  ...
163304
160560
166961
161098
162499

Can somebody help? Thanks :D

A: You will just need to use the tolist function from pandas:
import os
import pandas as pd

for file in os.listdir("./python_files"):
    if file.endswith(".xlsx"):
        df = pd.read_excel(os.path.join("./python_files", file))
        print(df.iloc[:,1].tolist())

Output
172081
163314
173547
284221
283170
  ...
163304
160560
166961
161098
162499

A: As an array:
df.iloc[:,1].values

As a list:
df.iloc[:,1].values.tolist()


text:
Q: Can I use git to replay changes for projects that use media assets rather than program source code? So while waiting for a project to build I like to run gource and see a fun video of my team building the project over time. While I was watching me and my team fly around editing and changing the file tree a coworker who is on our media team loved the visual representation and immediately asked how I could do this for his team's media projects ( documentaries, short videos, poster design projects ) which are worked on as a team and everyone edits files individually and then pushes them up to a central server on the LAN.
I know git would freak every file change because to it the entire file is new every time they say export the video to the LAN or anything like that. But would a quick git repo be possible for a media team? How much overhead vs pay off would they expect?

A: Pro and Cons:
For:

*

*will store different versions over time

*will still be able to use compression to reduce file size for older versions.

*will enable different developers to share one code (or asset in this case) base.

*will make sure any common files stay with 1 version.

*will track who touches which files.

*can use the git-fat tool https://github.com/jedbrown/git-fat to not store the files in git but use $ git fat pull when you want to get one

*will be the same tool that many people will already know form using it for code.

Against:

*

*different versions of media assets will probably need to be stored in their (compressed) entirety.

*standard 'git difference' functionality will not work on media which is not code without customization.

*people will need training in at least a subset of git commands and/or a git gui

*will require all users to get all files, which for media, can mean a huge amount of data

The last point, also mentioned by Esben Skov Pedersen, is possibly a good reason to use SVN for the media.  This would be a judgement call.  With SVN you get the huge advantage of being able to get individual files and directories instead of the complete repository as with git.  The downside is that its an older technology with some different philosophies and and if folks use git at all (either concurrently or at other times) they will find the different philosophies and different syntax (or, worst, same syntax, different meaning!) confusing.

A: Git is not very will suited for this as evidenced by the fact that currently at least three different extensions exist to handle this problem git-fat, git-annex, git-media.
Svn also have the possibility to only check out only a sub folder of the repository which git was explicitly designed to NOT to do.
Since git is distributed all clones must contain all versions of all blobs which will be large for binary files since they don't compress or diff well. Svn is centralized so a checkout can checkout only the recent version.
I recommend using svn or using one of the git extensions.


text:
Q: Pivot/Transpose data in Coldfusion Query of Queries I have a COLDFUSION subquery containing the data to be displayed in an HTML table.
The data needs to be pivoted before displaying. I tried pivoting the subquery but its throwing an error of 'containing ( in subquery'. After going through various forums, looks like all oracle queries do not work on subqueries. I tried doing this http://www.houseoffusion.com/groups/cf-talk/thread.cfm/threadid:46838 way as well but still the same result.
Although, I have a solution which is very crude of writing different queries on contract, datetime and then looping through each of them to get the values and displaying in HTML.
select * from
(select datetime, contract, VALUE from Q_Table_Data)
t pivot (max(VALUE) for CONTRACT in ('A', 'B', 'C'.......))

Please let me know if there is a better way to do the same.
Query Data:

CONTRACT    DATETIME            VALUE
    A   28/02/2014 00:30:00      224
    B   28/02/2014 00:30:00      896.9791123
    C   28/02/2014 00:30:00      -1950.0432
    D   28/02/2014 00:30:00      67.11
    E   28/02/2014 00:30:00      28.81819
    F   28/02/2014 00:30:00      80.40048
    G   28/02/2014 00:30:00      257.4114
    A   28/02/2014 01:00:00      224
    B   28/02/2014 01:00:00      814.3872992
    C   28/02/2014 01:00:00     -1879.6858
    D   28/02/2014 01:00:00      67.09
    E   28/02/2014 01:00:00      29.996185
    F   28/02/2014 01:00:00      79.32327
    G   28/02/2014 01:00:00      277.9678
    A   28/02/2014 01:30:00      224
    B   28/02/2014 01:30:00      791.0937311
    C   28/02/2014 01:30:00     -1761.6632

EXPECTED Data:

    Datetime    A          B           C      D        E           F          G
28/02/2014 0:30 224 896.9791123 -1950.0432  67.11   28.81819    80.40048    257.4114
28/02/2014 1:00 224 814.3872992 -1879.6858  67.09   29.996185   79.32327    277.9678
28/02/2014 1:30 224 791.0937311 -1761.6632  67.05   29.257648   79.97122    271.7564


text:
Q: Is there a way I can see the payout history in appstore connect? Is there a way to see the payout history in appstore connect? I have tried looking in financial reports, but I can only get reports per month.

A: From Stack Overflow:

*

*https://stackoverflow.com/questions/4996656/itunes-connect-check-total-sales

From the Apple User Guide for the Financial Reports (available at bottom of iTunes Connect page):

We do not store or regenerate the data after the periods have expired
    (14 rolling days and 13 rolling weeks); you will need to download and
    store this data on a regular basis if you intend to use it in the
    future.


text:
Q: DB design while designing the system Recently we had a discussion if rough DB schema (high level tables and columns) design should be part of system design phase or not.
We have two confronting approaches in the company.
Let's assume System Design consists of designing Queues, Lambdas, integration with other microservices, etc.
Approach 1)
In system design we should also include (at least in rough idea) what tables should be in DB, with relations, and normalization.
Approach 2)
During system design we should just state that DB is there, and that's it. Later DB schema will naturally evolve after logic is implemented and needs to be persisted.
What do you think?

A: It is never wrong to have a rough idea of what your goals are, at any stage of design, as long as it is a rough idea, a concept on a piece of paper, nothing engraved in stone. You could also envision certain tables and attributes if it helps you to get a clearer picture. But make sure everyone in the team takes this as what it is, and especially what it is not: it is not a blueprint of what must be build afterwards.
When it comes to table design with attributes, relations and normalization, it is a good idea to only implement exactly the pieces one needs for the current iteration at the database, for supporting the persistence required for the use case or user story one is planning for the next release, and nothing more, and nothing just because it was in the former concept.
Often it turns out that the former "vision" was roughly correct, but the details are quite different, so the team will be happy that it won't become necessary to fix too many of those differences at the implementation level.
So in short: the two alternatives presented in your question don't need to be at odds when you take the right point of view.

A: I think a data model is an essential part of most designs. This means you have expressed the major entities and their relationships in the system you are designing. How is a real world problem and solution mapped to a computer program? You'll quickly fail when working in a team if you go into coding without having reached clarity on how you are going to solve the problem.
When I read database tables, columns, these are implementation artifacts. There is no need to write this all out. You note down there is a persistence layer needed.
There are couple exceptions. Sometimes the data structures are dictated by existing designs. Sometimes they are generic, like log files. In an exploratory design, the may not be enough information available. But they are never 'obvious' - any two developers will write vastly different implementations when it is 'obvious' ;-)


text:
Q: Resizing with handles in interact.js + SVG In this jsFiddle I have an SVG rect that is resized with interact.js. This works fine, however I need to add resize handles n/ne/e/se/s/sw/w/nw, 8x8 pixel squares at each point. These handles should be used to resize the rect (instead of dragging the rect sides).
I found examples in HTML, not SVG, for example here, but I couldn't figure out how to make this work in SVG instead of HTML. Any help will be greatly appreciated.
var svg = document.getElementById('mysvg');
var rect = document.createElementNS("http://www.w3.org/2000/svg", "rect");
svg.appendChild(rect);
rect.setAttribute('x', 100);
rect.setAttribute('y', 100);
rect.setAttribute('width', 100);
rect.setAttribute('height', 100);
rect.setAttribute('class', 'resize-me');
rect.setAttribute('stroke-width', 2);
rect.setAttribute('stroke', 'white');
rect.setAttribute('fill', 'grey')

interact('.resize-me')
    .resizable({
        edges: { left: true, right: true, bottom: true, top: true }
    })
    .on('resizemove', function(event) {
        var target = event.target;
        var x = (parseFloat(target.getAttribute('endx')) || 0)
        var y = (parseFloat(target.getAttribute('endy')) || 0)

        target.setAttribute('width', event.rect.width);
        target.setAttribute('height', event.rect.height);

        x += event.deltaRect.left
        y += event.deltaRect.top
        target.setAttribute('transform', 'translate(' + x + ', ' + y + ')')

        target.setAttribute('endx', x)
        target.setAttribute('endy', y)
    });

A: Okay, done. Take a look:

const svg = document.getElementById('mysvg');
const rect = document.createElementNS("http://www.w3.org/2000/svg", "rect");
const group = document.createElementNS("http://www.w3.org/2000/svg", "g");

svg.appendChild(group);
group.appendChild(rect);
group.setAttribute('class', 'resize-me');

rect.setAttribute('x', 100);
rect.setAttribute('y', 100);
rect.setAttribute('width', 100);
rect.setAttribute('height', 100);
rect.setAttribute('stroke-width', 2);
rect.setAttribute('stroke', 'white');
rect.setAttribute('fill', 'grey');

// Create the handles
const handles = [];
for (let i = 0; i < 8; i++) {
  const handle = document.createElementNS("http://www.w3.org/2000/svg", "rect");

  handle.setAttribute('width', 8);
  handle.setAttribute('height', 8);
  handle.setAttribute('stroke-width', 1);
  handle.setAttribute('stroke', 'white');
  handle.setAttribute('fill', 'black');

  handles.push(handle);
  group.appendChild(handle);
}

// Manually assign them their resize duties (R->L, T->B)
handles[0].classList.add('resize-top', 'resize-left');
handles[1].classList.add('resize-top');
handles[2].classList.add('resize-top', 'resize-right');
handles[3].classList.add('resize-left');
handles[4].classList.add('resize-right');
handles[5].classList.add('resize-bottom', 'resize-left');
handles[6].classList.add('resize-bottom');
handles[7].classList.add('resize-bottom', 'resize-right');

// This function takes the rect and the list of handles and positions
// the handles accordingly
const findLocations = (r, h) => {
  const x = Number(r.getAttribute('x'));
  const y = Number(r.getAttribute('y'));
  const width = Number(r.getAttribute('width'));
  const height = Number(r.getAttribute('height'));

  // Important these are in the same order as the classes above
  let locations = [
    [0, 0],
    [width / 2, 0],
    [width, 0],
    [0, height / 2],
    [width, height / 2],
    [0, height],
    [width / 2, height],
    [width, height]
  ];

  // Move each location such that it's relative to the (x,y) of the rect,
  // and also subtract half the width of the handles to make up for their
  // own size.
  locations = locations.map(subarr => [
    subarr[0] + x - 4,
    subarr[1] + y - 4
  ]);

  for (let i = 0; i < locations.length; i++) {
    h[i].setAttribute('x', locations[i][0]);
    h[i].setAttribute('y', locations[i][1]);
  }
}

interact('.resize-me')
  .resizable({
    edges: {
      left: '.resize-left',
      right: '.resize-right',
      bottom: '.resize-bottom',
      top: '.resize-top'
    }
  })
  .on('resizemove', function(event) {
    // Resize the rect, not the group, it will resize automatically
    const target = event.target.querySelector('rect');

    for (const attr of ['width', 'height']) {
      let v = Number(target.getAttribute(attr));
      v += event.deltaRect[attr];
      target.setAttribute(attr, v);
    }

    for (const attr of ['top', 'left']) {
      const a = attr == 'left' ? 'x' : 'y';
      let v = Number(target.getAttribute(a));
      v += event.deltaRect[attr];
      target.setAttribute(a, v);
    }

    findLocations(rect, handles);
  });

findLocations(rect, handles);
svg {
  width: 100%;
  height: 240px;
  background-color: #2e9;
  -ms-touch-action: none;
  touch-action: none;
}

body {
  margin: 0;
}
<script src="https://cdn.jsdelivr.net/npm/interactjs@latest/dist/interact.min.js"></script>
<svg id="mysvg"></svg>

This works by taking advantage of Interact.js's support for using separate elements as handles, as mentioned in their docs here, as well as the nifty fact that you're using SVG instead of HTML. This means that you don't have to worry about using a CSS transform. Instead, you can just move the rect's x and y, and the calculations become quite a bit simpler.
The only easy-to-miss change I had to make was that I had to put the rectangle and the handles into a group. This is because Interact.js will only let you use a child element as a handle for resizing. This means the listener is on the group, which resizes the rectangle within itself (and then, of course, causes the group to grow, since they match the size of their children).
Let me know if I've missed anything.


text:
Q: Refresh element including attributes I would like to refresh a <data> element every second incuding it's attributes:
<data id="one" data-status="offline"></data>

I tried to use the .load() method:
setInterval(function() {
    $(#one).load(page.php #one, function() {
        if($(#one).data("status") == "online"){
            alert("online!");
            return false; //stop interval(?)
        } else {
            alert("offline!");
        }
    });
}, 1000);

but its not working properly.
The main problem is that the  element is refreshed as a child like this:
 <data id="one" data-status="offline"><data id="one" data-status="online"></data></data>

Your help is greatly appreciated,

A: Try using this...
document.getElementById('one').reload();

might work...


text:
Q: retain certain file using .gitignore I think I'm using .gitignore wrongly. I try to retain my config/db.js to have 2 version, one is to connect to localhost db on my developement environment, one is to connect to live db.
I created .gitignore file and put in config/db, so that I can achieve that. I commit and push everything is working ; but when I put, someone config/db.js got overwritten. What's wrong?

A: you have to remove config/db.js from git and then ignore it
$ git rm --cached config/db.js
$ echo "config/db.js" >> .gitignore


text:
Q: Custom Cell is never nil (NOT using storyboard) at the Moment i have the following classes:

My Problem is that my Custom Cell Class "GTNewsCustomCell" is never called, i set some breakpoints in the .m file but nothing happend, than i realized that in my "cellForRowAtIndexPath" the cell is never nil!
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

static NSString *CellIdentifier1 = @"NewsCell";

GTNewsCustomCell *newsCell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier1];

if(newsCell == nil){

newsCell = [[GTNewsCustomCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier1];

}

newsCell.titleLabel.text = [[self.newsList objectAtIndex:indexPath.section]objectForKey:@"title"];
NSAttributedString *attString = [[NSAttributedString alloc]initWithString:[[self.newsList objectAtIndex:indexPath.section]objectForKey:@"previewMessage"]];

newsCell.messageTextView.attributedText = attString;

return newsCell;

}
And here is a little part of my Code from my GTNewsCustomCell.m:
- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
if (self) {
    // Initialization code

    self.messageTextView.textColor = [UIColor blackColor];
    self.messageTextView.backgroundColor = GTDefaultTextBackgroundColor;
    self.messageTextView.editable = NO;
    self.messageTextView.userInteractionEnabled = NO;

    self.messageTextView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;

    NSString *htmlTag = @"<b></b>";
    NSString *html = [NSString stringWithFormat:@"%@%@",htmlTag,self.messageTextView.attributedText];

    NSData *data = [html dataUsingEncoding:NSUTF8StringEncoding];

    CGFloat fontSizeMultiplier = 1.1;
    CGFloat const DTCoreTextDefaultFontSize = 12.0;
    NSString * fontName = @"Helvetica";
    DTCSSStylesheet* css;

    if (SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"7.0")){

        css = [[DTCSSStylesheet alloc] initWithStyleBlock:@"ul li{padding-left: -10px;}"];

        NSMutableDictionary *options = [NSMutableDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithFloat:fontSizeMultiplier], NSTextSizeMultiplierDocumentOption,
                                        fontName, DTDefaultFontFamily,
                                        @"purple", DTDefaultLinkColor,
                                        @"red", DTDefaultLinkHighlightColor,
                                        css,DTDefaultStyleSheet,
                                        [NSNumber numberWithBool:YES],DTUseiOS6Attributes,
                                        nil];

.
.
.
.

Here are some screenshots from my xib Files for more information:
My GTNewsTableViewController:

GTNewsCustomCell (FilesOwner):

GTNewsCustomCell (View):

GTNewsCustomCell:

A: Okay, since you're doing the registration of cells via tableView's method registerNib:forCellReuseIdentifier:. The initWithStyle:reuseIdentifier: won't ever get called. If you'd like to do the styling, use -awakeFromNib method of your UITableViewCell subclass.
- (void)awakeFromNib {
  [super awakeFromNib];
  self.messageTextView.textColor = [UIColor blackColor];
  self.messageTextView.backgroundColor = GTDefaultTextBackgroundColor;
  self.messageTextView.editable = NO;
  self.messageTextView.userInteractionEnabled = NO;
}

A: with GTNewsCustomCell (FilesOwner), you will not be able to reuse this cell if needed. you should make it NSObject(FileOwner). and load this cell in cellForRowAtIndexPath.
by this way , you will get the same style of of your custom cell.
static NSString *CellIdentifier= @"CustomCell";
CustomCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell ==  nil) {
    NSArray* nibViews = [[NSBundle mainBundle] loadNibNamed:@"CustomCell"
                                                      owner:self//transfer ownership to self
                                                    options:nil];
    cell = [nibViews objectAtIndex:0];
}

return cell;
}


text:
Q: Lua 5.1 equivalent of lua_setgcthreshold After updating my lua version from 5.0 to 5.1
I get an lua_setgcthreshold was not declared in this scope
With lua 5.0 all work fine.
In lua 5.0  lua_setgcthreshold is declared like this :
LUA_API void  lua_setgcthreshold (lua_State *L, int newthreshold);

But in 5.1 i can't find an equivalent for this.
Anyone can help me?

A: Depending on your situation, the Lua function collectgarbage may be of use to you. See: http://luatut.com/collectgarbage.html


text:
Q: compute the result of a variable inside a recursive function I have written the printing staircase algorithm. A function that given n prints the staircase n levels.

    var i = 1;
    function printStaircase(n) {
      //Base case
      if (n < 1) return n;
      //Recursive case
      var line = '';
      line += ' '.repeat(n - 1);
      line += '*'.repeat(i);
      console.log(line);
      i++;
      return printStaircase(n - 1);
    }

    printStaircase(10);

As you can see I have to pass in the i variable from the outside. I'm wondering how I can accomplish while computing the value of i inside the function body, so that it is self-contained and gets nothing from the global scope

A: Recursion is super fun -

const chars = (c = "") => (n = 0) =>
  n === 0
    ? ""
    : c + chars (c) (n - 1)

const spaces =
  chars (" ")

const stars =
  chars ("*")

const newline =
  "\n"

const stairs = (n, m = n - 1) =>
  m <= 0
    ? ""
    : spaces (m)
      + stars (n - m)
      + newline
      + stairs (n, m - 1)

console .log (stairs (10))

console .log (stairs (4))

A: Closure to the rescue:

/**
  * @return stair case n high
  */
function staircase(n) {
  function helper (cur, str) {
    if (cur < 1) return str;
    return helper(
      cur - 1,
      `${str}${' '.repeat(cur)}${'*'.repeat(n-cur+1)}\n`);
  }
  return helper(n, '');
}

/**
  * prints a staircase n-1 hight
  * @return 0 (don't know why)
  */
function printStaircase(n) {
  console.log(staircase(n));
  return 0;
}

printStaircase(10);
printStaircase(3);

A: I think something like this would work
function printStaircase(n, i) {
  //Base case
  if (n < 1) return n;
  //Recursive case
  var line = '';
  line += ' '.repeat(n - 1);
  line += '*'.repeat(i);
  console.log(line);
  i++;
  return printStaircase(n - 1, i);
}
printStaircase(10, 1);

Hope this helps!

A: n and i are related in that i is simply the inital value of n minus the current value of n +1, so we can capture that quite nicely with something like:

function printStaircase(n) {
  staircaseInternal(n);

  function staircaseInternal(curr) {
    //Base case
    if (curr < 1) return;
    //Recursive case
    var line = ' '.repeat(curr - 1);
    line += '*'.repeat((n - curr) + 1);
    console.log(line);
    staircaseInternal(curr - 1);
  }
}

printStaircase(10);


text:
Q: Call Oracle function with a cursor IN/OUT I am trying to make a simple call to a function(Test2) which takes a cursor, and returns a cursor.
I am stuck with the error:
Error(23,17): PLS-00306: wrong number or types of arguments in call to 'TEST2'
What is wrong with my function call?
v_resp := TEST2(v_req);

Here is my test:
CREATE OR REPLACE TYPE TRANS_OBJ AS OBJECT (TRANSNO CHAR(8));
CREATE OR REPLACE TYPE TRANS_OBJ_TAB AS TABLE OF TRANS_OBJ;

CREATE OR REPLACE FUNCTION TEST2 (v_rc IN SYS_REFCURSOR) RETURN TRANS_OBJ_TAB
IS
  v_resp TRANS_OBJ_TAB := TRANS_OBJ_TAB();

  BEGIN
    v_resp.extend;
    v_resp(1) := TRANS_OBJ('222222');
    RETURN v_resp;
  END;

CREATE OR REPLACE FUNCTION TEST1 RETURN TRANS_OBJ_TAB
IS
  TRANSNO   CHAR(8);
  v_cnt number := 0;
  v_req TRANS_OBJ_TAB := TRANS_OBJ_TAB();
  v_resp TRANS_OBJ_TAB := TRANS_OBJ_TAB();
  --v_resp sys_refcursor;

  CURSOR v_rc IS SELECT '1111' AS TRANSNO FROM DUAL;

  BEGIN
      OPEN v_rc;

      LOOP
        fetch v_rc into TRANSNO;
        EXIT WHEN v_rc%NOTFOUND;

        v_req.extend;
        v_cnt := v_cnt + 1;
        v_req(v_cnt)  := TRANS_OBJ(TRANSNO);
      END LOOP;

      CLOSE v_rc;
      v_resp := TEST2(v_req);
      RETURN v_resp;
    END;
/
DROP TYPE TRANS_OBJ_TAB;
DROP TYPE TRANS_OBJ;
DROP FUNCTION TEST1;
DROP FUNCTION TEST2;

A: First you are not returning a CURSOR from TEST2 function as you says (try return sys_refcursor).
On the other hand v_req is not an sys_refcursor, besides v_resp can't contains a cursor too. Review the types you are using.
Hope this help!!!


text:
Q: K-Means Clustering variable results depending on sort order of data I'm using PASWStatistics18 and K-Means clustering data that I'd previously clustered using an earlier version of SPSS... My problem is that I'm getting different cluster results depending on how the data file is sorted.  I can't remember this being an issue in the earlier versions of SPSS, but I can't repeat the same results, using the same data file, again!  Only by using the saved cluster centres can I get close to the original result.
Have others had similar isues?  Am I doing something wrong?

A: This is a well-known property of k-means. The initialization is usually randomized, so you might even get (and in fact, intend to get) different results for multiple runs. It is a common best practise with k-means to run it multiple times, and choose the one with the minimum average distances (or by some other internal metric).
DBSCAN is mostly order independent. Only for fringe points that could belong to two different clusters, the cluster assignment is not stable (unless you extend DBSCAN to support multi-assignments or use some other stable tie-braking rule).
In general, it actually is even a good idea to shuffle your dataset before doing any kind of analysis. Say your method fails completely, and returns the data set in its original order. If the data was sorted before, the output will look meaningful. So always shuffle your data.

A: Actually SPSS has acknowledged, going back at least to version 13 (ca. 2003) that cluster solutions will be affected by sort order.  This applies not only to K-means but to its other clustering algorithms as well.  You'll find this information in the Help files and possibly in the Tutorial.  When using cluster analysis in SPSS I always create a random number and sort by that first.


text:
Q: Different size blocks best allocation to fixed size buckets I have an interesting (or maybe its plain simple) problem to solve.
There are different size blocks (say any real numbers like 0.5 or 50) to allocate among buckets. Bucket size is always 64.
The problem to solve is to allocate the blocks in such a way that least amount of space in buckets is wasted.
Going for naive solution one can just iterate over buckets and push nth element into first bucket that the block can fit into. If there are no buckets that can fit the element - new bucket is created.
Is there any better way to do that or is the naive solution also an optimal solution?

A: This is a mathematically complex question called the Bin Packing Problem.
You probably won't find an easy way to implement the optimal soloution.  This page mentions one solution, to always put the block in the fullest bucket that can fit it.
I think analyzing the entire dataset beforehand is the key to an optimal solution, but it doesn't seem like it will be easy to implement.

A: You can keep the buckets sorted by available space (e.g. from the max space available till the least space available. Your algorithm would be:

*

*Initially the list is empty.

*Create the first block for the new coming block.

*The next one one is coming. Check if it fits into the first bucket. If doesn't, create a new one and check for available. If the new one has more available space than the first one, place it in front of the list, otherwise append to the end.

*Essentially the problem narrows down to performing a binary search to find which of the buckets will fit the new element and finding a new place for the element you've updated at the current step.


text:
Q: Hibernate hbm2ddl with synonyms I've recently added synonyms to our DB. These synonyms hold the entire entity information, hence have their own mapping file. Connecting to the synonyms is not an issue. The issue is when using the hbm2ddl tool.
If I include the synonym mapping files, the hbm2ddl tool creates the synonym table as a normal table, it should be ignored. I'm not sure how to flag the entity mapping as a synonym (or if possible) and restrain hibernate from creating a new table for this synonym.
If I exclude the mapping files, then the tool does not pass validation since other files refer to the synonym entities. Example:
   <many-to-one name="creator" class="com.entities.MySynonymEntity"  cascade="refresh" foreign-key="MY_SYNM_FKC" not-null="false" lazy="proxy" fetch="select">
        <column name="MY_SYNM_FK" not-null="false"  sql-type="NUMBER(19)"  />
    </many-to-one>

Here the mapping file belong to an entity which lives in the true database but refers to an entity whose data is populated from a synonym.
What would be the correct way to setup your mapping files for the hbm2ddl tool when synonyms of involved?
Thanks much,
JP

A: I add this answer because this is not an acceptable answer to disable the validation. Sometimes you want to validate the schema.
With Hibernate 5.1, the validation also works with synonyms, one should set the following property hibernate.synonyms to true.
Source: https://docs.jboss.org/hibernate/orm/5.1/userguide/html_single/Hibernate_User_Guide.html#configurations-hbmddl

A: I think hbm2ddl works only for tables and not for synonyms.I would suggest
to keep value for hibernate.hbm2ddl.auto= "" rather then validation.
Same discussion went in hibernate forums
https://forum.hibernate.org/viewtopic.php?p=2438033


text:
Q: How to refer to the current record in a Rails query? In a Rails controller I'm using a JSON request to an external database to return integers that are used to order a collection of records:
Model.order(JSON.parse(open("http://myapp.com/models/#{:id}")).read)['attribute'])

I want to make this dynamic to aid switching between environments. Something like:
Model.order(JSON.parse(open(model_url(model))).read)['attribute'])

This is not correct, and model_url(model) is returning an error:
undefined local variable or method 'model'
How do I refer to self in query?
There must be a more elegant solution than
...JSON.parse(open("#{root_url}/models/{:id}"))....

EDIT:
Lightswitch05's answer below does anser the question I asked. The query should reference params[:id] to get the url of the current record.
In fact, I have decided to move this JSON call into a virtual attribute on the model. This means I can simply call Model.order(:my_virtual_attribute). While this solution brings its own share of issues—I needed to make url_helpers available to the model—in the long run I think this will be a cleaner solution.

A: As per our discussion the problem is that model is not defined. Since all you are trying to do with model is get the url to it, all you really need is params[:id]. This will fix your error message:
Model.order(JSON.parse(open(model_url(params[:id]))).read)['attribute'])

where model has been replaced with params[:id]

A: Change your code:
Model.order(JSON.parse(open(model_url(model))).read)['attribute'])

to:
model_tableized = Model.to_s.tableize
model_url = "#{model_tableized}_url(#{model_tableized.chomp('s')})"
Model.order(JSON.parse(open(model_url).read)["attribute"])

I think that should work.

A: You need the name method.
If you're using the model, and not an instance of the model, it would be Model.name
If you're using an instance, it would be
@model = Model.first
@model.class.name


text:
Q: Format ffmpeg command to extract the full klv for an mpg/ts file I am extracting the KLV data from an mpg file using klvdata and ffmpeg.
Following the readme, I have downloaded the sample "Day Flight.mpg" video file that contains KLV data.  Running the quick start command works (I get the exact same result as the readme example for the first 6 frames.)
However, for the life of me I don't know how I can extract the KLV data for the entire video file.
As an experiment, I tried creating the KLV data file from an offset start:
ffmpeg -ss 5 -i Day\ Flight.mpg -map data-re -codec copy -f data - > out.klv

and when I run it through my code with different start times (5, 25, etc.) I do get different results.
This (to me) would suggest that the mpg file does contain KLV data throughout, but I can only access 6 frames at a time.
I would expect to be able to run an ffmpeg command to output the full KLV data.  I need help formatting my ffmpeg command to properly provide all the data.
To replicate, download the "Day Flight.mpg" file from the klvdata project page and run the command I posted above.  You will note it is less than a page long.  It should be many, many pages long.  Thank you for your help!


text:
Q: How to reset the Windows 7 desktop gadgets? After changing the Windows Sidebar settings
C:\Users\USERNAME\AppData\Local\Microsoft\Windows Sidebar\Settings.ini

( Where are the settings for the Windows 7 clock gadget stored? )
How do i refresh the Windows Sidebar to pick up these changes?

A: So far i have discovered killing and restarting "sidebar.exe" works.
But I assume there is a better way?

A: On Windows 7, right click on the desktop, view Show desktop gadgets, un-click it, then enable it again.
All the gadgets will initialize.

A: Save the following to a .bat text file and run it (probably as Administrator) :
:: Created by: Shawn Brink
:: http://www.sevenforums.com
:: Tutorial:  http://www.sevenforums.com/tutorials/140358-gadgets-not-displaying-correctly-windows-7-fix.html

taskkill /im sidebar.exe /f
regsvr32 /s msxml3.dll
regsvr32 /s scrrun.dll
regsvr32 /s jscript.dll
regsvr32 /s atl.dll
Regsvr32 /s "%ProgramFiles%\Windows Sidebar\sbdrop.dll"
Regsvr32 /s "%ProgramFiles%\Windows Sidebar\wlsrvc.dll"
reg delete "HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Internet Settings\Zones" /f
"%ProgramFiles%\Windows Sidebar\sidebar.exe"

There's a way to make the last command exit the terminal without waiting on the program, but I forget it. You can just close the terminal.


text:
Q: adding more button for list in responsive navigation I have a navigation of lets say 12 items, and when resolution gets smaller items drop in a new line. I need to make that when an item doesn't fit on a navigation anymore it should put a "MORE" dropdown button on the right side of nav. and put that item that doesn't fit in a dropdown.
If you don't understand me there is image below.
But the problem is that navigation items aren't always the same width because navigation items are generated from REST api.
I tryed to make jQuery script for calculating items width and adding them to navigation.
Here is the script I created, I made it in a hurry so it's really bad.
I need to help on how to properly calculate items witdh and navigation width and calculating when to add items to navigation or remove items from navigation.
Here is image if you don't get it: http://img.hr/aagV

    /*
    * Here we check how many items can we put on the navigation bar
    * If item doesn't fit we clone it on the more dropdown button
    */
    function removeMany() {
        var i = $items.length - 1;

        if (itemsWidth > navWidth) {
            while (itemsWidth > navWidth) {
                $($items[i]).removeClass('first-level-item').addClass('second-level-item');
                dropdownItems.push($items[i]);
                $($items[i]).removeClass('showed');
                $items.pop();

                i--;
                getItemsWidth();
            }

            $nav.append($navMore);

            dropdownItems.reverse().forEach(function (element, index, array) {
                $('ul.second-level').append(element);
            });

            getItems();
        }
    }

    //If window is resized to bigger resolution we need to put back items on the navbar
    function addMany() {
        var i = dropdownItems.length - 1;

        if (dropdownItems.length != 0) {

            do {
                $('ul.first-level').append(dropdownItems.reverse()[i]);
                $items.push(dropdownItems[i]);
                dropdownItems.pop();

                i--;
                getItemsWidth();
            } while (itemsWidth < navWidth);

            $navMore.remove();

            $items.each(function (i) {
                $(this).addClass('first-level-item showed').removeClass('second-level-item');
            });

            if (!(dropdownItems != 0)) {
                return;
            } else {
                $nav.append($navMore);
            }

        }
    }

body {
  margin: 0;
  padding: 0;
  border: 0; }

ul, li {
  margin: 0;
  padding: 0;
  list-style: none; }

ul.second-level li {
  display: block !important; }
ul.second-level li > a {
  color: black; }

a {
  color: #fff;
  text-decoration: none;
  text-transform: uppercase; }

.second-level-item a {
  color: #333 !important; }

.navigation {
  width: 960px;
  max-width: 100%;
  background: #211;
  color: #aaa;
  margin: 0 auto; }

.first-level .first-level-item {
  display: inline-block;
  padding: 10px; }
.first-level .item-more {
  display: inline-block; }
  .first-level .item-more .second-level-item {
    display: inline-block; }

.second-level {
  position: absolute;
  top: 100%;
  right: 0;
  width: 200px;
  background: #fff;
  padding: 10px;
  box-shadow: 0 4px 10px rgba(0, 0, 0, 0.4); }

.has-second-level {
  position: relative; }
  .has-second-level .second-level {
    display: none; }
  .has-second-level:hover {
    background: #fff;
    color: #000; }
    .has-second-level:hover .second-level {
      display: block; }

/*# sourceMappingURL=style.css.map */
<!doctype html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>DropDown</title>

    <link rel="stylesheet" href="css/reset.css"/>
    <link rel="stylesheet" href="css/style.css"/>

Introduction to Irish Culture

Cellular and Molecular Neurobiology

Guitar foundations

Startup Inovation

Astrophysics

                 More

A: If you have fixed-width list-items, then it is simple to collect extra list-items and push them into a separate list. Here is a simple example. Explanation is in the code comments.
View the snippet in full-screen and try changing the window width.
Also a Fiddle: http://jsfiddle.net/abhitalks/860LzgLL/
Full Screen: http://jsfiddle.net/abhitalks/860LzgLL/embedded/result/
Snippet:

var elemWidth, fitCount, fixedWidth = 120,
    $menu = $("ul#menu"), $collectedSet;

// Assuming that the list-items are of fixed-width.

collect();
$(window).resize(collect);

function collect() {
    // Get the container width
    elemWidth = $menu.width();

    // Calculate how many list-items can be accomodated in that width
    fitCount = Math.floor(elemWidth / fixedWidth) - 1;

    // Create a new set of list-items more than the fit count
    $collectedSet = $menu.children(":gt(" + fitCount + ")");

    // Empty the collection submenu and add the cloned collection set
    $("#submenu").empty().append($collectedSet.clone());
}
* { box-sizing: border-box; margin: 0; padding: 0; }
div { position: relative; background-color: #ccc; height: 32px; overflow: visible; }
ul#menu, ol { height: 32px; max-width: 80%; overflow: hidden; }
ul#menu > li, ol > li { display: block; float: left;  height: 32px; width: 120px; padding: 4px 8px; }
ol { position: absolute; right: 0; top: 0; overflow: visible; }
ol > li { min-width: 120px; }
ol ul { position: absolute; top: 120%; right: 10%; }
ol li ul > li { list-style: none; background-color: #eee; border: 1px solid gray; padding: 4px 8px;}

Option One

Option Two

Option Three

Option Four

Option Five

Option Six

Collected

Update:
This is regarding your query on differing / variable widths of list-items. There would be a minor change.
Also a Fiddle: http://jsfiddle.net/abhitalks/tkbmcupt/1/
Full Screen: http://jsfiddle.net/abhitalks/tkbmcupt/1/embedded/result/
Snippet:

var elemWidth, fitCount, varWidth = 0, ctr, $menu = $("ul#menu"), $collectedSet;

// Get static values here first
ctr = $menu.children().length;         // number of children will not change
$menu.children().each(function() {
    varWidth += $(this).outerWidth();  // widths will not change, so just a total
});

collect();  // fire first collection on page load
$(window).resize(collect); // fire collection on window resize

function collect() {
    elemWidth = $menu.width();  // width of menu

    // Calculate fitCount on the total width this time
    fitCount = Math.floor((elemWidth / varWidth) * ctr) - 1;

    // Reset display and width on all list-items
    $menu.children().css({"display": "block", "width": "auto"});

    // Make a set of collected list-items based on fitCount
    $collectedSet = $menu.children(":gt(" + fitCount + ")");

    // Empty the more menu and add the collected items
    $("#submenu").empty().append($collectedSet.clone());

    // Set display to none and width to 0 on collection,
    // because they are not visible anyway.
    $collectedSet.css({"display": "none", "width": "0"});
}
* { box-sizing: border-box; margin: 0; padding: 0; }
div { position: relative; background-color: #ccc; height: 32px; overflow: visible; }
ul#menu, ol { height: 32px; max-width: 80%; overflow: hidden; }
ul#menu > li, ol > li { display: block; float: left; height: 32px; white-space: nowrap; padding: 4px 8px; }
ol { position: absolute; right: 0; top: 0; overflow: visible; }
ol > li { min-width: 120px; }
ol ul { position: absolute; top: 120%; right: 10%; }
ol li ul > li { list-style: none; background-color: #eee; border: 1px solid gray; padding: 4px 8px;}

Option One

Option Two

Option Three

Option Four

Option Five

Option Six

Collected

A: Can and SHOULD be optimised (as it is quite inefficient from what i've tested), but that's up to you.

$(document).ready(function(){
  var moreW = $(".more").outerWidth(), //width of your "more" element
      totalW = -moreW, //cumulated width of list elements
      totalN = $('.nav li').length - 1,  //number of elements minus the "more" element
      dw = document.documentElement.clientWidth;

  $('.nav li').each(function(){
    totalW += $(this).outerWidth();
  });

  function moveToDropdown(){
    dw = document.documentElement.clientWidth;
    //moves elements into the list
    while(totalW > (dw - moreW)){
      var temp = $(".nav li:nth-last-child(2)"); //element to be moved

      totalW = totalW - temp.outerWidth();
      $(".dropdown").append(temp.clone());
      temp.remove();
    }
    //moves elements out of the list
    var newList = $('.dropdown li').length; //check if we have elements
    if(newList > 0){
      var element = $('.dropdown li:last-child'), //element to be moved
          elementW = $('.dropdown li:last-child').outerWidth(); //width of element to be moved

      if(totalW +  elementW < dw - moreW){
        while(totalW +  elementW < dw - moreW ){
          var element = $('.dropdown li:last-child'),
              elementW = $('.dropdown li:last-child').outerWidth();

          totalW = totalW + elementW;
          $(".nav > li:last-child").before(element.clone());
          element.remove();
        }
      }
    }
  }

  moveToDropdown();
  $(window).resize(moveToDropdown)
});
.clearfix:after{
  display:block;
  content:'';
  clear:both;
}
body,html{
  width:100%;
  height:100%;
  margin:0;
  padding:0;
}
ul{
  list-style:none;
  width:100%;
  padding:0;
  margin:0;
}
ul li{
  float:left;
  padding:5px;
}
.nav > li {
  position:relative;
}
.nav ul{
  position:absolute;
  top:25px;
}

Item

Item

Item

Item

Item

Item

Item

    more

A: The script that Abhitalks made did not work properly for different element sizes. I modified the code a little bit do that it does:
$(function() {
    function makeMenuFit() {
        //Get data
        var menuSize = menu.width();

        //Determine how many items that fit
        var menuTotalWidth = 0;
        var itemThatFit = 0;
        for(var i = 0; i < menuItems.length; i++) {
            menuTotalWidth += menuItems[i];
            if(menuTotalWidth <= menuSize) {
                itemThatFit++;
                continue;
            }
            break;
        }

        menu.children().css({"display": "block", "width": "auto"});
        var collectedSet = menu.children(":gt(" + (itemThatFit - 1) + ")");
        $("#submenu").empty().append(collectedSet.clone());
        collectedSet.css({"display": "none", "width": "0"});
    }

    var menu = $(".tabletNavigation > ul");
    var menuItems = [];
    menu.children().each(function() {
        menuItems.push($(this).outerWidth());
    });

    $(window).resize(makeMenuFit);
    makeMenuFit();
});

A: This question is too old, but i want to post my answer too. Maybe this is more cleaner and easier way. I have created a pen: https://codepen.io/sergi95/pen/bmNoML

    home

    about us

    portfolio

    team

    blog

    contact

    more

        policy

const $mainMenu = $("#mainMenu");
    const $autoNav = $("#autoNav");
    const $autoNavMore = $("#autoNavMore");
    const $autoNavMoreList = $("#autoNavMoreList");
    autoNavMore = () => {
        let childNumber = 2;

        if($(window).width() >= 320) {
            // GET MENU AND NAV WIDTH
            const $menuWidth = $mainMenu.width();
            const $autoNavWidth = $autoNav.width();
            if($autoNavWidth > $menuWidth) {
                // CODE FIRES WHEN WINDOW SIZE GOES DOWN
                $autoNav.children(`li:nth-last-child(${childNumber})`).prependTo($autoNavMoreList);
                autoNavMore();
            } else {
                // CODE FIRES WHEN WINDOW SIZE GOES UP
                const $autoNavMoreFirst = $autoNavMoreList.children('li:first-child').width();
                // CHECK IF ITEM HAS ENOUGH SPACE TO PLACE IN MENU
                if(($autoNavWidth + $autoNavMoreFirst) < $menuWidth) {
                    $autoNavMoreList.children('li:first-child').insertBefore($autoNavMore);
                }
            }
            if($autoNavMoreList.children().length > 0) {
                $autoNavMore.show();
                childNumber = 2;
            } else {
                $autoNavMore.hide();
                childNumber = 1;
            }
        }
    }
    // INIT
    autoNavMore();
    $(window).resize(autoNavMore);

.main-menu {
        max-width: 800px;
    }
    .main-nav {
        display: inline-flex;
        padding: 0;
        list-style: none;
    }
    .main-nav li a {
        padding: 10px;
        text-transform: capitalize;
        white-space: nowrap;
        font-size: 30px;
        font-family: sans-serif;
        text-decoration: none;
    }
    .more-btn {
        color: red;
    }
    .auto-nav-more {
        position: relative;
    }
    .auto-nav-more-list {
        position: absolute;
        right: 0;
        opacity: 0;
        visibility: hidden;
        transition: 0.2s;
        text-align: right;
        padding: 0;
        list-style: none;
        background: grey;
        border-radius: 4px;
    }
    .auto-nav-more:hover .auto-nav-more-list {
        opacity: 1;
        visibility: visible;
    }


text:
Q: Scheduling Airflow DAGs to run exclusively Monday through Friday i.e only weekdays I have a DAG executing a Python script which takes a date argument (the current date). I'm scheduling the DAG to run at 6:00 AM Monday through Friday i.e weekdays Eastern Standard Time. The DAG has to run the Python script on Monday with Mondays date as an argument, same for Tuesday all the way to Friday with Fridays date as an argument.
I noticed using a schedule interval of '0 6 * * 1-5' didn't work because Fridays execution didn't occur until the following Monday.
I changed the schedule interval to '0 6 * * *' to run everyday at 6:00 AM and at the start of my dag, filter for dates that fall within '0 6 * * 1-5', so effectively Monday to Friday. For Saturday and Sunday, the downstream tasks should be skipped.
This is my code
from __future__ import print_function
import pendulum
import logging
from airflow.models import DAG
from airflow.models import Variable
from datetime import datetime, timedelta
from airflow.contrib.operators.ssh_operator import SSHOperator
from airflow.operators.python_operator import ShortCircuitOperator
from airflow.operators.dummy_operator import DummyOperator
from airflow.utils.trigger_rule import TriggerRule
from croniter import croniter

log = logging.getLogger(__name__)

def filter_processing_date(**context):
    execution_date = context['execution_date']
    cron = croniter('0 6 * * 1-5', execution_date)
    log.info('cron is: {}'.format(cron))
    log.info('execution date is: {}'.format(execution_date))
    #prev_date = cron.get_prev(datetime)
    #log.info('prev_date is: {}'.format(prev_date))
    return execution_date == cron.get_next(datetime).get_prev(datetime)

local_tz = pendulum.timezone("America/New_York")
# DAG parameters

default_args = {
    'owner': 'Managed Services',
    'depends_on_past': False,
    'start_date': datetime(2020, 8, 3, tzinfo=local_tz),
    'dagrun_timeout': None,
    'email': Variable.get('email'),
    'email_on_failure': True,
    'email_on_retry': False,
    'provide_context': True,
    'retries': 12,
    'retry_delay': timedelta(minutes=5)
}

with DAG(
    'execute_python',
    schedule_interval='0 6 * * *',
    default_args=default_args
    ) as dag:

    start_dummy = DummyOperator(
        task_id='start',
        dag=dag
    )

    end_dummy = DummyOperator(
        task_id='end',
        trigger_rule=TriggerRule.NONE_FAILED,
        dag=dag
    )

    weekdays_only = ShortCircuitOperator(
        task_id='weekdays_only',
        python_callable=filter_processing_date,
        dag=dag
    )

    run_python = SSHOperator(
    ssh_conn_id="oci_connection",
    task_id='run_python',
    command='/usr/bin/python3  /home/sb/local/bin/runProcess.py -d {{ ds_nodash }}',
    dag=dag)

    start_dummy >> weekdays_only >> run_python >> end_dummy

Unfortunately, weekdays_only task is failing with the below error message. What is going wrong?
Airflow error message
Airflow error message continuation
Airflow version: v1.10.9-composer
Python 3.

A: I managed to solve my problem by hacking something together. Checking if the next execution date is a weekday and returning true if it's the case or false otherwise. I call the function in a ShortCircuitOperator which proceeds with downstream tasks if true or skips them if false.
This is my code below but I'm open to better solutions.
from __future__ import print_function
import pendulum
import logging
from airflow.models import DAG
from airflow.models import Variable
from datetime import datetime, timedelta
from airflow.contrib.operators.ssh_operator import SSHOperator
from airflow.operators.python_operator import ShortCircuitOperator
from airflow.operators.dummy_operator import DummyOperator
from airflow.utils.trigger_rule import TriggerRule

log = logging.getLogger(__name__)

def checktheday(**context):
    next_execution_date = context['next_execution_date']
    log.info('next_execution_date is: {}'.format(next_execution_date))
    date_check = next_execution_date.weekday()
    log.info('date_check is: {}'.format(date_check))
    if date_check == 0 or date_check == 1 or date_check == 2 or date_check == 3 or date_check == 4:
        decision = True
    else:
        decision = False

    log.info('decision is: {}'.format(decision))
    return decision

local_tz = pendulum.timezone("America/New_York")
# DAG parameters

default_args = {
    'owner': 'Managed Services',
    'depends_on_past': False,
    'start_date': datetime(2020, 8, 3, tzinfo=local_tz),
    'dagrun_timeout': None,
    'email': Variable.get('email'),
    'email_on_failure': True,
    'email_on_retry': False,
    'provide_context': True,
    'retries': 12,
    'retry_delay': timedelta(minutes=5)
}

with DAG(
    'execute_python',
    schedule_interval='0 6 * * *',
    default_args=default_args
    ) as dag:

    start_dummy = DummyOperator(
        task_id='start',
        dag=dag
    )

    end_dummy = DummyOperator(
        task_id='end',
        trigger_rule=TriggerRule.NONE_FAILED,
        dag=dag
    )

    weekdays_only = ShortCircuitOperator(
        task_id='weekdays_only',
        python_callable=checktheday,
        dag=dag
    )

    run_python = SSHOperator(
    ssh_conn_id="oci_connection",
    task_id='run_python',
    command='/usr/bin/python3  /home/sb/local/bin/runProcess.py -d {{ macros.ds_format(macros.ds_add(ds, 1), "%Y-%m-%d", "%Y%m%d") }}',
    dag=dag)

    start_dummy >> weekdays_only >> run_python >> end_dummy


text:
Q: How to select numbers only if the column contains both character and numbers in SQL query? Would like to check with all expect in SQL query. Please look at below for the examples. Thanks.
Column
abc 123
cdf 456

What I want is:
123
456

Appreciate your help for this question. Thanks a lot!

A: Based on your comments, Try this -
SELECT REGEXP_SUBSTR(Column, '[0-9]+');


text:
Q: Changing values of the dataframe columns based on a list of indices I have a data frame with 4 columns:
myData<-mtcars[1:20,1:4]

also a list with the same column names:
myList<-list(mpg=c(1,2,3), cyl=c(2,10), disp=integer(0), hp=c(3))

How can I change the values of each column of the dataframe based on the corresponding vector of a list?
So I want to set the first, second and third row of the myData$mpg, the second and tenth row of myData$cyl and so forth, to e.g. NA.
I have tried the following line but it doesn't work.
mapply(function(x, y)y[x, names(x)]<-NA, myList, myData, SIMPLIFY=FALSE)

Error in y[x, names(x)] : incorrect number of dimensions

A: One solution I can think of is as follows:
sapply(names(myList), function(x) {myData[myList[[x]], x] <<- NA})

I have not used mapply, but your problem may be the 'global' assignment.
Providing output as:
myData
                     mpg cyl  disp  hp
Mazda RX4             NA   6 160.0 110
Mazda RX4 Wag         NA  NA 160.0 110
Datsun 710            NA   4 108.0  NA
Hornet 4 Drive      21.4   6 258.0 110
Hornet Sportabout   18.7   8 360.0 175
Valiant             18.1   6 225.0 105
Duster 360          14.3   8 360.0 245
Merc 240D           24.4   4 146.7  62
Merc 230            22.8   4 140.8  95
Merc 280            19.2  NA 167.6 123
Merc 280C           17.8   6 167.6 123
Merc 450SE          16.4   8 275.8 180
Merc 450SL          17.3   8 275.8 180
Merc 450SLC         15.2   8 275.8 180
Cadillac Fleetwood  10.4   8 472.0 205
Lincoln Continental 10.4   8 460.0 215
Chrysler Imperial   14.7   8 440.0 230
Fiat 128            32.4   4  78.7  66
Honda Civic         30.4   4  75.7  52
Toyota Corolla      33.9   4  71.1  65

A: We can use mapply in this way. If you don't need the row.names of the result:
mapply(function(data, index) {data[index] <- NA; data}, myData, myList)

should suffice. Otherwise, you can manually assign the row.names back.
`row.names<-`(mapply(function(data, index) {data[index] <- NA; data}, myData, myList),
              rownames(myData))
                     mpg cyl  disp  hp
Mazda RX4             NA   6 160.0 110
Mazda RX4 Wag         NA  NA 160.0 110
Datsun 710            NA   4 108.0  NA
Hornet 4 Drive      21.4   6 258.0 110
Hornet Sportabout   18.7   8 360.0 175
Valiant             18.1   6 225.0 105
Duster 360          14.3   8 360.0 245
Merc 240D           24.4   4 146.7  62
Merc 230            22.8   4 140.8  95
Merc 280            19.2  NA 167.6 123
Merc 280C           17.8   6 167.6 123
Merc 450SE          16.4   8 275.8 180
Merc 450SL          17.3   8 275.8 180
Merc 450SLC         15.2   8 275.8 180
Cadillac Fleetwood  10.4   8 472.0 205
Lincoln Continental 10.4   8 460.0 215
Chrysler Imperial   14.7   8 440.0 230
Fiat 128            32.4   4  78.7  66
Honda Civic         30.4   4  75.7  52
Toyota Corolla      33.9   4  71.1  65

A: Another option by looping over the sequence
myData[] <- lapply(seq_along(myList), function(i) {
      myData[i][myList[[i]],] <- NA
      myData[[i]]})
head(myData)
#                   mpg cyl disp  hp
#Mazda RX4           NA   6  160 110
#Mazda RX4 Wag       NA  NA  160 110
#Datsun 710          NA   4  108  NA
#Hornet 4 Drive    21.4   6  258 110
#Hornet Sportabout 18.7   8  360 175
#Valiant           18.1   6  225 105


text:
Q: Repeating a function throughout a dataset I have been having trouble finding a solution to my problem.
I have a very large csv file containing multiple points. I have created two different functions that compute both distance and speed.
What I need is a way to carry out these functions between the first and second point, then the second and third point, and so on. I have been toying with using arrays and numpy, but I can not seem to figure it out.
Here are my functions:

# distance
def haversine_distance(lat1, long1, lat2, long2):
    degrees_to_radians = math.pi/180.0
    phi1 = (90.0 - lat1)*degrees_to_radians
    phi2 = (90.0 - lat2)*degrees_to_radians
    theta1 = long1 * degrees_to_radians
    theta2 = long2 * degrees_to_radians
    cos = (math.sin(phi1)*math.sin(phi2)*math.cos(theta1 - theta2) +
           math.cos(phi1)*math.cos(phi2))
    arc = math.acos(cos) * 6371
    arc = arc * 1000

    return arc

# speed
def speed(lat1, long1, time1, lat2, long2, time2):
    distance = haversine_distance(lat1, long1, lat2, long2)
    delta_time = time2 - time1
    speed = (distance / delta_time)
    speed = speed * 3.6

    return speed

A: I assume you can read your csv data into numpy arrays. Let's call them capital Lat,Long and Time. Then all you need to do is to call your functions over the appropriate points:
# initialize correct vectors
l1=Lat[:-1]      # all points but last
l2=Lat[1:]       # all points but first
lg1=Long[:-1]
lg2=Long[1:]
t1=Time[:-1]
t2=Time[1:]

speed(l1,lg1,t1,l2,lg2,t2)    # call the function which will run over your arrays


text:
Q: How to add back an option in select 2 which is removed already My select2 plugin drop down below,
<select class="select_drop wid_100" id="dropDownId">
    <option value="0">Select Account Manager</option>
    <option value="1">Justin</option>
    <option value="2">Issac</option>
</select>

Script below to remove an option while onchange.
$('#dropDownId').change(function() {
      $("#dropDownId option[value='0']").remove();
     amClose();
});

In another function amclose(), I want to get back that option. Something like below.
function amClose() {
    $(".am_dd_text p i").click(function() {
      $("#dropDownId option[value='0']").add();
   });
  }

I know this won't work as $("#dropDownId option[value='0']").add() is not a function. Instead how to do this?

A: You can use .detach() and keep item with events.
var items;
$('#dropDownId').change(function() {
     items = $("#dropDownId option[value='0']").detach();
     amClose();
});

function amClose() {
    $(".am_dd_text p i").click(function() {
      $("#dropDownId").append(items );
   });
  }

A: try this:
 function amClose() {
    $(".am_dd_text p i").click(function() {
       document.getElementById('select-image').innerHTML = '<option value="0">Select Account Manager</option>' + document.getElementById('select-image').innerHTML;
    });
 }

This way if it is only the first option is to be added back, you can add it.


text:
Q: How to expand/collapse bootstrap accordion on panel-heading click event? I try to Expand/Collapse 'panel-body' on 'panel-heading' on click event instead of   on click (default), but it's not working.
Here is my html markup:

                  Portal Design

<input type="radio" name="web_design" data-price="15000" value="Website Design">Website design required

<input type="radio" name="web_design" data-price="7000" value="Website Re-Design">Re-Design existing website

<input type="radio" name="web_design" data-price="0" value="Not Required">Website design not required

                  Recharge API's

Basic Plan

Lorem ipsum dolor

Lorem ipsum

Lorem ipsum

Lorem

-

-

Read More

                                <input type="radio" name="api-mobile" data-price="18000" value="Basic">

Business Plan

Lorem ipsum dolor

Lorem ipsum dolor dedyh

Lorem ipsum

Lorem

Lorem ipsum

-

Read More

                                <input type="radio" name="api-mobile" data-price="25000" value="Business">

Enterprise Plan

Lorem ipsum dolor

Lorem ipsum dolor dedyh

Lorem ipsum

Lorem

-

-

Read More

                                <input type="radio" name="api-mobile" data-price="150000" value="Enterprise">

                    Utility Bill Payment API's

Basic Plan

Lorem ipsum dolor

Lorem ipsum

Lorem ipsum

Lorem

-

-

Read More

                                    <input type="radio" name="api-utlitybill" data-price="18000" value="Basic">

Business Plan

Lorem ipsum dolor

Lorem ipsum dolor dedyh

Lorem ipsum

Lorem

Lorem ipsum

-

Read More

                                    <input type="radio" name="api-utlitybill" data-price="25000" value="Business">

Enterprise Plan

Lorem ipsum dolor

Lorem ipsum dolor dedyh

Lorem ipsum

Lorem

-

-

Read More

                                    <input type="radio" name="api-utlitybill" data-price="150000" value="Enterprise">

                    Travel API's

Basic Plan

Lorem ipsum dolor

Lorem ipsum

Lorem ipsum

Lorem

-

-

Read More

                                    <input type="radio" name="api-travel" data-price="18000" value="Basic">

Business Plan

Lorem ipsum dolor

Lorem ipsum dolor dedyh

Lorem ipsum

Lorem

Lorem ipsum

-

Read More

                                    <input type="radio" name="api-travel" data-price="25000" value="Business">

Enterprise Plan

Lorem ipsum dolor

Lorem ipsum dolor dedyh

Lorem ipsum

Lorem

-

-

Read More

                                    <input type="radio" name="api-travel" data-price="150000" value="Enterprise">

                    Money Transfer API's

Basic Plan

Lorem ipsum dolor

Lorem ipsum

Lorem ipsum

Lorem

-

-

Read More

                                    <input type="radio" name="api-dmr" data-price="9600" value="Basic">

Business Plan

Lorem ipsum dolor

Lorem ipsum dolor dedyh

Lorem ipsum

Lorem

Lorem ipsum

-

Read More

                                    <input type="radio" name="api-dmr" data-price="10500" value="Business">

Enterprise Plan

Lorem ipsum dolor

Lorem ipsum dolor dedyh

Lorem ipsum

Lorem

-

-

Read More

                                    <input type="radio" name="api-dmr" data-price="25000" value="Enterprise">

                    Additional Services

<input type="checkbox" name="sms_gateway" data-price="5000" value="SMS Gateway"> SMS Gateway

<input type="checkbox" name="long_code" data-price="1300" value="Long Code"> Long Code

                    Others

No other service available

Here the live: http://jsfiddle.net/8yaurtxr/
I have try to add data-toggle="collapse" but it's not working.

A: Your anchor tag has all the event listeners
Portal Design

delete the event listeners from the anchor tag
role="button" data-toggle="collapse" data-parent="#orderAccordion" href="#collapsePortalDesign" aria-expanded="true" aria-controls="collapsePortalDesign"

and paste it in the div containing panel-heading class
like this

just do this for all the other accordions and it should work like you want it to

A:

    Collapsible Group Item #1


text:
Q: DJango deployment on Apache24 not working I am new to web frameworks and I have designed small website using DJango-3.1.7.
I am trying to deploy DJango website on Apache server in Windows 10 platform but it seems something not correct or I missed out it. If anyone could help with this we be precious for me.
I have configured virtual environment for this application
Problem:
Getting error PYTHONHOME = (not set) PYTHONPATH = (not set)

error.log

Python path configuration:
  PYTHONHOME = (not set)
  PYTHONPATH = (not set)
  program name = 'python'
  isolated = 0
  environment = 1
  user site = 1
  import site = 1
  sys._base_executable = 'C:\\Apache24\\bin\\httpd.exe'
  sys.base_prefix = 'C:\\Users\\Hp\\AppData\\Local\\Programs\\Python\\Python38'
  sys.base_exec_prefix = 'C:\\Users\\Hp\\AppData\\Local\\Programs\\Python\\Python38'
  sys.executable = 'C:\\Apache24\\bin\\httpd.exe'
  sys.prefix = 'C:\\Users\\Hp\\AppData\\Local\\Programs\\Python\\Python38'
  sys.exec_prefix = 'C:\\Users\\Hp\\AppData\\Local\\Programs\\Python\\Python38'
  sys.path = [
    'C:\\Users\\Hp\\AppData\\Local\\Programs\\Python\\Python38\\python38.zip',
    '.\\DLLs',
    '.\\lib',
    'C:\\Apache24\\bin',
  ]
Fatal Python error: init_fs_encoding: failed to get the Python codec of the filesystem encoding
Python runtime state: core initialized
ModuleNotFoundError: No module named 'encodings'

Current thread 0x00002838 (most recent call first):
<no Python frame>
[Sat Jun 26 21:56:47.558067 2021] [mpm_winnt:crit] [pid 5344:tid 780] AH00419: master_main: create child process failed. Exiting.

etc/hosts

127.0.0.2    stack-hack.com

httpd.conf

    LoadFile "c:/users/hp/appdata/local/programs/python/python38/python38.dll"
    LoadModule wsgi_module "e:/Code-Stack/stack-hack/lib/site-packages/mod_wsgi/server/mod_wsgi.cp38-win_amd64.pyd"
    WSGIPythonHome "e:/Code-Stack/stack-hack"
    WSGIPythonPath "e:/Code-Stack/stack-hack/Lib/site-packages"

    <VirtualHost *:80>
    ServerAlias www.stack-hack.com
    ServerName stack-hack.com
    ServerAdmin info@admin.com
    WSGIScriptAlias / "E:/Code-Stack/Stack-Hack/src/stackhack/wsgi.py"
    <Directory "E:/Code-Stack/Stack-Hack/src/stackhack">
        <Files wsgi.py>
        Require all granted
        </Files>
    </Directory>

    Alias /static/ "E:/Code-Stack/Stack-Hack/src/static/"
    <Directory "E:/Code-Stack/Stack-Hack/src/static">
        Require all granted
    </Directory>

    ErrorLog "E:/Code-Stack/Stack-Hack/logs/apache.error.log"
    CustomLog "E:/Code-Stack/Stack-Hack/logs/apache.custom.log" common
    </VirtualHost>

wsgi.py

    import os
    import sys
    from django.core.wsgi import get_wsgi_application
    from pathlib import Path

    path_home = str(Path(__file__).parents[1])
    if path_home not in sys.path:
        sys.path.append(path_home)

    os.environ['DJANGO_SETTINGS_MODULE'] = 'main.settings'

    application = get_wsgi_application()

Project Structure
Stack-Hack  [Virtual env]
- Lib
- Scripts
+ src
  - home
  - media
  + stackhack
    - asgi.py
    - settings.py
    - urls.py
    - wsgi.py
  - static
  - manage.py
- pyvenv.cfg

Workaround I did:

All other django settings are ok and working fine. I have followed various blog post for configuration of Apache Server

*

*https://montesariel.com/blog/post-3

*https://www.codementor.io/@aswinmurugesh/deploying-a-django-application-in-windows-with-apache-and-mod_wsgi-uhl2xq09e

A: Finding a possible fix for each error present in the trackback provided, here is what I found that might help:
This error:
Fatal Python error: init_fs_encoding: failed to get the Python codec of the filesystem encoding
Python runtime state: core initialized

has been discussed in this post, and the working solution was:

I see your PYTHONHOME is set to PYTHONHOME = '/home/env3/educ'. Try to check if it is really there.
The solution for me was to remove the PYTHONHOME environment variable. For you, it can be just that, or setting that variable to another value.

Another possible solution is from reddit here:

I was getting the same error but when I changed the full path of my python virtual environment to the relative path it worked for me, try to change this
virtualenv = /home/env3/%(projectname)

to
virtualenv = your_env

in your uwsgi.ini file

This error:
ModuleNotFoundError: No module named 'encodings'

has been discussed in this post, and the working solution was:

For Python-3 try removing virtual environment files. And resetting it up.
rm -rf venv
virtualenv -p /usr/bin/python3 venv/
source venv/bin/activate
pip install -r requirements.txt

This error:
AH00419: master_main: create child process failed. Exiting.

has been discussed in this post, and the working solution was

I added following lines to my httpd.conf

WSGIPythonPath "C:/Python33/Lib;C:/Python33/Lib/site-packages;C:/Python33/DLLs"
WSGIPythonHome "C:/Python33"

Then Apache started to work fine.

A: try this
unset PYTHONPATH
unset PYTHONHOME
Based on this solution

A: Set PYTHONHOME in your SYSTEM environment, then reboot.
In your case, set it to "C:\Users\Hp\AppData\Local\Programs\Python\Python38".


text:
Q: C# - Efficiently search through a data set For my project, I have to search through a data set to find a string that matches. Previously, it was implemented by comparing every single item with the result string, but now my team wants it to run faster. I cannot use a hash map because we are searching through multiple datasets to find a string so I need an alternative. Please help, thank you!
//Looking for a specific string (time) in data set
foreach(var dataset in datasets)
{
    if(dataset.Tables[0].Rows[i].ItemArray[0].ToString() == time.ToString())
      {
      //Enter this block
      }
}

A: Use bitmaps. For example this one here - https://github.com/Auralytical/CRoaring.Net

*

*Split your files into tokens, normalize them (to lower, trim, etc)

*Assign index to each unique token (plain list, for example, any new token is just appended at the end)

*If file contain token - set bit at its index.

*You will get compact indexes for each file (sparse bitmap).

All you have to do now is to make the same with your query to get query bitmap, then just scan through all bitmaps to find which files are matched. You can make binary search tree to make it logarithmic.
pros
is that final complexity will be O(N) for indexing, O(log(N)) for finding any query you desire. N - count of documents.
cons
of this approach is if your tokens are random (hashes, md5, telephone numbers, datetimes, etc) - it will work very slow. Because domain is practically infinite and you should ignore those tokens and put them in some kind of offloading tree (or just into key-value database).
PS
This is how most of FullText search engines do it, so you can just straight use ElasticSearch or Lucene shard (which I recommend you to use, because it is simple and very flexible engine, and it is production ready which means there is gazilion of people who use this for most perverted business logic, like building their own search engines or porn story catalogs)


text:
Q: 16.04 Lts doesn't contain auto run and wubi file I have downloaded Ubuntu 16.04 from its website through a torrent, but I am unable to install it because it doesn't contain auto run and wubi files. What to do now?

A: Follow the normal installation procedure:
How do I install Ubuntu?
or specifically for dual boot with Windows 8 or later and Ubuntu 15.10 or later:
http://www.everydaylinuxuser.com/2015/11/how-to-install-ubuntu-linux-alongside.html
This will install it for you.


text:
Q: How to build single nuget package for multiple projects in a solution I have a web application solution with more than one projects within it. I am using Octopack to prepare the build and publish it on to my web server.
My web application deployment structure looks like this
-My Web App (Root folder)
  - WS1 (Virtual directory)
  - WS2 (Virtual directory)
  - PT1
  - PT2
Here, WS1 and WS2 are the virtual directories. PT1 and PT2 are the physical directories representing different projects.
On building my solution which has four different projects corresponding to the deployment structure stated above. Each project has the reference for OCTOPACK, on building the solution with MSBUILD I notice that 4 different nuget packages are built.
Is there any way to build into a single package having the above stated deployment structure for deploying in OCTOPUS DEPLOY. Thanks in advance.

A: I don't think you can because Octopus Deploy doesn't seem to support granularity above the project level.  If you could deploy a solution in total, what you're asking could work, but the process steps available in Octopus are pretty much leveled out at one project each.  I see the allure of one deployment for what is to your way of thinking a single product release with four things in it, but the settings for Octopus obviates a 1:1 ration of sites / services per deploy.
If you ditch Octopus Deploy, you could probably get team city or a build script to make one nuget package, and then you could use powershell, or maybe something like final builder to deploy.  Come to think of it, Final Builder would probably do the whole thing including generating the single package.
But then you lose the awesomeness of the Octopus dashboard.

A: use this parameter while creating the package with octopack /p:OctoPackProjectName=your package filename


text:
Q: How to amend object in an array with duplicate attributes? (XY coordinates) I have an array of objects (nodes) with XY coordinates. Wherever I find a node overlaying another node (with the exact same XY coords) I would like to edit the Y attribute "up" by 3.
id, x, y are all attributes of the objects I am looking at. And collectively held in an Array of nodes.
I am looking to go through the array and whenever a duplicate XY is present, edit the first non-unique instance by adding 3 to the Y attribute. If another duplicate is found, I would like this object's Y attribute to be altered by 6 and so on.
E.g.

NODE      X        Y
node1   267555   666777
node2   267555   666777
node3   245698   656400
node4   267555   666777

I would like node 2 and node 4 to become:
NODE      X        Y
node1   267555   666777
node2   267555   666780
node3   245698   656400
node4   267555   666783

Essentially adding 3 to 'Y' for every instance of a duplicate XY, and doing so for every instance where there are overlying nodes in the array (the real array is much larger).
I have managed to identify duplicates using, but unsure of how to proceed:
duplicates = nodes.group_by{|i| [i.x, i.y] }.select{|k,v| v.length > 1}.values

However I don't want a new array, I wish to amend the original "nodes" array attributes.
Thanks

A: Let's start by creating a class of nodes.
class Nodes
  attr_accessor :name, :x, :y
  def initialize(name, x, y)
    @name = name
    @x = x
    @y = y
  end
end

Next, create the instances shown in the problem.
nodes = [
  Nodes.new("node1", 267555, 666777),
  Nodes.new("node2", 267555, 666777),
  Nodes.new("node3", 245698, 656400),
  Nodes.new("node4", 267555, 666777)
]
  #=> [#<Nodes:0x00005c7949ee8e40 @name="node1", @x=267555, @y=666777>,
  #    #<Nodes:0x00005c7949f57c50 @name="node2", @x=267555, @y=666777>,
  #    #<Nodes:0x00005c7949f57958 @name="node3", @x=245698, @y=656400>,
  #    #<Nodes:0x00005c7949f577a0 @name="node4", @x=267555, @y=666777>]

Now modify the y values as desired. For this we make use of the form of the method Hash::new that takes an argument called the default value. If a hash h has been created this way, h[k] will return the default value if it does not have a key k. This is sometimes called a counting hash.
nodes.each_with_object(Hash.new(0)) do |inst,h|
  y = inst.y
  inst.y += 3 * h[y] if h.key?(y)
  h[y] += 1
end
  #=> {666777=>3, 656400=>1}

Let's see what nodes looks like now.
nodes
  #=> [#<Nodes:0x00005c7949ee8e40 @name="node1", @x=267555, @y=666777>,
  #    #<Nodes:0x00005c7949f57c50 @name="node2", @x=267555, @y=666780>,
  #    #<Nodes:0x00005c7949f57958 @name="node3", @x=245698, @y=656400>,
  #    #<Nodes:0x00005c7949f577a0 @name="node4", @x=267555, @y=666783>]

nodes.map { |inst| [inst.name, inst.x, inst.y] }
  #=> [["node1", 267555, 666777],
  #    ["node2", 267555, 666780],
  #    ["node3", 245698, 656400],
  #    ["node4", 267555, 666783]]