Can 1 beat = 1 eighth note instead of 1 quarter note?

Question: I'm learning basic music theory.  I see that 1 beat = 1 quarter note, but I'm wondering if this rule is strict or can it be modified.
Can 1 beat = 1 eighth note instead of 1 quarter note?
Comment: Does this answer your question? [What is the length of the beat?](https://music.stackexchange.com/questions/44287/what-is-the-length-of-the-beat)
Comment: See https://music.stackexchange.com/a/115907/78419. Also, I'd add to the existing answers that no matter what the time signature says, one can *choose* to feel the pulse as other values instead. So for instance, even in 4/4, if you're practicing at a slow tempo, you can "pretend" to be in 8/8; or, at a fast tempo, it might sound better if you pretend it's 2/2.
Answer: Simple answer - yes, just about any note value can be the 'beat'.
Complicated continued answer - and the time signature doesn't always tell us directly what the beat is!
You'll get told: 'Top number says how many, bottom number says what of'. Far too simplistic.  That's fine for 4/4 - four beats, each a quarter note.  Or 2/2 - two beats, each a half note.  But it doesn't work for the (very common) 6/8, which ISN'T six beats each an 8th, it's two beats, each a dotted quarter.   And 3/4 (or 3/8) can be three quarter-note beats or 'one-in-the-bar'.  And just to confuse you further, 3/8 has traditionally been used for both very brisk and quite slow music - it isn't by any means always 'faster than 3/4'.
Answer: Yes. Any note type can represent one beat. This is indicated by the bottom number in a time signature.
For example,

3/2 = three half-note beats per measure
3/8 = three eighth-note beats per measure
3/16 = three sixteenth-note beats per measure
Comment: Sometimes, in triple and especially in compound meters, the beat is the dotted note one level longer than the level specified by the denominator of the time signature.  For example, 6/8 is frequently two dotted-quarter beats per measure, and 3/4 is occasionally one dotted-half beat per measure.
Answer: The standard way of thinking about it is, as others have said, that the lower number of the time signature tells you which note value corresponds with the beat.  But in real life there's even more flexibility and variation.
This is typically seen at faster tempos.  For example, the scherzo of Beethoven's ninth symphony is in a fast 3/4, but it's way too fast to beat three beats in each bar.  Instead, we say it is "in one" and the beat is the dotted half note.  In some sections, Beethoven even specifies that the measures should be grouped into metrical groups of three or four (ritmo di tre battute and ritmo di quattro battute).
Music in compound meters, typically where the numerator is 6, 9, or 12, is frequently actually in 2, 3, or 4 with the beat being subdivided in 3 (and in the case of 9 and 12 nearly always so).  As an example, think of "Here we go round the mulberry bush" (a.k.a. "this is the way we [do some task]") -- it's awkward and cumbersome to beat in six; beat it in two and you'll get the skipping, dancing rhythm that it deserves.
For basic music theory, the next step after "quarter note gets the beat" should certainly be "the bottom number of the time signature specifies the beat," but do keep in mind that it's not the end of the story.
Answer: It can be, but when you see a time signature where the top number is a multiple of 3, like 6/8, 9/8, or 12/8, it typically represents a beat divided into three instead of two - three eighth notes equals one beat.
Answer: Yes, you can have quaver, crotchet, or minim beats, each one with or without a dot. You can have 2, 3, or 4 beats to a measure with whatever type of beat you like, and in the Modern musical era, composers even experimented with 5 and 7 time ie 5 or 7 beats to a measure.
Answer: Yes. A time signature defines how many beats are in a measure (the top number), and also the note value that is considered a beat (the bottom number). A 4/4 time signature indicates there are 4 quarter notes per measure. A 6/8 time signature indicates there are 6 eighth notes per measure. A 2/2 time signature indicates there are 2 half notes per measure.
Any time signature that is something/8 has eighth notes as beats.
I'll also note that a time signature usually carries implications about the feel or pulse of a piece of music, in addition to the definitional aspect of how the beats should be counted. Any piece written in 4/4 would look the same in 8/8 or 16/16, but the latter two might have different pulse patterns than the usual emphasis on 1 and 3 in a 4-beat measure. You could write a triplet-feel piece in 2/4, but it might be a better fit for 6/8.
Comment: Sometimes, in triple and especially in compound meters, the beat is the dotted note one level longer than the level specified by the denominator of the time signature.  For example, 6/8 is frequently two dotted-quarter beats per measure, and 3/4 is occasionally one dotted-half beat per measure.
Comment: @phoog Those are pulses, not beats, although colloquially they're sometimes referred to as the same. The 8 in 6/8 defines the eighth note as the beat, but they're usually organized in threes, yielding a dotted quarter note *pulse*. A 6/8 time signature does not have 2 dotted quarter note beats per measure, nothing in the time signature references 2 beats or dotted quarter notes.
Comment: "Those are pulses, not beats": is there a meaningful distinction between pulses and beats other than the circular "the beat is the unit of time specified by the bottom number of the time signature"?  Have you ever been in a rehearsal where a conductor has said "I'll conduct dotted quarter pulses" instead of "I'm beating the 6/8 section in 2" or something similar?
Comment: @phoog Tempo is defined in terms of "beats per minute" - that exclusively refers to the beat unit defined by the time signature, not the stylistic pulse (which can change without modifying the time signature/beat). If you interpret a 6/8 piece as having 2 dotted quarter beats, you'll be playing it 3x too fast according to the noted BPM.
Comment: (Setting aside any quibbles with that definition of "tempo",) that still seems circular. Metronome markings for compound-meter works are rarely given in eighth notes. I might expect that only for a truly lugubrious compound pulse, like some of the somnambulant slow-movements-of-the-Bach-double or pastoral-symphonies-from-Messiah that I've had the misfortune to play.
Comment: @Nuclear Hoagie No.  6/8 is not 6 beats in the bar, it's two.  If there's a BPM indication it will be the number of dotted quarter beats per minute.  Even sequencer programs know this!
Comment: "that exclusively refers to the beat unit defined by the time signature": no it doesn't; it refers to the time unit indicated by the composer in the metronome marking, which includes a note value, an equals sign, and a BPM indication. "If you interpret a 6/8 piece as having 2 dotted quarter beats, you'll be playing it 3x too fast according to the noted BPM": not if the composer has equated the given BPM with the dotted quarter note.  The first example I found was Verdi's _Libiam',_ in 3/8 at dotted quarter = 69.  He could have specified eighth=208, but he didn't, because it's one beat per bar.
Comment: @AndyBonner fortunately or otherwise, Bach and Handel predate the metronome.  But slow 3/8 and 6/8 are not uncommon in post-metronome compositions, either.  Bach however makes a good case for dotted notes as the beat unit in compound meters when he has different instruments simultaneously in 12/8 and 4/4 in some of his pieces, though I done have an example handy at the moment.
Answer: The beat is whatever the denominator of the time signature says it is. Quarter in n/4 times (e. g. 3/4), eighth in n/8 times (e. g. 12/8), half in n/2 times (e. g. 2/2).
So, yes. It can be the eighth.
Comment: @Divizna No, too simplistic.   12/8 is vanishingly unlikely to be 12 beats to the bar!
Comment: Sometimes, in triple and especially in compound meters, the beat is the dotted note one level longer than the level specified by the denominator of the time signature.  For example, 6/8 is frequently two dotted-quarter beats per measure, and 3/4 is occasionally one dotted-half beat per measure.


Syntax error on Ruby script

Question: I need to get past a syntax error in a Redmine plugin. My Ruby version is 2.2.3.
The script is:
module RedmineAnonymousWatchers
  module WatchersHelperPatch
    unloadable

    def self.included(base)
      base.send(:include, InstanceMethods)
      base.class_eval do
        alias_method_chain :watchers_checkboxes, :anonymous
        alias_method_chain :watchers_list, :anonymous
        alias_method_chain :watcher_link, :anonymous
      end
    end
    module InstanceMethods
      def watcher_link_with_anonymous(object, user)
        return watcher_link_without_anonymous(object, user) unless user && user.anonymous? && object.respond_to?('watched_by?')
        return '' unless User.current.allowed_to?(:subscribe_anonymously, nil, :global => true)
        include_anonymous_watchers_tags
        watched = cookies[:anonymous_token] && object.watched_by?(AnonymousWatcher.new(:anonymous_token => cookies[:anonymous_token]))
        url = {:controller => 'watchers',
               :action => (watched ? 'anonymous_unwatch' : 'anonymous_watch'),
               :object_type => object.class.to_s.underscore,
               :object_id => object.id}
        link_to((watched ? l(:button_unwatch) : l(:button_watch)), url,
                :class => (watched ? 'icon icon-fav' : 'icon icon-fav-off'),
                :onclick => watched ? "return anonymousUnwatch(this.href);" :
                    "return anonymousWatch(#{l(:text_enter_watcher_email).to_json}, #{(cookies[:watcher_mail] || cookies[:author_mail] || "").to_json}, this.href);")
      end
      def watchers_list_with_anonymous(object)
        str = watchers_list_without_anonymous(object)
        remove_allowed = User.current.allowed_to?("delete_#{object.class.name.underscore}_watchers".to_sym, object.project)
        content = ''.html_safe
        object.watcher_mails.collect do |mail|
          s = ''.html_safe
          s << link_to(mail, "mailto:"<<mail, :class => 'mail')
          if remove_allowed
            url = {:controller => 'watchers',
                   :action => 'destroy',
                   :object_type => object.class.to_s.underscore,
                   :object_id => object.id,
                   :mail => mail}
            s << ' '
            if Redmine::VERSION::MAJOR >= 2
              s << link_to(image_tag('delete.png'), url,
                           :remote => true, :method => 'delete', :class => "delete")
              # Redmine < 2.2
              #s << link_to(image_tag('delete.png'), url,
              #             :remote => true, :method => 'post', :style => "vertical-align: middle", :class => "delete")
            else
              s << link_to_remote(image_tag('delete.png'), {:url => url}, :href => url_for(url),
                           :style => "vertical-align: middle", :class => "delete")
            end
          end
          content << content_tag('li', s)
        end
        content.present? ? str + content_tag('ul', content) : str
      end
      def watchers_checkboxes_with_anonymous(object, users, checked=nil)
        str = watchers_checkboxes_without_anonymous(object, users, checked)
        mails = object && object.watcher_mails || @watcher_mails
        mails ? str + mails.map do |mail|
          c = checked.nil? ? object.watched_by?(mail) : checked
          tag = check_box_tag 'issue[watcher_mails][]', mail, c, :id => nil
          content_tag 'label', "#{tag} #{h(mail)}".html_safe,
                      :id => "issue_watcher_mails_"+mail.gsub(/[^\w]+/, '_'),
                      :class => "floating"
        end.join.html_safe : str
      end
    end
  end
end

The syntax errors are in the last method (watchers_checkboxes_with_anonymous). The first error is:
 syntax error, unexpected keyword_do_cond, expecting ':'
        mails ? str + mails.map do |mail|

The second error is:
syntax error, unexpected ':'
        end.join.html_safe : str

And finally I get:
syntax error, unexpected keyword_end, expecting end-of-input

Any ideas how to fix this?
Comment: if in doubt on operator precedence, just add parenthesis.
Answer: Your ternary operator syntax at
mails ? str + mails.map do |mail|

is causing the issue.
Answer: This block:
mails ? str + mails.map do |mail|
      c = checked.nil? ? object.watched_by?(mail) : checked
      tag = check_box_tag 'issue[watcher_mails][]', mail, c, :id => nil
      content_tag 'label', "#{tag} #{h(mail)}".html_safe,
                  :id => "issue_watcher_mails_"+mail.gsub(/[^\w]+/, '_'),
                  :class => "floating"
    end.join.html_safe : str

should be rewritten as:
mails ? (str + mails.map do |mail|
      c = checked.nil? ? object.watched_by?(mail) : checked
      tag = check_box_tag 'issue[watcher_mails][]', mail, c, :id => nil
      content_tag 'label', "#{tag} #{h(mail)}".html_safe,
                  :id => "issue_watcher_mails_"+mail.gsub(/[^\w]+/, '_'),
                  :class => "floating"
    end.join.html_safe) : str

or, even better:
str.tap do |str|
  str << mails.map do |mail|
      c = checked.nil? ? object.watched_by?(mail) : checked
      tag = check_box_tag 'issue[watcher_mails][]', mail, c, :id => nil
      content_tag 'label', "#{tag} #{h(mail)}".html_safe,
                  :id => "issue_watcher_mails_"+mail.gsub(/[^\w]+/, '_'),
                  :class => "floating"
    end.join.html_safe if mails
end

The operator precedence matters.
Comment: Thanks a bunch. That advanced me through this particular obstacle.

Regretfully, only to find out that this particular Redmine plugin does not work with the most recent version of Redmine (v3.2.0).

Any chance any of you guys are using Redmine and have adapted the Anynymous Watchers plugin for Redmine 3.2.0 ?

Syntax error on Ruby script


High Load Average But CPU And Memory Are Not Used NGINX

Question: First of all I want to explain what I am using the server for.
This server is used to deliver downloadable files. Specially video games which I upload to the server and then users can download it through form action. Below is the link to the source where the download file is requested.
The problem I am facing is that I have Intel Core i7 8 Cores 12 GB Ram dedicated server. And whenever I let my users download files through the server it starts generating high load average and the server is then unable to fetch downloads through the PHP pages that I created it for.
I have also attached my Nginx.conf and other screenshots so do check them out.
And one more thing: whenever I restart my nginx its gets ultra fast despite the load average but then again slows down after a minute.
You can check here this is the source where the download file is requested
worldofpcgames.net/fairy-fencer-f-advent-dark-force-free-download/
HERE IS MY NGINX->
user nginx;
worker_processes 8;
worker_rlimit_nofile 5000;
error_log /var/log/nginx/error.log;
pid /run/nginx.pid;

# Load dynamic modules. See /usr/share/nginx/README.dynamic.
include /usr/share/nginx/modules/*.conf;

events {
    worker_connections 3000;
    use epoll;
    multi_accept on;
}

http {
    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';

    access_log  /var/log/nginx/access.log  main;

    sendfile            on;
    tcp_nopush          on;
    tcp_nodelay         on;
    keepalive_timeout   65;
    types_hash_max_size 2048;

    include             /etc/nginx/mime.types;
    default_type        application/octet-stream;

    # Load modular configuration files from the /etc/nginx/conf.d directory.
    # See http://nginx.org/en/docs/ngx_core_module.html#include
    # for more information.
    include /etc/nginx/conf.d/*.conf;

    server {
        listen       80 default_server;
        listen       [::]:80 default_server;
        server_name  _;
        root         /mnt/www/html;
    index index.php;
        # Load configuration files for the default server block.
        include /etc/nginx/default.d/*.conf;

        location / {
        try_files $uri $uri/ =404;
    }
    error_page 404 /404.html;
    error_page 500 502 503 504 /50x.html;
    location = /50x.html {
        root /usr/share/nginx/html;
    }

    location ~ \.php$ {
        try_files $uri =404;
        fastcgi_pass unix:/var/run/php-fpm/php-fpm.sock;
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        include fastcgi_params;
    }
        location /protected {
            root /mnt/www/html;
            secure_link $arg_md5,$arg_expires;
            secure_link_md5 "$secure_link_expires$uri$remote_addr enigma";

            if ($secure_link = "") { return 403; }
            if ($secure_link = "0") { return 410; }
    error_page 403 /blocked.html;
        }
}

# Settings for a TLS enabled server.
#
#    server {
#        listen       443 ssl http2 default_server;
#        listen       [::]:443 ssl http2 default_server;
#        server_name  _;
#        root         /usr/share/nginx/html;
#
#        ssl_certificate "/etc/pki/nginx/server.crt";
#        ssl_certificate_key "/etc/pki/nginx/private/server.key";
#        ssl_session_cache shared:SSL:1m;
#        ssl_session_timeout  10m;
#        ssl_ciphers HIGH:!aNULL:!MD5;
#        ssl_prefer_server_ciphers on;
#
#        # Load configuration files for the default server block.
#        include /etc/nginx/default.d/*.conf;
#
#        location / {
#        }
#
#        error_page 404 /404.html;
#            location = /40x.html {
#        }
#
#        error_page 500 502 503 504 /50x.html;
#            location = /50x.html {
#        }
#    }

}

And HERE IS THE NGINX error log ->
And one more thing i havent configured my PHP or Mysql at all. I just installed them and did the basic settings such as changed the user and owner group to nginx. and listen
HERE are the screenshot of TOP->

atop -c

And i am on Centos7
So please help me out

Sorry here is the nginx.conf couldn't link above because I don't have reputation points
https://drive.google.com/open?id=0ByamFYoTQ6KRRFpnUWJ3VGNxUEE
Comment: The problem is obviously with the disk `/dev/sdc`. It can't keep up with all the demand placed on it. That might be because the drive is defective or it might be because you have more traffic than it can handle.
Comment: @MichaelHampton when you say "obviously", perhaps you could point out which piece of information led you to this, to help others who'd like to learn.
Comment: @Tim It's so blatantly a problem that `atop` was kind enough to print it in red text. So, yes, it's obvious where the problem lies. What's not obvious is the underlying cause; as I mentioned there are a couple of possibilities.
Comment: @Tim it would be a combination of the high I/O wait and the red line that says `sdc` is at 100% utilization.
Comment: Also the fact that so many nginx process are in a `D` state, which is waiting on I/O.
Comment: So whats the fix and the drive is not faulty for sure, they are brand new.
Comment: Well, that doesn't mean it *can't* be faulty. You may want to grab SMART data from the drive via something like `smartctl -a /dev/sdc`. In addition, we don't know your LVM configuration, and you might be running a linear logical volume that's only allocating to the first disk and thus only reading from it. That would be more of a capacity planning problem, though.
Answer: The problem is your disk iowait (sdc). Look at the red lines of your screen shot called atop -c. This would cause high load average but low cpu usage. What is your lvm configuration?
update: @MichaelHampton pointed this out before me, in the comments.


JavaScript sub object is not accessible

Question: I am new to object handling in JavaScript and I got stuck on a problem. I hope you can help me.
To understand what I am doing here: I have a multilevel object with two different phone numbers (short codes) for each country. Since the list got too long, I added a category for "Europe". When I try to access the data of the sub object, my reference is always undefined but my console.log(l2) is stating that the sub is there and should have the defined properties.
Can you help me to understand why the properties are undefined or what I am doing wrong?
Fiddle: https://jsfiddle.net/qsov54an/
JS:
langs = {
    "CRA": {flag: '',cs:'4262',as:''},
    "Reviews": {flag: '',cs:'72074301',as:''},
    "Europe": {
        "Bulgarian": {flag: 'bg',cs:'4668',as:''},
        "Croatian": {flag: 'hr',cs:'4671',as:'4707'},
        "Czech": {flag: 'cz',cs:'4365',as:'4553'},
        "Danish": {flag: 'dk',cs:'4357',as:'4526'},
        "Dutch": {flag: 'nl',cs:'4343',as:'4511'},
        "English": {flag: 'gb',cs:'4164',as:'4482'},
        "Finnish": {flag: 'fi',cs:'4092',as:''},
        "Flemish": {flag: 'be',cs:'4500',as:''},
        "French": {flag: 'fr',cs:'4344',as:'4781'},
        "German": {flag: 'de',cs:'4345',as:'4473'},
        "Hungarian": {flag: 'hu',cs:'4221',as:'4729'},
        "Italian": {flag: 'it',cs:'4348',as:'4485'},
        "Latvian": {flag: 'lv',cs:'4674',as:''},
        "Lithuanian": {flag: 'lt',cs:'4673',as:''},
        "Norwegian": {flag: 'no',cs:'4356',as:'4533'},
        "Polish": {flag: 'pl',cs:'4351',as:'4512'},
        "Spanish": {flag: 'es',cs:'4346',as:'4524'},
        "Swedish": {flag: 'se',cs:'4349',as:'4554'},
        "Portuguese (PT)": {flag: 'pt',cs:'4347',as:'4522'},
        "Romanian": {flag: 'ro',cs:'4675',as:''},
        "Turkish": {flag: 'tr',cs:'4355',as:'4530'},
    },
    "Cantonese": {flag: 'cn',cs:'',as:''},
    "Chinese": {flag: 'cn',cs:'4353',as:'4752'},
    "English": {flag: 'us',cs:'4164',as:'4482'},
    "Estonian": {flag: 'ee',cs:'4669',as:''},
    "Hebrew": {flag: 'il',cs:'4670',as:'4727'},
    "Icelanding": {flag: 'is',cs:'4672',as:''},
    "Indonesia": {flag: 'id',cs:'4368',as:'4713'},
    "Japanese": {flag: 'jp',cs:'4265',as:'4717'},
    "Korean": {flag: 'kp',cs:'4366',as:''},
    "Malay": {flag: 'ms',cs:'4367',as:''},
    "Portuguese (BR)": {flag: 'br',cs:'4552',as:'4781'},
    "Russian": {flag: 'ru',cs:'4350',as:'4559'},
    "Serbian": {flag: 'rs',cs:'4677',as:''},
    "Slovenian": {flag: 'si',cs:'4676',as:''},
    "Tagalog": {flag: '',cs:'4678',as:''},
    "Thai": {flag: 'th',cs:'4354',as:'4555'},
    "Vietnamese": {flag: 'vn',cs:'4679',as:''}
};

$.each( langs, function( key, l ) {
    //console.log('length L:',Object.keys(l).length,l);
    if(Object.keys(l).length > 3)
    {
            if(key == "Europe") flag = 'eu';
            else flag = '';
            html  = '
';
            html += '   '+key+'';
            html += '
';

            $.each( l, function( key2, l2 ) {
                console.log(key2,l2);
                if(l2.cs.length < 8)
                    l2.cs = '7108' + l.cs;
                if(l2.as.length < 8 && l2.as.length > 0)
                    l.as = '7108' + l.as;
                if(l2.as !== '')
                {
                    html += '
';
                    html += '   '+key2+'';
                    html += '
';
                    html += '
CS: '+l2.cs.substring(4,8)+'
';
                    html += '
AS: '+l2.as.substring(4,8)+'
';
                    html += '
';
                    html += '
';
                }
                else
                {
                    html += '
';
                    html += '   '+key2+'';
                    html += '
';
                }

            });

            $('#btb_lang_list').append(html);
    }
    else
    {
        if(l.cs.length < 8)
            l.cs = '7108' + l.cs;
        if(l.as.length < 8 && l.as.length > 0)
            l.as = '7108' + l.as;
        if(l.as !== '')
        {
            html  = '
';
            html += '   '+key+'';
            html += '
';
            html += '
CS: '+l.cs.substring(4,8)+'
';
            html += '
AS: '+l.as.substring(4,8)+'
';
            html += '
';
            html += '
';
        }
        else
        {
            html  = '
';
            html += '   '+key+'';
            html += '
';
        }

        $('#btb_lang_list').append(html);
    }
});

Comment: Could you please shorten your code/example and indicate where you're getteng an undefined reference ?
Comment: Did you try this: `langs.Europe`?
Answer: I think your 2nd loop is trying to access a variable which it doesn't have:
$.each( l, function( key2, l2 ) {
within that, you try to reference l.cs in your function( key2, l2 ), but that function doesn't know what l is, so it returns an empty local object (and undefined for l.cs)
I'm not sure, but that's my first guess from looking at it.
Comment: So, I was wrong here. `l` is accessible, but it's the array of subcountries, so it doesn't contain a `.cs` property. @nilsK provides the correct answer.
Comment: thank you! I was already sure that I forgot a "2" somewhere, but was not able to find it. Now it works perfectly
Answer: The error is in line 81 in your fiddle.
Change
l2.cs = '7108' + l.cs;
to
l2.cs = '7108' + l[key2].cs;
l is your first categorie (e.g. "Europe") wich doesn't have a property named cs. You'll need to use the countries names to get your property.
Comment: Yep, this looks like it's the problem.
Comment: No, the problem was that it should be `l2.cs = '7108' + l2.cs;`. But thanks. You pointed out the line with the error ^^
Comment: well, okay, but `l[key2].cs` works too. glad you could solve your problem.
Answer: It works if you remove the quotes from Europe, Bulgarian, etc
Comment: This not possible because my keys have white spaces.

JavaScript sub object is not accessible


How to broadcast a message to all geventwebsocket clients

Question: I'm setting up a geventwebscoket app in python using gevent-websocket.
In on of the examples (chat-app) that is pretty much the same as my application, I define an app that handles websocket connections and messages like this:

import json

from gevent import monkey
monkey.patch_all()

from flask import Flask, render_template
from werkzeug.debug import DebuggedApplication

from geventwebsocket import WebSocketServer, WebSocketApplication, Resource

flask_app = Flask(__name__)
flask_app.debug = True

class ChatApplication(WebSocketApplication):
    def on_open(self):
        print("Some client connected!")

    def on_message(self, message):
        if message is None:
            return

        message = json.loads(message)

        if message['msg_type'] == 'message':
            self.broadcast(message)
        elif message['msg_type'] == 'update_clients':
            self.send_client_list(message)

    def send_client_list(self, message):
        current_client = self.ws.handler.active_client
        current_client.nickname = message['nickname']

        self.ws.send(json.dumps({
            'msg_type': 'update_clients',
            'clients': [
                getattr(client, 'nickname', 'anonymous')
                for client in self.ws.handler.server.clients.values()
            ]
        }))

    def broadcast(self, message):
        for client in self.ws.handler.server.clients.values():
            client.ws.send(json.dumps({
                'msg_type': 'message',
                'nickname': message['nickname'],
                'message': message['message']
            }))

    def on_close(self, reason):
        print("Connection closed!")

@flask_app.route('/')
def index():
    return render_template('index.html')

WebSocketServer(
    ('0.0.0.0', 8000),

    Resource([
        ('^/chat', ChatApplication),
        ('^/.*', DebuggedApplication(flask_app))
    ]),

    debug=False
).serve_forever()

I want to have some scheduled processes in my code that send a message to every client connected to the websocket.
In the examples and the limited documentation I find no way of calling the broadcast method from somewhere else in the project. Every message/broadcast has to be sent as a reaction to a received message (as I understand it).
I tried to figure it so I tried broadcasting a message every time someone visits the index page:
@flask_app.route('/')
def index():
    chat_application = ChatApplication()
    chat_application.broadcast("A new user on the page!")
    return render_template('index.html')

This throws an error:
chat_application = ChatApplication()
TypeError: __init__() missing 1 required positional argument: 'ws'

Long story short:
I do not know how to send a message to every client on the websocket since I need the ChatApplication instance to access the broadcast function and I can't seem to figure out how to create a ChatApplication object to let me call that function.
Answer: I figured it out.
By starting a server like this
server = WebSocketServer(
    ('0.0.0.0', 8000),

    Resource([
        ('^/chat', ChatApplication),
        ('^/.*', DebuggedApplication(flask_app))
    ]),

    debug=False
)

server.serve_forever()

you can access all the clients and send them a message like this
for client in server.clients.values():
    client.ws.send("whatever you want to send")


Simple hit counter (as block)?

Question: I need to implement kind of a hit counter for the entire page (so how often the site was visited) in D7.
For D6 we got the Counter module, but is there any simple way to do it? Perhaps with a custom block and some PHP code?
Answer: You could use the core Statistics module as described here.
You could use Visitors module.
I use Google Analytics but this might be too heavy if you need a basic solution.
Comment: The link to the core module instructions no longer works (Jan 21 2015)
Answer: You could use the mostpopular module for this.

The module is pre-packaged with several services including:

Drupal - Most Viewed pages (using Statistics module)
Drupal - Most Commented pages (from simple database query)
Google Analytics - Most Viewed pages
AddThis.com - Most Shared pages
Disqus.com - Most Commented pages The system defines Drupal hooks to allow new services to be created, which can pull data from third
  party providers or internally from Drupal.

The system also provides an API to help service plugins normalize their results and exclude certain pages, as configured by the administrator.

For more detail about the module you could visit this.

Simple hit counter (as block)?


How do I programmatically add an image while programmatically creating nodes?

Question: I'm writing a script to add nodes programmatically, and I don't know the proper way to add/attach image. Actually I'm not that familiar with Drupal.
Here are the (sample) image objects I found while print_ring the existing $node I'm using:

field_image: Array ( [und] => Array ( [0] => Array ( [fxid] => 3089 [alt] => [title] => [width] => 95 [height] => 126 [uid] => 249 [filename] => helloworld.jpg [uri] => public://helloworld.jpg [filemime] => image/jpeg [filesize] => 3694 [status] => 1 [timestamp] => 1346748001 [type] => image [media_title] => Array ( ) [media_description] => Array ( ) [field_tags] => Array ( ) [field_license] => Array ( [und] => Array ( [0] => Array ( [value] => nothing ) ) ) [metatags] => Array ( ) [rdf_mapping] => Array ( ) ) ) )

The next one I found is the following.

field_temp_image: Array ( [und] => Array ( [0] => Array ( [value] => http://www.example.com/sample-path/helloworld.jpg [format] => [safe_value] => http://www.example.com/sample-path/helloworld.jpg ) ) ) `

How should I add an image to that node in that way?
Answer: Let suppose your image fields in field_body_images ,
first load your node by node_load
and record your image in file tables and add it to your node image field
I hope this sample help you to achieve :
$n=  node_load($nid);
$file = new stdClass();
$file->filename =$file_name;
$file->filemime =file_get_mimetype($localimagepath.$file_name);
$file->filesize = @filesize(file_create_path($localimagepath.$file_name));
$file->uid = $user->uid;
$file->status = 1;
$file->timestamp = time();
$file->list=1;
$file->data=array('alt'=>'','title'=>$n->title);
drupal_write_record('files', $file);
$record->fid=$file->fid;
$n->field_body_images[]=(array)$file;
node_save($n);

Comment: There's some code to demonstrate this in devel_generate: http://drupalcontrib.org/api/drupal/contributions%21devel%21devel_generate%21image.devel_generate.inc/7 Devel_generate of course generates dummy content for Drupal sites, including images. It's part of the Devel package: http://drupal.org/project/devel
Comment: Do not forget to add `file_usage_add($file, 'file', 'node', $n->nid);` in the end to prevent the file from accidental deletion.
Comment: @Neograph734 it will add when `node_save` getting triggered.
Comment: @Neograph734 you're welcome ;). tnx for your attention
Answer: Drupal 8
For Drupal 8 it would go like following. First add the file and get a file ID. Then create the node and attach the given file ID.
$data = file_get_contents(__DIR__ . '/images/my_image.jpeg');
$file = file_save_data($data, 'public://my_image.jpeg');

$node = \Drupal\node\Entity\Node::create([
  'type'             => 'page',
  'title'            => 'Foobar',
  'field_my_image' => [
    'target_id' => $file->id(),
    'alt'       => 'Lorem ipsum',
    'title'     => 'Dolor sit amet',
  ],
]);

$node->save();

Answer: May be not exactly what you need, but why not just add a reference to an image in a field, like your example 2 suggests ? And then in content template file render that field as an image.
In node creation stream:
$node->field_image['und'][0]['value'] = "/path_to_image/image.jpg";

In content type:
<?php
global $base_url;
$image_source_link=$base_url . $node->field_image['und'][0]['value'];
?>
<img src="<?php print($image_source_link); ?>" />

Answer: In a Drupal 8 form submit callback, with entityTypeManager:
public function submitForm(array &$form, FormStateInterface $form_state) {
  // Get values from a managed_file widget.
  $files = $form_state->getValue('uploaded_images');

  $storage_file = $this->entityTypeManager->getStorage('file');
  $storage_node = $this->entityTypeManager->getStorage('node');

  $field_image = [];

  foreach ($files as $fid) {
    /** @var \Drupal\file\Entity\File $file */
    $file = $storage_file->load($fid);
    // Set the file status to permanent.
    $file->setPermanent();
    $file->save();

    $field_image[] = [
      'target_id' => $file->id(),
      'alt'       => '',
    ];
  }

  $values = [
    // Node bundle.
    'type'           => 'gallery',
    // Node title.
    'title'          => 'Gallery',
    // Node status: active.
    'status'         => 1,
    // Author ID.
    'uid'            => \Drupal::currentUser()->id(),
    // Uploaded images.
    'field_image'    => $field_image,
  ];

  /** @var \Drupal\node\Entity\Node $entity */
  $entity = $storage_node->create($values);
  $entity->save();
}


Find all primes $p$ such that $p^2-p+1$ is a perfect cube

Question: Find all primes $p$ such that $p^2-p+1$ is a perfect cube.
I found out that p is of the form $18n+1$ and $p=19$ is a solution but I am not getting anything further.
$p^2-p-(m^3-1)=0$
$1+4(m^3-1)=k^2$
$4m^3-3=k^2$
every square is $0,1,4 or 7(\mod9)$ and every cube is $0,1 or 8\mod9$
Using this fact we can conclude that $m^3\equiv{1\mod 9}$
Hence $k$ is either $1$ or $-1$ $\mod9$
But $k\equiv{-1\mod9}$ is not possible since $p$ is a prime. So putting  $k\equiv{1\mod9}$ in the quadratic formula we get $p\equiv{1\mod9}$ and since $p$ is odd(as $p=2$ is not a solution),  $p\equiv{1\mod18}$
Comment: You might like to edit your question to include that information.
Comment: How did you find that $p$ has the form $18 n + 1$?
Comment: @Travis I made quadratic in terms of $p$ and made discriminent perfevt square. Then I took mod(9) Since every cube is either $0,1$ or $-1$ mod(9).
Comment: @Travis I have edited the question.
Comment: Not sure if this helps, but note that if $n = p^2 - p + 1$ then $n-p$ is a perfect square. So you need a cube that is a prime larger than a perfect square.
Comment: A similar question without the condition that $p$ is prime: [$x^2+x+1$ is the cube of a prime.](https://math.stackexchange.com/q/394240)
Answer: this is an easier answer:
$$$$we have$$p^2-p=p(p-1)=m^3-1=(m-1)(m^2+m+1)$$we can see $p>m-1$ so we have $$p-1|m-1\to p=1\, MODm-1$$and we have$$m^2+m+1=3\, MODm-1$$we know $$p|m^2+m+1$$ so we have$$m^2+m+1=3p\, or\, m^2+m+1\ge (m+2)p$$if $$m^2+m+1=3p$$ we can see p=19,we have $3(m-1)=p-1$ so we have $m^2+m+1=9m-6$ so m=1 or
,m=7,p=19,$$$$if $$m^2+m+1\ge (m+2)p$$ we have$$(m+2)(m-1)\ge p-1$$ so $$m^2+m-1\ge p=(m^2+m+1)/m+2$$because $m>1$ it is clearly impossible.
Comment: ali, this is all one sentence, without any line breaks. It's impossible to read, even if it's correct.
Comment: i edited the answer@TonyK
Comment: That's much better!
Answer: you can work in $Z[1/2+\sqrt{-3}/2]$.we have unique factorization in this ring,and units are $1,-1,1/2+\sqrt{-3}/2,1/2-\sqrt{-3}/2$,and 2 is prime,yo can easily check this facts by the norm
$N(a+b\sqrt{-3})=a^2+3b^2$
we have
$4m^3=k^2+3=(k-\sqrt{-3})(k+\sqrt{-3})$,we can see $gcd((k-\sqrt{-3}),(k+\sqrt{-3})|2\sqrt{-3}$
and because$(k,3)=1$ we have $gcd((k-\sqrt{-3}),(k+\sqrt{-3})=2 or 1 $and we have$4(a/2+\sqrt{-3}b/2)\not=k+\sqrt{-3}$ so we have this cases:
$$1:k+\sqrt{-3}=2(a/2+\sqrt{-3}b/2)^3,k-\sqrt{-3}=2(a/2-\sqrt{-3}b/2)^3$$
$$2:k+\sqrt{-3}=(1+\sqrt{-3})(a/2+\sqrt{-3}b/2)^3,k-\sqrt{-3}=(1-\sqrt{-3})(a/2-\sqrt{-3}b/2)^3$$
$$3:k+\sqrt{-3}=(1-\sqrt{-3})(a/2+\sqrt{-3}b/2)^3,k-\sqrt{-3}=(1+\sqrt{-3})(a/2-\sqrt{-3}b/2)^3$$
in case 1 by take imaginary part we have:$2(-3b^3/8+3a^2b/8)=1$ so case 1 is impossible.
in case 2 by take real and imaginary part we have :
$$-3b^3/8+3a^2b/8=1-k=2p$$
$$a^3/8-9ab^2/8=k+3$$
because $p\not=3$ case 2 is impossible
case 3:we have
$$-3b^3/8+3a^2b/8=1+k=2-2p$$
$$a^3/8-9ab^2/8=k-3=-2-2p$$
$$-3b^3/8+3a^2b/8+a^3/8-9ab^2/8=-4p$$
i cant go further in this case
Comment: This is a problem of INMO, a high school level examination. so there should be a simpler solution other than using Ring Theory.


SELECT * BETWEEN AND

Question: I'm trying to select a list of events from a database with MySQL. I'm fairly new to php but usually I can figure stuff out. cant seam to get this to work though..
function get_events_within_dates($da,$dd) {
    global $connection;
    $query = "SELECT *
        FROM events
        WHERE date
        BETWEEN STR_TO_DATE('$da','Y-m-d') AND STR_TO_DATE('$dd','Y-m-d')
        ORDER BY date ASC";

I've used $da and $dd as date of arrival and date of departure..
I can get it to work fine when I replace the variables with exact dates, tried messing around with STR_TO_DATE() and that didn't help either. Any help appreciated.
Answer: You are missing % in the format string. Use STR_TO_DATE() as:
   STR_TO_DATE('$da','%Y-%m-%d')

Full query as below:
   $query = "SELECT *
             FROM events
             WHERE date BETWEEN STR_TO_DATE('$da','%Y-%m-%d')
                        AND STR_TO_DATE('$dd','%Y-%m-%d')
             ORDER BY date ASC";

Comment: oh man i knew it would end up being something stupid too. thanks a lot

SELECT * BETWEEN AND


How do you calculate the expectation of $\left(\sum_{i=1}^n {X_i} \right)^2$?

Question: If $X_i$ is exponentially distributed $(i=1,...,n)$ with parameter $\lambda$ and $X_i$'s are mutually independent, what is the expectation of
$$ \left(\sum_{i=1}^n {X_i} \right)^2$$
in terms of $n$ and $\lambda$ and possibly other constants?
Note: This question has gotten a mathematical answer on https://math.stackexchange.com/q/12068/4051. The readers would take a look at it too.
Comment: The two copies of this question reference each other and, appropriately, the stats site (here) has a statistical answer and the math site has a mathematical answer.  It seems like a good division: let it stand!
Answer: If $x_i \sim Exp(\lambda)$, then (under independence), $y = \sum x_i \sim Gamma(n, 1/\lambda)$, so $y$ is gamma distributed (see wikipedia). So, we just need $E[y^2]$. Since $Var[y] = E[y^2] - E[y]^2$, we know that $E[y^2] = Var[y] + E[y]^2$. Therefore, $E[y^2] = n/\lambda^2 + n^2/\lambda^2 = n(1+n)/\lambda^2$ (see wikipedia for the expectation and variance of the gamma distribution).
Comment: The math answer computes the integrals using linearity of expectation.  In some ways it's simpler.  But I like your solution because it exploits *statistical* knowledge: because you know a sum of independent Exponential variables has a Gamma distribution, you're done.
Comment: I enjoyed it quite a bit and I am by no means a statistician or a mathematician.
Comment: @Dilip The mathematician tends to see this question as asking for an integral and proceeds directly to integrate it. The statistician re-expresses it in terms of familiar statistical quantities, such as the variance, and familiar statistical relationships, such as that the Exponential is Gamma and the Gamma family is closed under convolution. The answers are the same but the approaches are completely different. Then there's the question of what "doing an integration" really means. For example, [this complicated integral](http://math.stackexchange.com/a/3972) is done purely algebraically.
Comment: Thanks. A very neat way of answering the question (leading to the same answer) was also provided on math.stackexchange (link above in the question) a few minutes ago.
Comment: very elegant answer.
Comment: @whuber I don't understand what distinction between _statistical_ knowledge and _mathematical_ knowledge you are trying to draw in your comment.  _Somewhere_ one needs to do an integration to compute expectations, or to know a trustworthy source where someone else's results on $E[X]$ and $E[X^2]$ can be looked up (statistical knowledge?), whether it is of a Gamma random variable or the exponential random variable as Macro used. Also, is it possible to _prove_ the result that $\text{var}(Y) = E[Y^2] - (E[Y])^2$ that Wolfgang used without using the linearity of expectation?
Answer: The answer above is very nice and completely answers the question but I will, instead, provide a general formula for the expected square of a sum and apply it to the specific example mentioned here.
For any set of constants $a_1, ..., a_n$ it is a fact that
$$ \left( \sum_{i=1}^{n} a_i \right)^2 = \sum_{i=1}^{n} \sum_{j=1}^{n} a_{i} a_{j} $$
this is true by the Distributive property and becomes clear when you consider what you're doing when you calculate $(a_1 + ... + a_n) \cdot (a_1 + ... + a_n)$ by hand.
Therefore, for a sample of random variables $X_1, ..., X_n$, regardless of the distributions,
$$ E \left( \left[ \sum_{i=1}^{n} X_i \right]^2 \right) = E \left( \sum_{i=1}^{n} \sum_{j=1}^{n} X_i X_j \right) = \sum_{i=1}^{n} \sum_{j=1}^{n} E(X_i X_j)$$
provided that these expectations exist.
In the example from the problem, $X_1, ..., X_n$ are iid ${\rm exponential}(\lambda)$ random variables, which tells us that $E(X_{i}) = 1/\lambda$ and ${\rm var}(X_i) = 1/\lambda^2$ for each $i$. By independence, for $i \neq j$, we have
$$E(X_i X_j) = E(X_i) \cdot E(X_j) = \frac{1}{\lambda^2}$$
There are $n^2 - n$ of these terms in the sum. When $i = j$, we have
$$ E(X_i X_j) = E(X_{i}^{2}) = {\rm var}(X_{i}) + E(X_{i})^2 = \frac{2}{\lambda^2} $$
and there are $n$ of these term in the sum. Therefore, using the formula above,
$$ E \left( \sum_{i=1}^{n} X_i \right)^2
= \sum_{i=1}^{n} \sum_{j=1}^{n} E(X_i X_j) = (n^2 - n)\cdot\frac{1}{\lambda^2} + n \cdot \frac{2}{\lambda^2} = \frac{n^2 + n}{\lambda^2} $$
is your answer.
Answer: This problem is just a special case of the much more general problem of 'moments of moments' which are usually defined in terms of power sum notation. In particular, in power sum notation:
$$s_1 = \sum_{i=1}^{n} X_i$$
Then, irrespective of the distribution, the original poster seeks $E[s_1^2]$ (provided the moments exist). Since the expectations operator is just the 1st Raw Moment, the solution is given in the mathStatica software by:

[ The '___ToRaw' means that we want the solution presented in terms of raw moments of the population (rather than say central moments or cumulants). ]
Finally, if $X$ ~ Exponential($\lambda$) with pdf $f(x)$:
f = Exp[-x/λ]/λ;      domain[f] = {x, 0, ∞} && {λ > 0};

then we can replace the moments $\mu_i$ in the general solution sol with the actual values for an Exponential random variable, like so:

All done.

P.S. The reason the other solutions posted here yield an answer with $\lambda^2$  in the denominator rather than the numerator is, of course, because they are using a different parameterisation of the Exponential distribution. Since the OP didn't state which version he was using, I decided to use the standard distribution theory textbook definition Johnson Kotz et al … just to balance things out :)


Why is my MATLAB code printing every value within the for loop?

Question: I have code that breaks up a sound file into 1 sec chunks, calculates the RMS of the chunk, then plots all chunks. It works fine until I edited it to make it read through a folder rather than one user loaded file at at time. Now it prints every value of fs (all 32k) which obviously massively slows down the script. Here is the new script:
DirIn = 'D:\Trial'
eval(['filelist=dir(''' DirIn '/*.wav'')'])

for i = 1:length(filelist)
[y,fs] = audioread(strcat(DirIn,'/',filelist(i).name))
npts = length(y);
chunkDur = 1; % length of chunk to analyze in seconds

systemCal = 0; % this should be whatever dB corresponds to an amplitude of 1 in wav file

chunkPts = fs * chunkDur;
rms = [];

for i = 1:chunkPts:npts-chunkPts
    chunkRMS = 20 * log10(std(y(i: i + chunkPts))) + systemCal; % rms of chunk in dB
    rms = [rms; chunkRMS];
end

t = [0: length(rms) - 1] * chunkDur; % time scale
plot(t, rms)
xlabel('Time (s)');
ylabel('RMS dB');
end

For reference, here's the original that works:
npts = length(data);
chunkDur = 1; % length of chunk to analyze in seconds

systemCal = 0; % this should be whatever dB corresponds to an amplitude of 1 in wav file

chunkPts = fs * chunkDur;
rms = [];

for i = 1:chunkPts:npts-chunkPts
    chunkRMS = 20 * log10(std(data(i: i + chunkPts))) + systemCal; % rms of chunk in dB
    rms = [rms; chunkRMS];
end

t = [0: length(rms) - 1] * chunkDur; % time scale
plot(t, rms)
xlabel('Time (s)');
ylabel('RMS dB');

Answer: You missed a semicolon ; at the end of line [y,fs] = audioread(strcat(DirIn,'/',filelist(i).name)).
It signifies the end of a row and suppress an output of the code line. There is a nice blog-entry on this here.


Define map type in ocaml using the core library

Question: Core library for the OCaml language comes with very useful Map and Table modules.
I know how to define my own type if I want to use a map from some built-in type:
type mytype = int String.Map.t (* A mapping from strings to integers *)

I also know how to define a custom map with polymorphic compare:
type mytype = (string, string) Map.Poly.t (* A map from strings to strings *)

What I don't know is how to define custom map using non-polymorphic compare from my own type to my own type.
E.g. suppose I have
type row_t = Row of int
type column_t = Column of int
(* I want a map from rows to columns *)
type mymap_t = (row_t, column_t, ???) Map.t

I understand that the third argument should be the comparator, yet I don't know what to put inside: both Int.comparator and Int.comparator_witness fail to give the desired result.
Comment: Does [this blog post](https://ocaml.janestreet.com/?q=node/112) help.
Answer: You can refer to the blog post Ashish mentioned.
However I usually prefer more "automatic" way to generate Maps and Sets for custom structures when using Core (thanks to Core syntax extensions).
Here is a small example:
module T = struct
  type t = Row of int
  with sexp, compare
end
include T
include Comparable.Make(T)

So this will generate all comparison functions (and other useful functions) and basic data structures that you usually need:
type t = T.t = Row of int
...
val (>) : T.t -> T.t -> bool = <fun>    (* compare functions *)
val (<) : T.t -> T.t -> bool = <fun>
val equal : T.t -> T.t -> bool = <fun>
val compare : T.t -> T.t -> int = <fun>
val min : T.t -> T.t -> T.t = <fun>
val max : T.t -> T.t -> T.t = <fun>
...
module Map :  (* non-polymorphic Map module *)
...
end
module Set :  (* non-polymorphic Set module *)
...
end

and a lot more. So basically you can use a non-polymorphic map afterwards:
type column_t = Column of int
let map = Map.singleton (Row 1) (Column 2)

Comment: Wow, thanks! It's really surprising to see that `Comparable.Make(T)` actually creates `Set`, `Map` and a whole family of others, rather than just comparators.


Private DHCP through a switch using two eth interfaces?

Question: Right now, I have an Scientific Linux blade connected to the internet on eth3, and connected to a 48 port Cisco switch on eth2. This Cisco switch is connected to the eth2 of 24 blank blades (which are not connected to the internet).
I want to be able to assign the 24 blades private IPs based on their hostname so my main blade can connect to them, while keeping them fenced off from the internet. However, because there are so many, I also want to install kickstarted CentOS on them via PXE from the main blade. To do this I would need them to be assigned an IP first via DHCP, right?
So how would I go about doing all this? Any pointers would be appreciated.
Answer: This is just a basic DHCP/PXE boot environment.

Build your PXE Boot resources as per CentOS documentation.
Setup DHCP and TFTP on SL.
Configure SL DHCP to serve leases with PXE booting options.

The "private" blades will not have access to the internet unless you enable routing etc on the SL blade (1).
There is nothing overly special about what you're doing. You'll need to statically assign a private address to eth2 on the SL blade, then configure the corresponding subnet block in dhcpd.conf
(1) Unless SL does something stupid like automatically enabling routing, which I doubt.
Comment: A quick question to help me understand. When I have two connected interfaces in this way in the SL blade, and I ping an IP address, what governs which interface it will try first?
Comment: That is taken care of by your routing table. To view it, run `ip route show`


I/O exception caught when processing request to {}->http://IP:80: Too many open files

Question: I have this architecture, 3 systems:

Back-end
Middleware
Front-end (Client application).

I have rest web service between back-end and middleware and also another different rest service between Front-end and middleware ( as I displayed in the below image)

As appeared in above image,Client is calling Middleware, and Middleware is calling Back-end rest service.
now everything is working fine when i run few requests, but when I started stress testing from client side ( I used JMeter to do this test and call middleware service), I started recieving this exception

I am using this code to call Back-end service:
<code>public static String makeHttpPostCall(String url2, String param1, String type,
            String username, String password) throws IOException {

        String response1 = "";

        CredentialsProvider credsProvider = new BasicCredentialsProvider();
        credsProvider.setCredentials(
                AuthScope.ANY,
                new UsernamePasswordCredentials(username, password));

        CloseableHttpClient client = HttpClients.custom()
                .setDefaultCredentialsProvider(credsProvider)
                .build();

            HttpPost post = new HttpPost(url2);

            List<NameValuePair> urlParameters = new ArrayList<NameValuePair>();
            urlParameters.add(new BasicNameValuePair("param1", param1));
            urlParameters.add(new BasicNameValuePair("type", type));

            post.setEntity(new UrlEncodedFormEntity(urlParameters));

            HttpResponse response = client.execute(post);

            System.out.println("Response Code : "+ response.getStatusLine().getStatusCode());
            BufferedReader rd = new BufferedReader(new InputStreamReader(
                    response.getEntity().getContent()));

            String line;
            while ((line = rd.readLine()) != null) {
                response1 += line;
            }
            System.out.println("response1: "+ response1);
            return response1;
    }
</code>
please can anyone tell me where is the problem in Middleware or back-end, and why it happened?
Answer: You do not close the client http-connection. Try:
<code>...
 }
            System.out.println("response1: "+ response1);

            client.close();

            return response1;
...
</code>
The exception shows that the error occurs when trying to open a new http connection. Mind that although it's a network connection, for the underlying OS it's just an open file descriptor.
If you only make a few calls, the connection may be discarded by gc and everything seems fine. Making a stress test will open as much "files" as you're allowed to and then throws this exception.
Comment: you mean the problem in middleware, because I did not close the http connection?
Comment: I don't know whether its left, middle or right, it's exactly in that lines you have striked out in your screenshot.
Comment: And anyway it's always good practice to close any unused conenctions after usage and, furthermore, it doesn't cost anything and is usually without any harm.
Comment: Thanks I will change code, do same stress testing and tell you what happened.
Comment: I run this test again, and number of exception is decreased from 1000 / 4000 to 10/4000, can I remove these 10 also?
Comment: I don't know your stress test, but probably there are multiple parallel requests running which are again using too may descriptors at a time. In this case, you can only increase the number of allowed open files, look at `ulimit`.
Comment: can you tell me how to use ulimit and where? is there any relation between this error and my application server (JBOSS) configuration?


Mixed Integer Programming in R - Indicator functions

Question: I hope this message finds you well.
I am trying to solve an optimization problem formulated as a Mixed Integer Program with the lpSolveAPI R-package. However, there are indicator functions in the objective function and in some constraints. To be more specific, consider the following optimization problem:
min{        2.8 * x1 +        3.2 * x2 +        3.5 * x3 +
     17.5 * delta(x1) + 2.3 * delta(x2) + 5.5 * delta(x3)  }

subject to:
  0.4 * x1 + 8.7 * x2 + 4.5 * x3 <=
          387 - 3 * delta(x1) - 1 * delta(x2) - 3 * delta(x3)

  x1 <= 93 * delta(x1)

  x2 <= 94 * delta(x2),

  x3 <= 100 * delta(x3), and

  x1, x2, and x3 are non-negative integers.

In this problem, for all i in {1, 2, 3}, delta(xi) = 1 if xi > 0, whereas delta(xi) = 0 otherwise.
The R-code I have so far is:
install.packages("lpSolveAPI")
library(lpSolveAPI)
a <- c(3, 1, 3)
b <- c(0.4, 8.7, 4.5)
q <- 387
M <- c(93, 94, 100)
A <- c(17.5, 2.3, 5.5)
h <- c(2.8, 3.2, 3.5)

Fn <- function(u1, u2, u3, u4){
lprec <- make.lp(0, 3)
lp.control(lprec, "min")
set.objfn(lprec, u1)
add.constraint(lprec, u2, "<=", u3)
set.bounds(lprec, lower = rep(0, 3), upper = u4)
set.type(lprec, columns = 1:3, type = "integer")
solve(lprec)
return(list(Soln = get.variables(lprec), MinObj = get.objective(lprec)))
}

TheTest <- Fn(u1 = h, u2 = b, u3 = q, u4 = M)

Please, I was wondering if someone could tell me how to put delta functions into this R-code to solve the aforementioned optimization problem.
Rodrigo.
Comment: This the Dirac "delta function"?
Comment: Or maybe its integral.
Comment: It is an indicator function I(.) defined as: I(x) = 1 if x in A, whereas I(x) = 0 otherwise, where A = (0, +infinity).
Comment: The Dirac delta function (a.k.a. the Heaviside function) has support on (-Inf, Inf) but otherwise has the same definition. It's generally pretty easy in R to code such a construct. That doesn't look like R-code. It's missing assignments. Looks more like a pseudo-code specification.
Comment: After looking at the question ( for purposes of reformatting to SO standards) I'm puzzled by the joint requirement that x1, x2, x3 be non-negative integers and your use of an indication function that has a value of 1 at 0.
Comment: Mr. 42, thanks for reading the question. I believe that the main difficulties with the optimization problem are the objective function and the constraint
0.4 * x1 + 8.7 * x2 + 4.5 * x3 <= 387 - 3 * delta(x1) - 1 * delta(x2) - 3 * delta(x3) because the upper bound depends on whether xi is positive or not.
I do not know how to deal with those difficulties with the lpsolveAPI package to solve the optimization problem.
Answer: A constraint like x1 <= 93 * delta(x1) looks very strange to me. I think this is just x1 <= 93. For a MIP solver replace the function delta(x) by a binary variable d. Then add the constraint d <= x <= M*d where M is an upper bound on x. To be explicit, for your model we have:
min 2.8*x1 + 3.2*x2 + 3.5*x3 + 17.5*d1 + 2.3*d2 + 5.5*d3
0.4*x1 + 8.7*x2 + 4.5*x3 <= 387 - 3*d1 - d2 - 3*d3
d1 <= x1 <= 93*d1
d2 <= x2 <= 94*d2
d3 <= x3 <= 100*d3
x1 integer in [0,93]
x2 integer in [0,94]
x3 integer in [0,100]
d1,d2,d3 binary

This is now trivial to solve with any MIP solver. Note that a double inequality like d1 <= x1 <= 93*d1 can be written as two inequalities: d1<=x1 and x1<=93*d1.
Comment: Thanks for the suggestion, Mr. Kalvelagen. However, I realized that your suggestion includes the case in which di = 0 and xi > 0, with i in {1, 2, 3}.
Comment: No: you are mistaken
Comment: For example, the constraint d1 <= x1 takes place when d1 = 0 and x1 = 30 > 0.
Comment: We also have `x1 <= 93 d1` which implies that if `d1=0`, `x1` will be forced to be zero. Please read my answer more carefully.
Comment: Got it. Thanks a lot, Mr. Kalvelagen.


Como aumentar o numero de comentários no wordpress

Question: Gostaria de saber como posso aumentar o número de comentários que aparece no wordpress para moderação.
Obs.: não é o número de comentários do post não. É o da parte de administração, onde você pode aprovar, reprovar ou marcar como span.
Answer: Na página dos comentários, na parte superior à direita, tens um botão "Opções de ecrã" como na imagem abaixo:

Clique neste botão e poderás mudar o número de comentários visualizados
Comment: Na tela de administração do WP aparecem apenas 20 comentários para aprovação. Teria como aumentar para 50 ou 100 comentários para aprovar/reprovar/marcar como spam de uma só vez?
Comment: Mas tens a certeza que existem mais de 20 comentários que aparecem?
Comment: editei a minha resposta. Vê a solução.


error in grouping by year,month in mysql

Question: I have this code, and it is working properly on the online server:
SELECT
DATE(`order`.`date`) AS `dater`,
COUNT(*) AS `orders-amount`,
SUM(`order`.`price`) AS `orders-income`,
(SELECT SUM(`amount`) FROM `paypal` WHERE `paypal`.`txn_id` != 'Bonus' AND YEAR(`dater`) = YEAR(`paypal`.`posted_date`) AND MONTH(`dater`) = MONTH(`paypal`.`posted_date`)) AS `total_charge`
FROM `order`
GROUP BY YEAR(`dater`), MONTH(`dater`)
ORDER BY `dater` DESC

But on localhost it gives an error as below:
#1055 - Expression #1 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'panel.order.date' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by

Id I used this code for grouping then it working properly:
GROUP BY `dater`

This error appear only on localhost as I'm running on linux Mint and installing the apache, php, mysql & pypmyadmin
Comment: MySQL 5.7 by default enforces `only_full_group_by` which makes MySQL behave more like standard SQL, and like almost every other RDBMS implementation. You can either change your `sql_mode` or else you can write your queries to conform to the requires semantics.
Comment: Your localhost has `only_full_group_by` enabled, probably because it is a newer version of MySQL.  You must add `total_charge` to the `GROUP BY`, but doing so may change the outcome of your query.  This is a mistake MySQL developers have made for years because of its lenient behavior in earlier versions.
Comment: Something a little off there -- if it's working in production, then it's because it's returning an arbitrary date for that year and month.  Generally speaking, if you want to group by year and month, then you should be selecting those fields instead of the date.  If you want to group by the date, then your 2nd example is correct.  A little difficult to say without sample data and expected results.
Comment: @sgeddes Thanks for your reply, I make some thing like this but it is not working too, I tried many times but I cannot understand this error, also why it is working without errors on the server, just wondering
Answer: It means that different sql modes are used on local and remote servers.
Either you should change the mode or update your query like:
SELECT
YEAR(ANY_VALUE(`order`.`date`)) date_year,
MONTH(ANY_VALUE(`order`.`date`)) date_month,
COUNT(*) AS `orders-amount`,
SUM(`order`.`price`) AS `orders-income`,
(SELECT SUM(`amount`) FROM `paypal` WHERE `paypal`.`txn_id` != 'Bonus' AND YEAR(ANY_VALUE(`order`.`date`)) = YEAR(`paypal`.`posted_date`) AND MONTH(ANY_VALUE(`order`.`date`)) = MONTH(`paypal`.`posted_date`)) AS `total_charge`
FROM `order`
GROUP BY date_year, date_month

Answer: You have it in your error message:

this is incompatible with sql_mode=only_full_group_by

If you did not set it on purpose, I guess you got it by default and you have a different version on your local server (see here, it was made default at some point).
So all you need is to disable this mode, either by running SET sql_mode='';, or by following instructions here
Comment: Thank you very much, I follow the instructions in the link you send and changing the mode and it is working properly right now :)


Problema com autopreenchimento do dropdownlist

Question: Estou tendo um pequeno problema com o dropdownList do asp mvc 5, preciso preencher automaticamente o valor do dropdownlist assim que o usuário entrar na tela de busca, já consegui pegar o valor no banco de dados porém na parte de preencher automaticamente que está dando problema.
Aqui vai direcionar o usuário para tela de Filtro, referente à div que ele marcou:
Questões

Aqui vai recuperar o valor da section para poder comprar com o banco
public ActionResult FiltroQuestao(string section)
    {

        TempData["Materia"] = section;
        return View();
    }

Agora na view estou usando o jquery para preencher o dropdownlist
  $(document).ready(function () {
    $.ajax({
        type: "GET",
        url: "/Quiz/GetState",
        datatype: "Json",
        success: function (data) {
            $.each(data, function (index, value) {
                $('#ddlState').append('<option value="' + value.idMateria + '">' + value.nomeMateria + '</option>');
            });
        }
    });
});

Nessa parte estou usando json para poder popular o dropdownlist via ajax
 public JsonResult GetState()
    {
        var valorMateria = TempData["Materia"];
        if(valorMateria != null)
        {
            var stateData = db.Materia.Where(x => x.nomeMateria == valorMateria.ToString()).ToList();
            return Json(stateData, JsonRequestBehavior.AllowGet);
        }
        var stateData2 = db.Materia.ToList();
        return Json(stateData2, JsonRequestBehavior.AllowGet);
    }

Esse é o dropdownlist
  @Html.DropDownList("ddlState", new SelectList(string.Empty, "Value", "Text"), "Selecionar Materia", new { @class = "form-control" })

Por padrão ele está vindo como Selecionar Materia, mas quero que venha com o valor que está do banco, que no exemplo é Fisica
Answer: Acontece que no retorno do seu Get, você simplesmente adiciona o resultado da Consulta e o <option>Selecionar Matéria</option> já está lá.
$(document).ready(function () {
    $.ajax({
        type: "GET",
        url: "/Quiz/GetState",
        datatype: "Json",
        success: function (data) {

       //Removendo os options existentes
       $('#ddlState').find('option').remove();

        $.each(data, function (index, value) {
            $('#ddlState').append('<option value="' + value.idMateria + '">' + value.nomeMateria + '</option>');
        });
    }
});

});
Comment: Deu certo mas o único problema é se o usuario entrar na URL direto sem passar parâmetro,la no json eu fiz um IF caso ocorresse essa situação,com essa alteração ele tira também o Selecionar Matéria em ambos os casos(não sei se fui muito claro)


Exibir dados de array

Question: Preciso exibir os dados desse array e não estou sabendo fazer a chamada.
Gostaria de pegar dados específicos como [Postage] => 140.55
[0] => SimpleXMLElement Object
                    (

                        [@attributes] => Array
                            (
                                [ID] => 12
                            )

                        [Pounds] => 2
                        [Ounces] => 0
                        [Machinable] => True
                        [MailType] => Package
                        [Container] => RECTANGULAR
                        [Size] => REGULAR
                        [Width] => 2
                        [Length] => 2
                        [Height] => 2
                        [Girth] => 0
                        [Country] => BRAZIL
                        [Postage] => 140.55
                        [ExtraServices] => SimpleXMLElement Object
                            (
                                [ExtraService] => SimpleXMLElement Object
                                    (
                                        [ServiceID] => 106
                                        [ServiceName] => Insurance
                                        [Available] => True
                                        [Price] => 1.00
                                        [DeclaredValueRequired] => True
                                    )

                            )

                        [ValueOfContents] => 200.00
                        [SvcCommitments] => 1 - 3 business days to many major markets
                        [SvcDescription] => USPS GXG™ Envelopes
                        [MaxDimensions] => USPS-Produced regular size cardboard envelope (12-1/2" x 9-1/2"), the legal-sized cardboard envelope (15" x 9-1/2") and the GXG Tyvek envelope (15-1/2" x 12-1/2")
                        [MaxWeight] => 70
                    )

Comment: ```$var->Postage``` não resolve?
Comment: Acabei de responder uma pergunta parecida com a sua https://pt.stackoverflow.com/questions/334455/como-fa%C3%A7o-para-ler-um-xml-com-marca%C3%A7%C3%A3o-html/334544#334544
Comment: $var->Postage não resolve, já tentei, na verdade a estrutura é maior que isso. É um retorno de uma consulta em uma api dos correios dos USA. mas fica muito grande pra mandar aqui.
Comment: Tenta assim: $v[0]->Postage
Answer: Basta você acessar a posição zero do array e o atributo.
$var[0]->Postage;

Exibir dados de array


How to make a MENU_LOCAL_TASK on a user's profile only appear on their profile?

Question: I use logic like this to place a tab on each user's profile page so users can view analytics from the usage of a WebApp:
  // maps a url to a sub-page of user's profile, url to user's Analytics-Management form
  $items['user/%user/ClientCompanyName'] = array(
    'title'            => 'ClientCompanyName',
    'description'      => 'Manage your ClientCompanyName services.',
    'page callback'    => 'drupal_get_form',
    'page arguments'   => array('_ClientCompanyName_mgmt_form'),
    'access callback'  => 'user_access',
    'access arguments' => array( 'access ClientCompanyName services' ),
    'type' => MENU_LOCAL_TASK,
  );

This works great for each user, but I do not want one user to be able to go to another user's profile and hit their link to get to that other user's private analytics data.
Currently, if a user tries to visit another user's analytics management page, they see an access denied page.
But I would like them never to even be given the link to that page. I tried writing my own 'access callback', but I can't figure out how to pass in the '%user' portion of the intended url so I can test that against the logged in user...
I like how one can use '%' symbols in the url, and then 'page arguments' can be used to reference those arguments in the url. Is it possible to do something similar with the 'access arguments'?
Essentially, I'm trying to achieve the same thing as the behavior of the 'edit' tab on a user's profile: only if the user is on their own profile page will that 'edit' tab appear on the profile. How do I get the same effect for my WebApp analytics page?
(I guess I could make my analytics page a MENU_LOCAL_TASK of the profile edit form... but I'd still like to know how to create a conditional MENU_LOCAL_TASK whose conditional is more then simply an user_access() permissions test.)
Answer: Instead of user_access, define your own access callback function and then pass the user object to that.
So 'access callback' => 'yourmodule_analytics_access' and 'access arguments' => array(1).
In that function, compare the user id and check the permission.
function yourmodule_analytics_access($account) {
  global $user;
  return $user->uid == $account->uid && user_access('access ClientCompanyName services');
}

Comment: @bsenftner using an integer as part of an arguments array means that numbered argument will be passed. If you want to pass a literal `1` you need to put `"1"` into the arguments array. The reason you get a full user object is because argument 1 is `%user` which calls `user_load($arg)` and passes that into your function. In general, using a `%foo` parameter in your URL will cause the result of `foo_load($arg)` to be passed to your function.
Comment: Using "'access arguments' => array(1)" will pass "1" to my access callback, not the 1'th argument from the url. I tried what you suggest. The issue seems to be that I can't get information from the url as a parameter to my custom access callback.
Comment: It works. See http://api.worldempire.ch/api/privatemsg/privatemsg.module/function/privatemsg_menu/7-1 for some examples. Maybe you didn't rebuild the menu after changing it?
Comment: Wow. You are right. At first I was trying "array('%user')" and not 'array(1)'... and when I tried 'array(1)' I was not expecting the entire user object, I was expecting a string equal to the uid of the profile being visited. I think I'm going to switch to your suggestion.
Comment: @Matthew Scharley: thanks for the additional EXTREMELY USEFUL information. As far as I know, that's not documented anywhere, and very, very valuable.
Comment: Most of that is documented here: http://api.drupal.org/api/drupal/modules--system--system.api.php/function/hook_menu/7. The only missing part is afaik the "1" trick.
Comment: @Berdir mostly because it's a hack. Any string will be passed to the function, any integer will be used to pull parts of the URL string and pass those to the function. How to pass an integer to a function? Pass it in string form. Works for 90% of cases in PHP, unless someone actually checks types. Whether it's a good thing to do is another argument altogether, but it works.
Answer: I ended up using a custom access callback like this:
// this makes the analytics user profile tab's MENU_LOCAL_TAB conditional:
function _cex_mgmt_access($accessAllowed) {
  global $user;
  if (arg(1) != $user->uid)
    return false;
  return user_access($accessAllowed);
}

Where the 'access callback' parameter in the MENU_LOCAL_TASK definition is set to '_cex_mgmt_access' rather than 'user_access'.
I'm a bit uncertain about this method. It depends upon the menu module's logic that handles the MENU_LOCAL_TASK definition to be processed each time a user travels to any profile page. Doesn't that information get cached (if caching is turned on)?
Comment: Actually, see my "wow" comment above. I switched to that answer after posting my first solution.
Comment: To answer your question, no it doesn't and can't get cached. But it is a fast check (the user object is already loaded and re-used), so don't worry about that.


how do i increase the value of q by one without resetting each time opening the popup.js in chrome extension

Question: var i = 300;
chrome.storage.sync.set({q:i},()=>{console.log(i);});
chrome.storage.sync.get(['q'],(q)=>{document.querySelector("#here").innerHTML = q.q;});
document.querySelector("body").addEventListener("click",()=>{
  i++;
  chrome.storage.sync.set({q:i},()=>{var q = i;});
  chrome.storage.sync.get(['q'],(q)=>{document.querySelector("#here").innerHTML = q.q;})
},false);

q always updates to 300 each time extension is opened how do i update it and not reset,
is there a way to do it without background page and just use popup.js?
Comment: Your question could be easier to answer if you clarified it a bit. Try to add some more details and context.
Comment: initially i is supposed to be 300 and after opening the popup and clicking the number goes up by one and after closing the popup and opening it again it should be what was the last number it is
Comment: Welcome to SO, What you are doing is declaring the var i =300, that is resetting the value each time. One workaround is to use some global variable or local storage. Then you can call and update it each time rather than creating 'i' each time.
Answer:
Remove the second line chrome.storage.sync.set({q:i},()=>{console.log(i);});
it always overwrites the storage with i which is 300.
Read the storage on start and put the result in i
Listen to changes in the storage and update i and DOM automatically - this will handle both your own changes and remote changes due to browser sync or changes in popups open in other browser windows.

let i;

chrome.storage.sync.get({q: 300}, res => {
  useValue(res.q);
});

chrome.storage.onChanged.addListener(changes => {
  if (changes.q) {
    useValue(changes.q.newValue);
  }
});

document.querySelector('body').addEventListener('click', () => {
  chrome.storage.sync.set({q: i + 1});
});

function useValue(val) {
  i = val;
  document.querySelector('#here').textContent = val;
}

Comment: what if i want to type it like instead of q:300 q:i and i = 300;
Comment: See tutorials for DOM - you can use an `input` element and listen to `input` event on that element.
Comment: i saw an extension doing it through input but i was wondering if i could just type the value within the js file as a variable and not the value 300
Comment: I guess I misunderstood your question. Yes, you can do that. The potential advantage of doing it my way is that the variable won't have the wrong value until the storage is accessed.
Comment: okay your answer actually helped what i'm trying to do so thanks :D


Moving variable product dropdowns in WooCommerce

Question: I've been playing around with hooks for a few hours and couldn't find the solution so far.
I am trying to move the variable product dropdown next to the quantity / add to cart button, but I don't know how to achieve this.
Here is the current render :

So the display would go like :

Product title
Price area
Attribute dropdown / Quantity / Add to cart

Edit :
I have removed the price range.
In the following code I change the live price behavior :
add_filter( 'woocommerce_variable_price_html', 'bbloomer_variation_price_format', 10, 2 );

function bbloomer_variation_price_format( $price, $product ) {

        // Main Price
        $prices = array( $product->get_variation_price( 'min', true ), $product->get_variation_price( 'max', true ) );
        $price = $prices[0] !== $prices[1] ? sprintf( __( '%1$s', 'woocommerce' ), wc_price( $prices[0] ) ) : wc_price( $prices[0] );

        // Sale Price
        $prices = array( $product->get_variation_regular_price( 'min', true ), $product->get_variation_regular_price( 'max', true ) );
        sort( $prices );
        $saleprice = $prices[0] !== $prices[1] ? sprintf( __( '%1$s', 'woocommerce' ), wc_price( $prices[0] ) ) : wc_price( $prices[0] );

        if ( $price !== $saleprice ) {
        $price = '' . $saleprice . ' ' . $price . '';
        }
        return $price;
}

How can I move the variable product dropdown at the left of Quantity / Add to cart button?
Answer: Edit (related to your last comment):
For variable products only, the code below will:

Remove the price range (If you are doing this already, you should remove your related code).
Move the live variation selected price above the attribute select fields…
Add CSS to get the attribute select fields at the left of the block that contains the quantity field and the add-to-cart button.http://www.cbleu.net/sites/tie2/product/premium-quality/
Move the short description location after the add-to-cart button

In this function you can just remove Css and add them in your active child theme (or active theme) styles.css file.
Here is that code:
add_action( 'woocommerce_single_product_summary', 'custom_single_product_styles', 2 );
function custom_single_product_styles() {
    global $product;

    // Only for variable products
    if ( ! $product->is_type('variable') ) return;

    // Change the short description location after the add-to-cart button
    remove_action( 'woocommerce_single_product_summary', 'woocommerce_template_single_add_to_cart', 30 );
    add_action( 'woocommerce_single_product_summary', 'woocommerce_template_single_add_to_cart', 15 );

    // Removing the price range
    remove_action( 'woocommerce_single_product_summary', 'woocommerce_template_single_price', 10 );

    // Change the price location above variation attribute select fields
    remove_action( 'woocommerce_single_variation', 'woocommerce_single_variation', 10 );
    add_action( 'woocommerce_before_variations_form', 'woocommerce_single_variation', 10 );

    // Styles to display the variation attribute select fields at the left of Quantity/Add to cart
    // (Can be removed and inserted in styles.css file)
    ?>

    <?php
}

Code goes in function.php file of your active child theme (or theme) or also in any plugin file.
Tested and works… You will get something like:

The related template that is involved specifically in this is single-product/add-to-cart/variable.php
You can try to change there the existing structure to match with your requirements specifically to your theme and styling needs...
Comment: Thank you for your detailed answer. This is the raw result I get : https://imgur.com/a/cxudK

It seems that the price and add to cart buttons are both contained in the "single_variation_wrap" div, so the price ends up between the cart button and the dropdown.

The snippet removing then re-adding the single variation has no impact on the actual render, though.
Comment: I can't manage to get the live variation price on top of everything else, even with your code. I would then be able to style the items to look right. The price and add to cart are in the same . I've showed you the code of my functions.php, I have no other CSS or function overrides and the theme is pretty default.
Comment: Thank you for your time, I'll look into it. Merry christmas :)
Comment: I've managed to make it work. I had another hook that created the problem I had, thank you. Here is the result : https://imgur.com/a/nuiJc

I have one last question, I used the following code to move the summary after the product price / cart zone :

remove_action( 'woocommerce_single_product_summary', 'woocommerce_template_single_add_to_cart', 30 );
add_action( 'woocommerce_single_product_summary', 'woocommerce_template_single_add_to_cart', 15 );

But now, the discount % has disappeared (sale_flash). Do you know how I could display it next to the variation price ? Thank you.


Showing the attractor of an IFS is either connected or totally disconnected

Question: I came across this execise in a problem set about Iterated Function System (IFS) and fractals:
"Show that the attractor of an IFS of the form $\{\mathbb{R};~ax+b, cx+d\}$ where $a,b,c,d \in \mathbb{R}$, is either connected or totally disconnected".
All I know about an IFS with contractive mappings $f$ and $g$ is that its attractor $A$ obeys
$f(A)∪g(A)=A$.
I spent quite a long time trying proving it, so I'll be greatful for any help.
Answer: Assuming that $|a|<1$ and $|c|<1$ (i.e., the system is contractive), each of the maps has a unique fixed point: call them $x_1,x_2$. The trivial case is when $x_1=x_2$; then $\{x_1\}$ is the invariant set. From now on, assume $x_1\ne x_2$.
Case 1.: $|a|+|c|<1$. This is when the invariant set (call it $K$) is of Cantor type, i.e., totally disconnected. Indeed, being compact, $K$ is contained in some interval $I$. Therefore, $f(I)\cup g(I)$ also contains $K$, etc. But the length of $f(I)\cup g(I)$ is at most $|a|+|c|$ times the length of $I$. Continuing this process, we find that the length of the iterated images of $I$ under $\{f,g\}$ tends to zero. Since each of them contains $K$, it follows that $K$ does not contain any line segment; thus it's totally disconnected.
Case 2.: $|a|+|c|\ge 1$. This is when the invariant set is a line segment $[\alpha,\beta]$. The most direct proof is to find $\alpha,\beta$ explicitly and then verify the invariance of this line segment. It helps to realize that if a map ($f$ or $g$) has positive derivative, its fixed point is an endpoint of the invariant set.  For negative derivatives you have to do some linear algebra, which I'll illustrate by an example:
$$f(x)=-x/2,\quad g(x)=(3-x)/2$$
Each map shrinks the line and flips it. Therefore, an invariant segment $[\alpha,\beta] $ must satisfy
$$-\beta/2 = \alpha,\quad (3-\alpha)/2 = \beta$$
The solution is $\alpha=-1$, $\beta=2$. It is easy to check that $[-1,2]$ is indeed invariant.


How to write a custom Deterministic or Stochastic in pymc3 with theano.op?

Question: I'm doing some pymc3 and I would like to create custom Stochastics, however there doesn't seem to be a lot documentation about how it's done. I know how to use the as_op way, however apparently that makes it impossible to use the NUTS sampler, in which case I don't see the advantage of pymc3 over pymc.
The tutorial mentions that it can be done by inheriting from theano.Op. But can anyone show me how that would work (I'm still getting started on theano)? I have two Stochastics that I want to define.
The first one should be easier, it's an N dimension vector F that has only constant parent variables:
with myModel:
    F = DensityDist('F', lambda value: pymc.skew_normal_like(value, F_mu_array, F_std_array, F_a_array), shape = N)

I want a skew normal distribution, which doesn't seem to be implemented in pymc3 yet, I just imported the pymc2 version. Unfortunately, F_mu_array, F_std_array, F_a_array and F are all N-dimensional vectors, and the lambda thing doesn't seem to work with an N-dimension list value.
Firstly, is there a way to make the lambda input an N-dimensional array? If not, I guess I would need to define the Stochastic F directly, and this is where I presume I need theano.Op to make it work.

The second example is a more complicated function of other Stochastics. Here how I want to define it (incorrectly at the moment):
with myModel:
    ln2_var = Uniform('ln2_var', lower=-10, upper=4)
    sigma = Deterministic('sigma', exp(0.5*ln2_var))
    A = Uniform('A', lower=-10, upper=10, shape=5)
    C = Uniform('C', lower=0.0, upper=2.0, shape=5)
    sw = Normal('sw', mu=5.5, sd=0.5, shape=5)

    # F from before
    F = DensityDist('F', lambda value: skew_normal_like(value, F_mu_array, F_std_array, F_a_array), shape = N)
    M = Normal('M', mu=M_obs_array, sd=M_stdev, shape=N)

    #   Radius forward-model (THIS IS THE STOCHASTIC IN QUESTION)
    R = Normal('R', mu = R_forward(F, M, A, C, sw, N), sd=sigma, shape=N)

Where the function R_forward(F,M,A,C,sw,N) is naively defined as:
from theano.tensor import lt, le, eq, gt, ge

def R_forward(Flux, Mass, A, C, sw, num):
    for i in range(num):
        if lt(Mass[i], 0.2):
            if lt(Flux[i], sw[0]):
                muR = C[0]
            else:
                muR = A[0]*log10(Flux[i]) + C[0] - A[0]*log10(sw[0])
        elif (le(0.2, Mass[i]) or le(Mass[i], 0.5)):
            if lt(Flux[i], sw[1]):
                muR = C[1]
            else:
                muR = A[1]*log10(Flux[i]) + C[1] - A[1]*log10(sw[1])
        elif (le(0.5, Mass[i]) or le(Mass[i], 1.5)):
            if lt(Flux[i], sw[2]):
                muR = C[2]
            else:
                muR = A[2]*log10(Flux[i]) + C[2] - A[2]*log10(sw[2])
        elif (le(1.5, Mass[i]) or le(Mass[i], 3.5)):
            if lt(Flux[i], sw[3]):
                muR = C[3]
            else:
                muR = A[3]*log10(Flux[i]) + C[3] - A[3]*log10(sw[3])
        else:
            if lt(Flux[i], sw[4]):
                muR = C[4]
            else:
                muR = A[4]*log10(Flux[i]) + C[4] - A[4]*log10(sw[4])
    return muR

This presumably won't work of course. I can see how I would use as_op, but I want to preserve the NUTS sampling.
Answer: I realize this is a bit late now, but I thought I'd answer the question (rather vaguely) anyways.
If you want to define a stochastic function (e.g. a probability distribution), then you need to do a couple of things:
First, define a subclass of either Discrete (pymc3.distributions.Discrete) or Continuous, which has at least the method logp, which returns the log-likelihood of your stochastic. If you define this as a simple symbolic equation (x+1), I believe you do not need to take care of any gradients (but don't quote me on this; see the documentation about this). I'll get on to more complicated cases below. In the unfortunate case that you need to do anything more complex, as in your second example (pymc3 now has a skew normal distribution implemented, by the way), you need to define the operations required for it (used in the logp method) as a Theano Op. If you need no derivatives, then the as_op does the job, but as you said, gradients are kind of the idea of pymc3.
This is where it gets complicated. If you want to use NUTS (or need gradients for whatever reason), then you need to implement your operation used in logp as a subclass of theano.gof.Op. Your new op class (let's call it just Op from now on) will need two or three methods at least. The first one defines inputs/outputs to the Op (check the Op documentation). The perform() method (or variants you might choose) is the one that does the operation you want (your R_forward function, for example). This can be done in pure python, if you so wish. The third method, grad(), is where you define the gradient of your perform()'s output wrt the inputs. The actual output to grad() is a bit different, but not a big deal.
And it is in grad() that using Theano pays off. If you define your entire perform() in Theano, then it might be that you can easily use automatic differentiation (theano.tensor.grad or theano.tensor.jacobian) to do the work for you (see the example below). However, this is not necessarily going to be easy.
In your second example, it would mean implementing your R_forward function in Theano, which could be complicated.
Here I include a somewhat minimal example of an Op that I created while learning to do these things.
def my_th_fun():
    """ Some needed auxiliary functions.
    """
    X = th.tensor.vector('X')
    SCALE = th.tensor.scalar('SCALE')

    X.tag.test_value = np.array([1,2,3,4])
    SCALE.tag.test_value = 5.

    Scale, upd_sm_X = th.scan(lambda x, scale: scale*(scale+ x),
                               sequences=[X],
                               outputs_info=[SCALE])
    fun_Scale = th.function(inputs=[X, SCALE], outputs=Scale)
    D_out_d_scale = th.tensor.grad(Scale[-1], SCALE)
    fun_d_out_d_scale = th.function([X, SCALE], D_out_d_scale)
    return Scale, fun_Scale, D_out_d_scale, fun_d_out_d_scale

class myOp(th.gof.Op):
    """ Op subclass with a somewhat silly computation. It uses
    th.scan and th.tensor.grad is used to calculate the gradient
    automagically in the grad() method.
    """
    __props__ = ()
    itypes = [th.tensor.dscalar]
    otypes = [th.tensor.dvector]
    def __init__(self, *args, **kwargs):
        super(myOp, self).__init__(*args, **kwargs)
        self.base_dist = np.arange(1,5)
        (self.UPD_scale, self.fun_scale,
         self.D_out_d_scale, self.fun_d_out_d_scale)= my_th_fun()

    def perform(self, node, inputs, outputs):
        scale = inputs[0]
        updated_scale = self.fun_scale(self.base_dist, scale)
        out1 = self.base_dist[0:2].sum()
        out2 = self.base_dist[2:4].sum()
        maxout = np.max([out1, out2])
        exp_out1 = np.exp(updated_scale[-1]*(out1-maxout))
        exp_out2 = np.exp(updated_scale[-1]*(out2-maxout))
        norm_const = exp_out1 + exp_out2
        outputs[0][0] = np.array([exp_out1/norm_const, exp_out2/norm_const])

    def grad(self, inputs, output_gradients): #working!
        """ Calculates the gradient of the output of the Op wrt
        to the input. As a simple example, the input is scalar.

        Notice how the output is actually the gradient multiplied
        by the output_gradients, which is an input provided by
        theano when calculating gradients.
        """
        scale = inputs[0]
        X = th.tensor.as_tensor(self.base_dist)
        # Do I need to recalculate all this or can I assume that perform() has
        # always been called before grad() and thus can take it from there?
        # In any case, this is a small enough example to recalculate quickly:
        all_scale, _ = th.scan(lambda x, scale_1: scale_1*(scale_1+ x),
                               sequences=[X],
                               outputs_info=[scale])
        updated_scale = all_scale[-1]

        out1 = self.base_dist[0:1].sum()
        out2 = self.base_dist[2:3].sum()
        maxout = np.max([out1, out2])

        exp_out1 = th.tensor.exp(updated_scale*(out1 - maxout))
        exp_out2 = th.tensor.exp(updated_scale*(out2 - maxout))
        norm_const = exp_out1 + exp_out2

        d_S_d_scale = th.theano.grad(all_scale[-1], scale)
        Jac1 = (-(out1-out2)*d_S_d_scale*
                th.tensor.exp(updated_scale*(out1+out2 - 2*maxout))/(norm_const**2))
        Jac2 = -Jac1
        return Jac1*output_gradients[0][0]+ Jac2*output_gradients[0][1],

This Op can then be used inside the logp() method of a stochastic in pymc3:
import pymc3 as pm

class myDist(pm.distributions.Discrete):
    def __init__(self, invT, *args, **kwargs):
        super(myDist, self).__init__(*args, **kwargs)
        self.invT = invT
        self.myOp = myOp()
    def logp(self, value):
        return self.myOp(self.invT)[value]

I hope it helps any (hopeless) pymc3/theano newbie out there.
Comment: thx for your example. I personnally am a complete beginner with pymc3 and can't use it for some tasks. So, I code for pymc2… such a shame… Please can you have a look on my case http://stackoverflow.com/questions/42205123/how-to-fit-a-method-belonging-to-an-instance-with-pymc3, to see whether you can help ? I saw your example a while ago but I found it complex and I didn't apply it to my case yet because I hoped someone would propose anything simpler. It would seem to me awkward whether pymc3 wouldn't have a practical answer... It seems to me more likely I'm missing something obvious.
Comment: Even the more recent tries to avoid using a theano.op, following comments, are failures. The mechanics remain mysterious...


Como alterar os media-query usando JS?

Question: Estou usando CSS com os media queries, como por exemplo:
html {
  --color: #OOOOOO;
}

@media (prefers-color-scheme: dark) {
 html {
   --color: #FFFFFF;
 }
}

Considerando o código acima, quem tem o prefers-color-scheme de dark terá #FFFFFF e quem não tem verá #000000. Nenhum problema até aí.
Porém, alguém pode preferir visualizar o conteúdo diferente do atual. Por exemplo, considerando que seu prefers-color-scheme é de light. Se você quiser visualizar o conteúdo como se fosse dark terá que ir até as configurações do navegador e alterar.
Existe alguma maneira, no JS, de sobrescrever a definição do navegador? Forçar que você se torne um prefers-color-scheme: dark?!

Existe alguma forma de sobrescrever estes parâmetros usando Javascript? Alguma coisa como:
window.document .MediaQueries .Set("prefers-color-scheme", "dark");

Dessa forma, independente do "prefers-color-scheme" atual do navegador, ele se tornaria "dark" e nada no CSS teria que ser alterado.

Isso é possível de alguma forma?

Utilizei o prefers-color-scheme para melhor exemplificar o problema, mas considere ver a publicação anterior.
Comment: Teria como fazer usando [`@custom-media`](https://drafts.csswg.org/mediaqueries-5/#custom-mq)(Capitulo 4 e 4.1) mas a recomendação até o momento não foi implementada em nenhum browser.
Answer: Encontrei uma solução, que seria usando cssRules, que o @Augusto Vasques mencionou num comentário.

Isso não é exatamente como queria, isso não vai funcionar com media-queries mais complexas (exemplo: min-width). Para que funcionasse iria exigir que criasse algum dicionário para depois recuperar os valores antigos.
Considerando, exatamente:
html {
  --color: #OOOOOO;
}

@media (prefers-color-scheme: dark) {
 html {
   --color: #FFFFFF;
 }
}

Se estivéssemos executando o navegador com light, a cor será #OOOOOO. A minha pergunta seria como mudar o navegador para dark, infelizmente isso não tem como e irei marcar qualquer outra resposta como válida que faça exatamente isso.
O que temos como fazer é trocar o @media (prefers-color-scheme: dark) para @media (prefers-color-scheme: light), dessa forma a segunda variável substiuirá a anterior. Então como você está como light irá passar a usar #FFFFFF, porque o dark do CSS virou light.

Para fazer essa magia existe o cssRules, como mencionei antes. No total, meu código ficou algo como:

JS:

// Quando tiver mais tempo dou uma organizada no código, porque nem eu estou entendendo, simplesmente copiei o que fiz em Golang. Deve ter como fazer melhor em JS.

window.document.querySelector("fullscreen").addEventListener("click", function(e) {
  if (!(e.target instanceof HTMLButtonElement)) {
    return;
  }

  if (IsBrowser(e.target.dataset.mode)) {
    SetTheme("light", "dark"); // Mudamos para o padrão, já que quer usar aquilo que o seu navegador já é.
  } else {
    SetTheme("dark", "light"); // Mudamos para o oposto ao seu navegador (porque se estiver como "dark" o CSS virá "light"; se estiver usando como "light" passará a ser "light" e então o modo noturno será ativado).
  }
});

window.matchMedia("(prefers-color-scheme: light)").addEventListener("change", function (_) {
  SetTheme("light", "dark"); // Se você mudar no browser voltamos ao modo normal do CSS.
})

function IsBrowser(t) {
  return window.matchMedia("(prefers-color-scheme: " + t + ")").matches;
}

function SetTheme(o, n) {
  let rules = window.document.styleSheets[0].cssRules;
  for (i = 0; i < rules.length; i++) {
    media = rules[i].media
    if (media == undefined) {
      continue
    }

    current = media.mediaText
    current = current.replace("(prefers-color-scheme: " + o + ")", "(prefers-color-scheme: " + n + ")");

    rules[i].media.mediaText = current
  }
}
html {
  --background: aqua;
}

@media (prefers-color-scheme: dark) {
  html {
    --background: brown;
  }
}

fullscreen {
  display: block;
  height: 100vh;
  width: 100vw;
  background-color: var(--background);
}
<fullscreen>
  <button data-mode=dark>Escuro</button>
  <button data-mode=light>Claro</button>
</fullscreen>

Golang:

func SetTheme(old, new string) {
    rules := js.Global.Get("document").Get("styleSheets").Index(0).Get("cssRules")
    for i := 0; i < rules.Length(); i++ {
        media := rules.Index(i).Get("media")
        if media == js.Undefined {
            continue
        }

        current := media.Get("mediaText").String()
        current = strings.Replace(current, `(prefers-color-scheme: `+old+`)`, `(prefers-color-scheme: `+new+`)`, -1)
        media.Set("mediaText", current)
    }
}

Comment: Por que a resposta foi negativada? Poderia explicar a falha no raciocínio do AR ou qual parte da resposta que não funciona?

Como alterar os media-query usando JS?