what happens to a scala map when it is updated and assigned to a var?

Question: Day 3 of learning Scala.
I guess maps are immutable. I was wondering, when we update an immutable map and assign it to a new var, what happens to the old map? Is the memory just immediately freed up?
Also, when the new map is assigned to a var which by definition is mutable, what does this mean? Because a map by default, even the new map is not mutable.
Does anyone know the answers? Is there a good resource that can explain these things to me? ( what happens under the hood etc )
Comment: Generally, I would recommend [Daniel Spiewak's talk](https://vimeo.com/28760673) on functional data structures.
Answer: "what happens to the old map?"
It depends on whether anyone else is using it. If not, the memory it uses will be freed at some point by a process called "garbage collection". There is no way for the program to tell when this actually happens.
"what does [it mean] when a new map is assigned to a var"
val and var both define a "variable" that refers to an object. The difference is that a val always points to the same object but a var may be updated to point to a different object.
In contrast, mutable and immutable are properties of an object itself. An immutable object will always have the same value whereas the value of a mutable object can be changed.
Comment: It may also be the case that the newly constructed map smartly shares some internal structures with the old map, in which case the old map is, of course, not garbage collected.


Entity Framework 6 error serverversion : (System.Data.SqlClient.SqlConnection)customerOrderContext.Database.Connection).ServerVersion

Question: I am implementing a web api that will fetch data using entity framework 6. I am using Sql Server 2014 and visual studio 2015.While debugging the the code in the CustomerDao class I am seeing an exception in the customerOrderContext object though I can see the records in the customer object. However after the using block executes I cant see any records.
((System.Data.SqlClient.SqlConnection)customerOrderContext.Database.Connection).ServerVersion
CustomerDao
using (var customerOrderContext = new Entities())
                {
                    return (from customer in customerOrderContext.Customers

                            select new CustomerOrder.BusinessObjects.Customers
                            {
                                Id = customer.Id,
                                FirstName = customer.FirstName,
                                LastName = customer.LastName,
                                Address = customer.Address,
                                City = customer.City,
                                Email = customer.Email,
                                Gender = customer.Gender,
                                State = customer.State,
                                Zip = customer.Zip
                            }).ToList();
                }

The connection string in the config file is as follows
<add name="Entities" connectionString="metadata=res://*/EF.CustomerOrderContext.csdl|res://*/EF.CustomerOrderContext.ssdl|res://*/EF.CustomerOrderContext.msl;provider=System.Data.SqlClient;provider connection string="data source=Tom-PC\MSSQLSERVER2014;initial catalog=Ransang;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />

The context class is follows
public partial class Entities : DbContext
{
    public Entities()
        : base("name=Entities")
    {
    }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {

    }

    public virtual DbSet<Customer> Customers { get; set; }
    public virtual DbSet<OrderDetail> OrderDetails { get; set; }
    public virtual DbSet<Order> Orders { get; set; }
    public virtual DbSet<Product> Products { get; set; }
}

CustomProvider.cs
  public IEnumerable<BusinessObjects.Customers> GetAllCustomers()
        {
            IList<BusinessObjects.Customers> customerCollection = new List<BusinessObjects.Customers>();
            dataAccess.CustomerDao.GetAllCustomers();
            return customerCollection;
        }

Comment: Do you receive any exception? *(System.Data.SqlClient.SqlConnection)customerOrderContext.Database.Connection).ServerVersion* doesn't seem to be an exception message. Where did you see that?
Comment: While debugging the the code in the CustomerDao class I am seeing an exception in the customerOrderContext object though I can see the records in the customer object. However after the using block executes I cant see any records. I think there is some issue with establishing the connection and hence cant get the data to the Ui
Comment: What's the exception message?
Comment: Cant see any exception message as such as the application runs without a breaking error. I only  see  the message I mentioned above while debugging
Comment: It's unclear where/how do you see that. Please add a picture from what you see.
Comment: Also after the using block the context is disposed, you should look in the variable which keeps the result of your function. For example I suppose the code is written in a `GetCustomers` method and used this way `var list = Customers();` so what's the value of `list` after executing the code?
Comment: I have updated the post with the image
Comment: I see, what's the result of calling the `GetAllCustomers` method?
Comment: I have updated the post with GetAllCustomers method. It count is zero. No records
Comment: The exception is [documented](https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlconnection.serverversion(v=vs.110).aspx#Anchor_1) *The connection is closed.* There is no problem with this.
Comment: Thank for the feedback, you also have my vote :)
Answer: The exception is documented and it's because the connection is closed. There is no problem with this.
But obviously you get empty result because you didn't use the result, you are just returning new List<BusinessObjects.Customers>() in your method:
public IEnumerable<BusinessObjects.Customers> GetAllCustomers()
{
    IList<BusinessObjects.Customers> customerCollection =
        new List<BusinessObjects.Customers>(); // ← An empty list
    dataAccess.CustomerDao.GetAllCustomers();  // ← Just executed but didn't use anywhere
    return customerCollection;                 // ← The empty list you created at first
}

You need to return dataAccess.CustomerDao.GetAllCustomers();:


Script to Push Files

Question: Script to Push Files
Hey Guys, Thanks for always being helpful, I have another issue that I need a little insight on how to fix.
See the below script I have and the error I get. I don't understand why it does that, am I not using the continue correctly?
#!/bin/bash -x
# @(#) File: filepush.sh
# ---------------------------------------------------------------------------
# Modication History:
# Date       Name                       Description
# 12/10/2014  Emmanuel Iroanya          Script to copy a file to all hosts listed in serverlist  file
# ---------------------------------------------------------------------------

source /opt/mgr/conf/file.conf
source /opt/mgr/conf/dest.conf
HOSTS=/opt/mgr/conf/$1serverlist.conf

echo "Are you sure you want to copy $file to the list of $1 servers"
echo "This may take a while!!"
echo -n "Enter 'y' or 'n':"
read CHOICE
case "$CHOICE" in
        y|yes|Yes) while read line
do
        ssh "$line" "mkdir -p $dest" && scp -r "$file" "$line:$dest"
done < $HOSTS
        continue ;;
     n|no|No) echo "Please try again later"

esac

And the Error:
./filepush: line 31: continue: only meaningful in a `for', `while', or `until' loop

Comment: Your continue statement outside of while done block
Comment: what do you suggest I do then? Please?
Answer: Just get rid of the continue command, it's not needed. Leave the ;;, though -- that's how the end of a case is indicated.
The purpose of continue is to skip the remainder of a loop body, and start the next iteration. It has no meaning outside a loop, so you get this error. This isn't like C/Javascript/PHP -- you don't need a special statement at the end of a case to prevent falling through to the next case.
Comment: so when I take the     continue out but leave the     ;; it reads like 2 lines from the conf and thats it.
Comment: Use `ssh -n`. Otherwise, `ssh` reads all the rest of the standard input, and sends it to the server.
Comment: Have you looked at `pscp` and `prsync`, which allow you to do parallel `scp` and `rsync` commands? `rsync` will automatically create directories as necessary, so you don't need the separate `ssh` command.

Script to Push Files


How do I automatically sync a file in cluster?

Question: I have a website growing very fast, and now I put it in several web servers.
Now the problem is how do I sync files between them; I use SVN to manage my source code, I could only commit the source code one by one now, is there a solution to commit the source code to one server and automatically sync to other servers?
Comment: Why do you have TWO SVN servers? Shouldn't one be sufficient?
Answer: You can have read-only mirrors, but (as I understand it) you have to have only a single read/write master repository.  It involves setting up some hook scripts that are run when commits are made.  See this reference:
http://svnbook.red-bean.com/en/1.7/svn.reposadmin.maint.html#svn.reposadmin.maint.replication
Note that if your master (read/write) node goes down, you can convert one of the (read-only) mirror nodes to be the master.
If you truly need multiple read/write mirrors, you'll probably have to look outside of subversion's provided capabilities. The big problem will be if the synchronization process can't keep up with check-ins happening at different mirrors, either due to simultaneous check-ins or intermittent network connectivity.  Could get to be a real headache.  To avoid such headaches, you might want to consider a distributed version control system, such as hg or git.
Comment: Thx a lot,I'm chinese,my english is not very good.What I mean is commit the source code to one svn server,and use post-commit hook to sync the file to other servers,but i didn't know how should the script write
Comment: That makes sense.  So will read-only server mirrors work for you?  Did you see the example scripts provided in the reference I cited?  They are a few pages down.  I have used the setup described in that document and it worked for me.


Rotating UIView with button in it

Question: I'm trying to rotate a UIview which has in the top left corner a UIButton with the action:
NSLog@"hello";
Now I rotate the UIView 180° and the button is now in the right bottom corner. But the button fires its action only if I press in the top left corner... so its like the buttons position has changed but its action stays at the same place as before the rotation?
I rotate the View with a CAKeyframeAnimation.
CAKeyframeAnimation *rotationAnimation;
rotationAnimation = [CAKeyframeAnimation animationWithKeyPath:@"transform.rotation.z"];

rotationAnimation.values = [NSArray arrayWithObjects:
                            [NSNumber numberWithFloat:0.0 * M_PI],
                            [NSNumber numberWithFloat:0.75 * M_PI],
                            [NSNumber numberWithFloat:1.5 * M_PI],
                            [NSNumber numberWithFloat:2.0 * M_PI], nil];
rotationAnimation.calculationMode = kCAAnimationPaced;

rotationAnimation.removedOnCompletion = NO;
rotationAnimation.fillMode = kCAFillModeForwards;

rotationAnimation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear];
rotationAnimation.duration = 10.0;

CALayer *layer = [rotateView layer];
[layer addAnimation:rotationAnimation forKey:@"rotationAnimation"];

Comment: Put your rotating animation code for details
Answer: Use CGAFFINETRANSFORM for rotaion
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDuration:0.2];
    CGAffineTransform transform=CGAffineTransformMakeRotation(3.14159265);
    yourView.transform=transform;
[UIView commitAnimations];

Comment: yes i triedd, but the i cant press the button while its moving.

Rotating UIView with button in it


Measuring the uncertainty of points along a trajectory

Question: I have a number of 2D trajectories, and I want to be able to estimate the variance of each step along the mean trajectory. I thought that this might be suited to Gaussian process modelling, but then I realised that this may not work...
So, my understanding of a Guassian process is that predictions of one variable (e.g. y) are made conditional on another variable (e.g. x), but where that prediction has an uncertainty for all values of x. So for this 2D (x, y) example, the prediction may look like this: (please excuse the terrible drawing!)

However, in my case, the data is actually drawn from a trajectory through space. (x, y) are just points in Euclidean 2D space. I now want to fit a distribution to this data, so that I can estimate the uncertainty at each step along the trajectory. This may look something like this:

But if I were to just train a regular Gaussian process on this data, it would probably end up looking like this:

What kind of technique should I be using to fit the distribution I am looking for? Is a Gaussian process suitable? Or some other method?
My overall aim is to be able to take any step along the trajectory, and estimate the variance of the data points at this step of the trajectory. I am not actually concerned with making predictions; I just want to estimate this uncertainty.
Answer: The trick here is that you want to parameterize your trajectory so that it is a function of time. In your case the trajectory is $\theta(t) : t \to \mathbb{R}^2$. This is also implicit in the way you phrased the question you want to answer, since you want to estimate the variance of the trajectory at a particular "step" (time).
Gaussian processes have recently been receiving a lot of attention in the context of robot motion planning. I know Byron Boots has been working a lot in this area, for more formal treatments/ideas see this paper and his google scholar page.


HTML JS/JQuery: Store Parameter after button click to use it for a later function

Question: Since the past two days, I am getting confused by implementing a simple way to allow the user the following steps:

User has a table with entries
He can click per row on an edit button
A modal view opens
User enters values
On click on save button these values PLUS the id from the table will be transfered to my controller

What I have achieved so far is:
I am able to filter out the clicked entry after the user clicked edit and before the modal window opens by either
$(this).closest('tr').find('.userID').text()

or
$(button.relatedTarget).attr('id')

But I am not able to hand over the necessary userID to my updateModal() JS function. And I need the ID for my Spring MVC Controller.
When I try to get these parameters inside the updateUser() function they are gone. So between the user click on the edit button and the show modal I lose these information. They are only available straight after click on the edit button, but not later.
What I need is a way to make these parameters available after the modal view opened and that I can send the userID to the controller when she user clicks send.
I found this option:
localStorage.setItem('key', 'value');

But it doesn't help me since my updateUser function has no idea about what ID the modal is working with.
Here is my JS:
function updateUser() {
    alert("try getting parameter");
    alert($(this).closest('tr').find('.userID').text()); //not working HELP pls
    alert($(button.relatedTarget).attr('id')); //not working too
    alert("success?");
    var newValues = {};
    newValues["newName"] = $("#newName").val();
    newValues["newAge"] = $("#newAge").val();
    var userID = "???";

    $.ajax({
        type: "POST",
        contentType: "application/json",
        url: "/api/edit/" + userID,
        data: JSON.stringify(newValues),
        dataType: 'json',
        timeout: 100000,
        success: function (data) {
            console.log("SUCCESS: ", data);
            display("SUCCESS");
            resultObj = data.result;
        },
        error: function (e) {
            console.log("ERROR: ", e);
            display("ERROR");
            //display(2);
        },
        done: function (e) {
            console.log("DONE");
            display("DONE");
            enableSearchButton(true);
        }
    });
}

Here my HTML:

Overview

                    Name
                    Age
                    ID

                                <button type="button" class="btn btn-outline-primary btn-sm" data-toggle="modal"
                                        data-target="#myModal" data-th-id="${person.getId()}">
                                    Edit
                                </button>

                                <button type="button" class="btn btn-outline-danger btn-sm" id="delete">Delete
                                </button>

        <button class="btn btn-primary" type="button" id="addElement">Add Element</button>
        <button class="btn btn-light" type="button" id="DeleteAll">Delete all Elements</button>

Change data

                <button type="button" class="close" data-dismiss="modal"
                        aria-label="Close">×</button>

                        <input name="referencia" id="newName" type="text"
                               class="form-control"
                               placeholder="Enter new name">

                        <input name="referencia" id="newAge" type="text"
                               class="form-control"
                               placeholder="Enter new age">

                <button type="button" class="btn btn-light"
                        data-dismiss="modal">Discard
                </button>
                <button type="button" class="btn btn-primary"
                        onclick="updateUser()">Save
                </button>

Answer: One possible solution to your problem is

When user clicks on table row get the UserID for that respective row i.e. $(this).closest('tr').find('.userID').text()
Store the User ID you retrieved above to model DOM
var userId = $(this).closest('tr').find('.userID').text();
$("#myModal").data('currentUserId', userId);

In updateUser get user ID from DOM.
var userId = $("#myModal").data('currentUserId');

Basically you need to store the UserID in a global context where you can access that once model closes as updateUser and table row click both will be called in different context.
Further, I think you need to read this https://stackoverflow.com/a/3127440/2509344 to understand how this works in JavaScript.
Comment: I want to say special thanks not only for the solution more that you even provide an additional link that I understand what my problem was about and increase my understanding. Thats nice!


How to check if a country belongs to Europe

Question: I'd like to check if the country name provided belongs to Europe.
Does anyone know of a list of european countries that can be used in a Ruby project?
I'd like to do something like this:
spain = Country.named('Spain')
spain.parent # => 'Europe'
japan = Country.named('Japan')
japan.parent # => 'Asia'
https://github.com/jim/carmen/ lets me list subregions of a country, but not a country's parent.
Answer: Try that gem if you really need whole gem for this. You should be able to do:
Country.find_all_countries_by_region('Europe')

to get countries in Europe.
Comment: Mr Manners reminds the Gentle Poster to remember to mark this as the correct answer, _after_ you install and audition that library...
Answer: Check out the Wikipedia article for a complete list. http://en.wikipedia.org/wiki/List_of_European_countries


How can I work out the ratio between the number of home runs this player had in baseball-reference.com

Question: How can I work out the ratio between the number of home runs this player had and the number of balls he hit (as opposed to struck out) using this table?
http://www.baseball-reference.com/players/m/marisro01.shtml

i.e. I have the strike outs and the number of home runs but I am not sure how many he hit from the table.
Answer: The column labeled 'H' is total hits, including home runs.  The "Glossary" link next to the chart near the top will explain what the heading of each column means.


How to load partial using Ajax request?

Question: I want to load partial using Ajax request. I created drop-down list having Ajax request.
<select name="search" id="search" onselect="new Ajax.Request('/calendar/find', {asynchronous:true, evalScripts:true, method:'get', parameters:'is_delivery_address=' + escape(value) }); return false;">

            <option value="0">A</option>
            <option value="1">B</option>
            <option value="2">C Calendar</option>

           </select>

And In the controller:
def find
    render :update do |page|

      if ["0"].include?(params[:is_delivery_address])

        page.replace_html :appRightContent, :partial=> 'calendar/trainer_view'
      else
        page.replace_html :appRightContent, :partial=> 'calendar/venue_view'
      end
    end
end

When I run this code Ajax request is not working and I got following error.
Error: "throw $continue" is deprecated, use "return" instead

What should I do to work this request? Can anybody help me?
Answer: This might be an issue with your version of prototype and rails javascript helper methods. Use an older version of Prototype. I think a version before 1.6.x should work.
Comment: I changed my prototype version into 184.108.40.206. But still it throws the same error and not working ajax request..

How to load partial using Ajax request?


Can't restart nginx server with 2nd sites-available conf

Question: I had one nginx configuration set up and working fine in /etc/nginx/sites-available/default-staging.  Today I've tried to add another for the sendy email marketing app based on this configuration.
After running the service nginx restart command failed I checked online and found that nginx -c /etc/nginx/sites-available/sendy-newsletter -t should highlight any  sytax errors, it gave the following result.
nginx: [emerg] "server" directive is not allowed here in /etc/nginx/sites-available/sendy-newsletter:1
nginx: configuration file /etc/nginx/sites-available/sendy-newsletter test failed

Two things confused me about this, first off I don't understand why the server block would not be allowed, after checking online it seems that this can be caused if sites-enabled config files are not included in the hhtp block of my nginx.conf, but they are:
user www-data;
worker_processes auto;
pid /run/nginx.pid;

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

http {

    ##
    # Basic Settings
    ##

    sendfile on;
    tcp_nopush on;
    tcp_nodelay on;
    keepalive_timeout 65;
    types_hash_max_size 2048;
    # server_tokens off;

    # server_names_hash_bucket_size 64;
    # server_name_in_redirect off;

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

    ##
    # Logging Settings
    ##

    access_log /var/log/nginx/access.log;
    error_log /var/log/nginx/error.log;

    ##
    # Gzip Settings
    ##

    gzip on;
    gzip_disable "msie6";

    gzip_vary on;
    gzip_proxied any;
    gzip_comp_level 6;
    gzip_buffers 16 8k;
    # gzip_http_version 1.1;
    gzip_types text/plain text/css application/json application/x-javascript text/xml application/xml application/xml+rss text/javascript;

    ##
    # nginx-naxsi config
    ##
    # Uncomment it if you installed nginx-naxsi
    ##

    #include /etc/nginx/naxsi_core.rules;

    ##
    # nginx-passenger config
    ##
    # Uncomment it if you installed nginx-passenger
    ##

    #passenger_root /usr;
    #passenger_ruby /usr/bin/ruby;

    ##
    # Virtual Host Configs
    ##

    include /etc/nginx/conf.d/*.conf;
    include /etc/nginx/sites-enabled/*;
}

#mail {
#   # See sample authentication script at:
#   # http://wiki.nginx.org/ImapAuthenticateWithApachePhpScript
#
#   # auth_http localhost/auth.php;
#   # pop3_capabilities "TOP" "USER";
#   # imap_capabilities "IMAP4rev1" "UIDPLUS";
#
#   server {
#       listen     localhost:110;
#       protocol   pop3;
#       proxy      on;
#   }
#
#   server {
#       listen     localhost:143;
#       protocol   imap;
#       proxy      on;
#   }
#}

Secondly when I removed the sendy-newsletter configuration from sites-available and sites-enabled folders, as expected I could restart the nginx server successfully but strangely when I ran nginx -c /etc/nginx/sites-available/default-staging -t I get the same error message as before but the server works!?
nginx: [emerg] "server" directive is not allowed here in /etc/nginx/sites-available/default-staging:1
nginx: configuration file /etc/nginx/sites-available/default-staging test failed

Here is the full configuration I have in /etc/nginx/sites-available/sendy-newsletter, it is sym linked and the same in sites-enabled
server {
    listen 80;
    #listen [::]:80;

    server_name newsletter.example.com;

    autoindex off;
    index index.php index.html;

    root /var/www/sendy-newsletter/public;
#    access_log /var/www/sendy-newsletter/logs/access.log;
#    error_log /var/www/sendy-newsletter/error.log;

    # Don't allow search engines to index any
    add_header X-Robots-Tag "noindex, noarchive";

    location / {
        try_files $uri $uri/ $uri.php?$args;
    }

    location /l/ {
        rewrite ^/l/([a-zA-Z0-9/]+)$ /l.php?i=$1 last;
    }

    location /t/ {
        rewrite ^/t/([a-zA-Z0-9/]+)$ /t.php?i=$1 last;
    }

    location /w/ {
        rewrite ^/w/([a-zA-Z0-9/]+)$ /w.php?i=$1 last;
    }

    location /unsubscribe/ {
        rewrite ^/unsubscribe/(.*)$ /unsubscribe.php?i=$1 last;
    }

    location /subscribe/ {
        rewrite ^/subscribe/(.*)$ /subscribe.php?i=$1 last;
    }

    location ~ \.php$ {
        # --PHP5-FPM CONFIG START (keep fastcgi_param HTTPS OFF)--
        #fastcgi_pass unix:/var/run/php5-fpm.sock;
        ##fastcgi_param HTTPS $fastcgi_https;
        #fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        # --PHP5-FPM CONFIG START--

        # --HHVM CONFIG START--
        fastcgi_pass   127.0.0.1:9000;
        fastcgi_index  index.php;
        fastcgi_param  SCRIPT_FILENAME $document_root$fastcgi_script_name;
        #include        fastcgi_params;
        try_files $uri $uri/ @handler;
        # --HHVM CONFIG END--

        include fastcgi_params;
    }

    location ~* ^.+.(jpg|jpeg|gif|css|png|js|ico|xml)$ {
        access_log off;
        log_not_found off;
        expires 30d;
    }
}

UPDATE
I checked my nginx error logs and I'm getting this message after I try to restart nginx.
2015/11/18 13:09:44 [emerg] 21899#0: bind() to 0.0.0.0:80 failed (98: Address already in use)
2015/11/18 13:09:44 [emerg] 21899#0: bind() to 0.0.0.0:80 failed (98: Address already in use)
2015/11/18 13:09:44 [emerg] 21899#0: bind() to 0.0.0.0:80 failed (98: Address already in use)
2015/11/18 13:09:44 [emerg] 21899#0: bind() to 0.0.0.0:80 failed (98: Address already in use)
2015/11/18 13:09:44 [emerg] 21899#0: bind() to 0.0.0.0:80 failed (98: Address already in use)
2015/11/18 13:09:44 [emerg] 21899#0: still could not bind()

Also this is the result of running:
$ sudo nginx -c /etc/nginx/nginx.conf -t
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful

Also I tried running the syntax test after removing the configuration file I am not using
$ sudo rm default-staging
$ sudo rm ../sites-enabled/default-staging
$ sudo nginx -c /etc/nginx/sites-available/sendy-newsletter -t
nginx: [emerg] "server" directive is not allowed here in /etc/nginx/sites-available/sendy:1
nginx: configuration file /etc/nginx/sites-available/sendy test failed
Comment: Like I said, you can only run nginx -c on the full.conf. There is no need, and no use to run it on just one directive. Can you restart nginx if you just have one directive in sites-enabled? Try it with the default one first.
Answer: Of course you're getting an error :) nginx -c is supposed to check your whole web server config, not just the server block. Just run it on the main conf file and you'll see. It is automatically taking into account any linked server directives.
That's why you should delete the (link to the) directive you don't use from the sites-enabled directory before making the check. You can always link it back.
Comment: I nginx -c works passes on the nginx.conf file but I still can't restart nginx :(  I updated my question with more details
Comment: figured it out, see my answer.  Thanks for your help :)
Comment: Yep, it was clear that port 80 is the culprit, question was just why, could have been conflicting site directives. Anyway, good you solved it. :)
Answer: I'm such a dope, forgot I had varnish running on the other application so port 80 was in use.  That was the issue, the error logs pointed me in the right direction while the nginx -c just confused me.


Alternative Top Menu bar for logged in users only via their Role

Question: I want to have an alternative top menu bar for certain Roles when they are logged in. For example, 'Teachers' have one top menu bar, 'Students' have another type.
For now, I want to do this using Rules, is this a good approach or is there an easier way. Simple functionality is the key here so at this time I'm not looking to hack tpl.php files as I just want to get something working for demo purposes.
I'm using Bootstrap and happy to stay that way for the future.
Any suggestions & advice on the above, most welcome. Thanks in advance.
Answer: When you create a menu, a block should be created at the same time (https://drupal.org/taxonomy/term/32478). Go to Admin, Structures, Blocks and place one of those menus in the area you want it to appear - under Role restriction at the bottom of the block configuration, you can decide who has access to that specific menu. Repeat for each menu - this way, the menu appears in the same spot, but a different menu will appear for different roles.
Comment: Thanks Geoff, I never really considered the Blocks option since I've been messing with others functions within Bootstrap. The above link is handy too, I'll go read it now and get back to your answer when I've made my result. Again, thanks.
Comment: Hummh.... I tried that, (and cleared caches). To test, I put a 'Test link' in a 'Teacher' topbar menu (in my case 'Header') and set it only to that role. Normal thing, cleared cache, logged out and back in, result: it shows the same top menu for all members even though only certain roles are 'assigned' to that menu. The 'student' sees also the 'teachers' topbar menu when they really shouldn't. I have missed something here or is my approach incorrect?  I'm using Panels for the dashboard layouts, but I doubt that matters. I could be wrong.
Comment: Do you have other blocks of content that you can test by restricting by Role?  Even just a test block with dummy text that appears on the content area. This might help figure out the next step.
Comment: I found some other resources that suggest it may not work with Panels.
Comment: Thanks for your reply. I'm also using a number of other functions, namely Workbench, Panels, Rules & more, etc Possible that they are influencing them. Had this issue for weeks, but it's not major at moment, but would like to get it resolved at some point. Will have to get my 'magnifying glass' to look deeper. Anyone else got idea's please drop them by here.
Answer: Just navigate to admin/structure/menus
Create menu Students and Teacher and assign some menus into it.
These menus will automatically create two blocks on path admin/structure/blocks
Create a region in info file header_menu and render it in page.tpl.php
Now assign both these menus to the same region and restrict its display to roles by its display settings.

Hope it will help!
Answer: I found an alternative to my original question which I have resolved myself, for others, here is the answer to my problem.
What I wanted to do was only show a top-menu bar link to certain members and hidden to others. I resolved this by setting the "Selection Rules" of the page to: User: role: Logged in user has one of 'whatever role you want to allow to show' (i.e Teacher Role) and setting the criteria to 'Only one criteria must pass'. So if set to 'Teacher' when the teacher logs in the menu link shows for them, if the 'student' logs in (which has no permission to view the link) they do not see the said link.
It must be stated that link to the page you wish to use, must be in your Menu Links (under the Structure) in my case, the 'Main Menu' links structure.
Maybe there are other ways to do this, but for now a simple result works for what I need for now and I'll probably replace it with some CSS structure, but it works. Try it yourself.


PublishSubject with backpressure in RxJava 2.x

Question: I am currently choosing between RxJava 1.x or 2.x for my current project.
I basically need a PublishSubject with a backpressure strategy onBackpressureLatest().
I want to choose RxJava 2.x, but i can't quite get my head around on how to apply a backpressure strategy to a PublishSubject, as it inherits from Observable and not from Flowable.

Could you please tell me how to create a PublishSubject with a onBackpressureLatest() backpressure strategy in RxJava 2.x ?
Answer: In 2.x the backpressure was moved to the base type Flowable and its hot partners PublishProcessor, ReplayProcessor etc.
PublishProcessor<Integer> pp = PublishProcessor.create();
Flowable<Integer> out = pp.onBackpressureLatest();

Comment: @akarnokd How to call the onNext() of subscriber of Flowable in this case? I tried to do pp.onNext(1) but it's not calling the flowable's subscribers onNext()
Comment: @SandipSoni Please open a question where you detail exactly what you have and what you tried, with source code.
Answer: I used at some point something like this:
Subject<Object> emitterSubject = PublishSubject.<Object>create().toSerialized();

emitterSubject.toFlowable(BackpressureStrategy.LATEST)


Add inline widget to product display

Question: I am trying to integrate our Drupal 7 Commerce install with Digital River's where-to-buy widget.
All I need to do is add a little JS to the product page, with a script variable set to the product sku.  On page load, this inline JS runs and adds a button that when clicked will pop-up a lightbox with where-to-buy information.  This script has a variable that requires a SKU to be entered.  If I add the snippet to my node-template it works fine.
HOWEVER, I have several products on each product display, and I have 2 product attributes that can be selected.  This, of course, refreshes the node/entity field values in my page, like the title, a product image and so forth.  This will not refresh the sku parameter of my javascript snippet though, so my WTB button does not update.  IE, if I did something like this:

I discovered that it would initially load but the product:sku wouldn't change as I selected a new attribute.
So, I also discovered that my values would update if they were displayed via the render() function.  So, if I just did this:
<?php print render($content['product:sku']) ?>

I would get an element that updates 'properly' when a product attribute is selected.  It does, however come with a lot of div's wrapping it, so I can't use it as a parameter in my script,and I didn't want to override the 'sku' field template because I need that sku elsewhere on the page, and even overriding the template, I would still get a wrapper around it.
Ok, so my next attempt was to create a 'virtual' field, using the virtual_field module.  This just lets you have a dummy field that doesn't get stored anywhere but still lets you create custom templates and specify display formatters.  I created a dummy field that just contains the product sku.
Using this, I created a custom field template (field--field-product-wtb.tpl.php) for this virtual field like so:
this will update: <?php print render($item); ?>
but this gets stripped out:

And then in my node template, I just do this:
<?php print render($content['product:field_product_wtb']) ?>

It works on initial load, and when a product attribute is selected, the sku does change (the 'this will update' part) but the entire script tag gets stripped out and my button disappears.  I guess because it gets filtered via some xss protection, but I haven't tracked it down.  As near as I can tell, this is because when content on a page is updated via ajax, the HTML returned from a tpl file is sanitized and things like script tags are filtered out.
Now I'm at a loss as to how to get this to work.
Answer: You could probably do something like this:

Add hidden form element with product SKU
Read the SKU in a JavaScript Drupal.behavior

The key is making the SKU available in the DOM and using Drupal.behaviors to read it, as they run / are reattached after the AJAX form update.
i.e:
/**
 * Implements hook_form_FORM_ID_alter
 */
function MYMODULE_form_commerce_cart_add_to_cart_form_alter(&$form, &$form_state){

  // Add a hidden SKU element to the add to cart form
  if (isset($form_state['default_product']->sku)){
    $form['product_sku'] = array(
      '#type' => 'hidden',
      '#value' => $form_state['default_product']->sku,
    );
  }

}

Then in your JS file
(function ($) {

  Drupal.behaviors.pswtb_loader = {
    attach: function (context, settings) {
     if($('input[name=product_sku]').length > 0){
       pswtb.loader.show({
         widgetConfigurationId: "3a4acc53-216e-48da-8e92-bfaeb58168a7",
         sku: "US_" +  $('input[name=product_sku]').val();
       });
     }
    }
  };

})(jQuery);

Add inline widget to product display


Unable to locate element href

Question: Please find the attached image i want to fetch the Admins and moderators name and href link .
i have tried below :
grp="https://m.facebook.com/groups/162265541050378?view=members&ref=m_notif&notif_t=group_r2j_approved"
driver.get(grp)
root1=driver.find_element_by_id("//*[@id='rootcontainer']")
if root1>0:
    admin=driver.find_elements_by_xpath("//*[@class='_4kk6 _5b6s']")
    ilink = admin.get_attribute('href')
    ilink2=admin.get_attribute('')
    print(ilink)

error
selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"css selector","selector":"[id="//*[@id='rootcontainer']"]"}
  (Session info: chrome=91.0.4472.101)

Answer: for Admins and moderators name you can do this :
for names in driver.find_elements(By.XPATH, "//div[contains(@id, 'member_')]/div[2]/descendant::h3[1]")
    print(names.text)

for href :
for hrefs in driver.find_elements(By.XPATH, "//div[contains(@id, 'member_')]/div[4]/descendant::a")
     print(hrefs.get_attribute('href'))

Comment: I have updated the code, Let me know if you have any issues.
Comment: My bad ! I have updated the code. use this `print(hrefs.get_attribute('href'))`
Comment: Admins and moderators names is known to you ? I mean in advance do you know how many are there
Comment: @pkk : I have updated the code in the discussion, try it out and let me know
Comment: for href not able to get the href link getting only text name . and getting printed two times
Comment: working thanks . can please advise how should print only  Admins and moderators names in name.text as it is printing other members name also refer screenshot.
Comment: not actually but i have to deal with Admins and moderators only . others are not required so i was asking how should i neglect them. and also in href it is printing two time in loop
Comment: Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/233782/discussion-between-pkk-and-cruisepandey).
Answer: First of all //*[@id='rootcontainer'] is XPath, not ID. So you can use it like this
root1=driver.find_element_by_xpath("//*[@id='rootcontainer']")

or this:
root1=driver.find_element_by_id("rootcontainer")

Also this ilink2=admin.get_attribute('') is not correct. Will not work.

Unable to locate element href


SQL Server Backup days

Question: I have a server running Windows Server 2008 SP2, and SQL Server 2005 Express.
There is a daily backup which runs via the Windows Task Scheduler. It keeps the last 7 days of backups and deletes the earlier ones automatically.
How/where do I change the number of days of backups that it keeps ?
UPDATE:
As per comments to the question, here is the contents of the script that is running:
exec expressmaint
   @database      = 'xxxx',
   @optype        = 'DB',
   @backupfldr    = 'c:\sql_data\backup',
   @reportfldr    = 'c:\sql_data\backup\reports',
   @verify        = 1,
   @dbretainunit  = 'weeks',
   @dbretainval   = 1,
   @rptretainunit = 'weeks',
   @rptretainval  = 1,
   @report        = 1
go

I would now like to store 4 days of backups instead of 7
Comment: @RandolphWest since he is using SQL Server Express it does not include SQL Server Agent service.
Comment: We cannot really give you that answer. The scheduled task is probably configured to call a script, you will need to look through that script and figure out what it is doing to determine where to change the number of days. If you want to post the script or command it is executing we might be able to point you in the right direction.
Comment: Shawn, good catch. I'll delete my comment(s).
Comment: @ShawnMelton - thanks - in Task Scheduler, it just shows the Task Name and when it was last run etc. I don't see where it shows the name of a script - could you point me in the right direction ?
Comment: What backup software are you using? Telling us that it runs via the task scheduler will make most assume it's Windows built-in backup but we shouldn't have to assume anything.
Comment: @JohnGardeniers It is something built-in to windows. There is no third party backup software being used that I am aware of.
Comment: @PSellaz I don't have a Windows 08 server in front of me but I believe what you need to look at is under the Action tab of the properties of the particular task. Trying to find a screenshot to reference off of.
Comment: Screenshot of what the Action looks like configured: http://blogs.technet.com/cfs-file.ashx/__key/CommunityServer-Blogs-Components-WeblogFiles/00-00-00-40-98-metablogapi/0245.ras5.jpg
Comment: @ShawnMelton , great - I have located the script and I will edit the question to post the script contents.
Answer: So your task is calling a T-SQL script that is being executed against the instance of SQL Server. It is calling a stored procedure that has the T-SQL commands to do the backups and cleanup, at least according to the variables (all the "@words"). I would guess this stored procedure expressmaint is stored in the master database. If you are familar with T-SQL you can open up SSMS, find this stored procedure, right-click on it and then left-click on "modify". This will open up the procedure and show you all the code it is executing. Making your changes and then clicking "execute" (or F5 key) will update the procedure, but don't do this until you are sure what you are changing.
From what the script looks like I would gather that    @dbretainunit  = 'weeks',
   @dbretainval   = 1, are the variables that pertain to how long your backups are kept. You will need to determine in the stored procedure how it is handling these variables. It might be basic and just simply change it to @dbretainunit = 'days', @dbretainval = 4, per your requirement. However you will not know that until you verify what it does.
Comment: Thank for the pointers - you were quite right and it was that simple !

SQL Server Backup days


Texture won't appear using native code to load it with opengl es on android

Question: I'm trying to apply a texture to an object in opengl es from the native side and I have no idea why it isn't showing up.  I have a couple random objects drawn on the screen, and they're all visible and everything.  I applied color to some shapes using glColor4f and that works fine.  I'm trying to use a texture on the last object that gets drawn but it ends up being the same color as the one previous.
I was originally loading the texture from a png, but I decided to simplify things by loading it from a file that contains raw RGB data.  It's 16 pixels x 16 pixels, and I've tried sizes up to 512 by 512 with the same result.
Here's how I'm initializing everything:
bool Activity::_initGL () {
  const EGLint attribs[] = {
    EGL_SURFACE_TYPE, EGL_WINDOW_BIT,
    EGL_BLUE_SIZE, 8,
    EGL_GREEN_SIZE, 8,
    EGL_RED_SIZE, 8,
    EGL_NONE
  };
  EGLint dummy, format;
  EGLint numConfigs;
  EGLConfig config;

  display = eglGetDisplay(EGL_DEFAULT_DISPLAY);
  eglInitialize(display, 0, 0);
  eglChooseConfig(display, attribs, &config, 1, &numConfigs);
  eglGetConfigAttrib(display, config, EGL_NATIVE_VISUAL_ID, &format);
  ANativeWindow_setBuffersGeometry(app->window, 0, 0, format);
  surface = eglCreateWindowSurface(display, config, app->window, NULL);
  context = eglCreateContext(display, config, NULL, NULL);

  if (eglMakeCurrent(display, surface, surface, context) == EGL_FALSE) {
    LOGE("Unable to eglMakeCurrent");
    return false;
  }

  eglQuerySurface(display, surface, EGL_WIDTH, &width);
  eglQuerySurface(display, surface, EGL_HEIGHT, &height);
  glViewport(0,0, width, height);
}

And then I enable the necessary things and try to create the texture:
void postInit () {
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
  glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_FASTEST);
  glDisable( GL_BLEND );
  glDisable( GL_LIGHTING );
//   glEnable(GL_CULL_FACE);
  glEnable( GL_TEXTURE_2D );

  glShadeModel(GL_SMOOTH);
  glDisable(GL_DEPTH_TEST);

  glClearColor(0,0,0,1);
  glEnableClientState(GL_VERTEX_ARRAY);
  glEnableClientState(GL_TEXTURE_COORD_ARRAY);

//   glTexEnvx( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE );
  glMatrixMode( GL_MODELVIEW );

  GLuint texIDarray[1];
  glGenTextures( 1, texIDarray );
  glActiveTexture( GL_TEXTURE0 );
  glBindTexture( GL_TEXTURE_2D, texIDarray[0] );
  glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, (GLsizei)16, (GLsizei)16, 0, GL_RGB, GL_UNSIGNED_BYTE, protData);

}

And here's where the texture gets drawn, someday:
void drawImpl () {
  glClear(GL_COLOR_BUFFER_BIT);
  glLoadIdentity();
//  glDisable(GL_TEXTURE_2D);
//  glTexEnvx( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE );
//  glEnableClientState(GL_VERTEX_ARRAY);
//  glViewport(0, 0, wid, hei);

#define fX(x) ((int)(x * (1  << 16)))
  static int verts[6] = {
    0,0,
    65536,0,
    0,30000
  };
  glVertexPointer(2, GL_FIXED, 0, verts);
//   glColor4f(1,0,1,1);
  glDrawArrays(GL_TRIANGLES, 0, 3);

  static int poo[12] = {
    40000,-5000,
    40000,-30000,
    60000,-5000,

60000,-5000,
40000,-30000,
60000,-30000
  };
  glVertexPointer(2, GL_FIXED, 0, poo);
 // glColor4f(1,1,1,1);
  glDrawArrays(GL_TRIANGLES, 0, 6);

  static int pee[12] = {
    40000, 5000,
    60000, 5000,
    60000,30000,

40000, 5000,
60000,30000,
40000,30000
  };
  glVertexPointer(2, GL_FIXED, 0, pee);
//    glColor4f(1,0,1,1);
  glDrawArrays(GL_TRIANGLES, 0, 6);

  glEnable(GL_TEXTURE_2D);
  static int squareVerts[12] = {
0,0,
fX(1),0,
0,fX(1),

0,fX(1),
fX(1),0,
fX(1),fX(1)
  };

  static int texCoords[12] = {
0,0,
fX(1),0,
0,fX(1),

0,fX(1),
fX(1),0,
fX(1),fX(1)
  };

  //glTranslatef( (float)-.25, (float)-.5, (float)0);

 // glColor4f(0,0,0,0);
//  glEnableClientState(GL_TEXTURE_COORD_ARRAY);
  glActiveTexture( GL_TEXTURE0 );
//  glBindTexture(GL_TEXTURE_2D, texID);
  glTexEnvx( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE );
  glTexParameterx( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT );
  glTexParameterx( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT );
  glVertexPointer(2, GL_FIXED, 0, squareVerts);

  glTexCoordPointer(2, GL_FLOAT, 0, texCoords);
 // glEnableClientState(GL_TEXTURE_COORD_ARRAY);
  glEnable( GL_TEXTURE_2D );
  glDrawArrays(GL_TRIANGLES, 0, 6);

//    glDisableClientState(GL_VERTEX_ARRAY);
//    glDisableClientState(GL_TEXTURE_COORD_ARRAY);
}

I deliberately left some of the commented out things to show the other things I have tried doing.
I am totally at a dead end with this right now.  If anyone has any suggestions or anything it would make me super happy, and that is good.
Answer: Seems like you messed up your texture coordinates.. They should be between 0 and 1, not between 0 and 1<<16. Another thing is your "glColor4f" will also affect your texture by modulating it and for normal texture draw it needs to be set to (1,1,1,1).
Comment: Thanks!  The coordinates were the problem.


Views Dependent Filter showing when no controller value selected

Question: I'm using Views Dependent Filters to have a filter show based on the value of a filter above it. It is working for the most part but it is showing the field by default (when no controller value is selected.)
When my multiple select filter  being used as the controller, the dependent field shows even when no value is selected. For example:
Vehicle:

Car (Set as controller)
Boat
Plane

Tire Size (Dependent Filter)

Small
Med
Large

Tire size shows when "car" is selected but also shows when no value is selected. I believe this the module is not intended to function this way.
Is there a solution to this or a possible alternative?
Answer: This was a bug relating the default views multiple select filter. I used the Better Exposed Filters checkboxes and now the dependent filter works as intended.


build_runner não executa o comando flutter pub run build_runner build --delete-conflicting-outputs --verbose

Question: Olá,
criei um projeto com o comando flutter create.
como vou usar modular a ativei o slidy no projeto com o comando slidy start
até ai tudo bem, mas quando tento rodar o comando para gerar os .g.dart, ele não executa.
na verdade executa, mais fica rodando em um loop infinito.
já tentei fazer clean, get packages, e até mudei o environment para outra versão
até agora nada
segue minha pilha:
PS C:\Users\MARCOS\Documents\mobile\github_search\github_search> flutter pub get
Running "flutter pub get" in github_search...                       0,6s
PS C:\Users\MARCOS\Documents\mobile\github_search\github_search> flutter pub run build_runner build --delete-conflicting-outputs --verbose
[ +105 ms] executing: [C:\src\flutter/] git -c log.showSignature=false log -n 1 --pretty=format:%H
[  +58 ms] Exit code 0 from: git -c log.showSignature=false log -n 1 --pretty=format:%H
[        ] 2ae34518b87dd891355ed6c6ea8cb68c4d52bb9d
[        ] executing: [C:\src\flutter/] git tag --contains HEAD
[ +185 ms] Exit code 0 from: git tag --contains HEAD
[        ] 1.20.1
[  +12 ms] executing: [C:\src\flutter/] git rev-parse --abbrev-ref --symbolic @{u}
[  +35 ms] Exit code 0 from: git rev-parse --abbrev-ref --symbolic @{u}
[        ] origin/stable
[        ] executing: [C:\src\flutter/] git ls-remote --get-url origin
[  +27 ms] Exit code 0 from: git ls-remote --get-url origin
[        ] https://github.com/flutter/flutter.git
[  +61 ms] executing: [C:\src\flutter/] git rev-parse --abbrev-ref HEAD
[  +30 ms] Exit code 0 from: git rev-parse --abbrev-ref HEAD
[        ] stable
[  +45 ms] Artifact Instance of 'AndroidMavenArtifacts' is not required, skipping update.
[        ] Artifact Instance of 'AndroidGenSnapshotArtifacts' is not required, skipping update.
[        ] Artifact Instance of 'AndroidInternalBuildArtifacts' is not required, skipping update.
[        ] Artifact Instance of 'IOSEngineArtifacts' is not required, skipping update.
[        ] Artifact Instance of 'FlutterWebSdk' is not required, skipping update.
[   +3 ms] Artifact Instance of 'WindowsEngineArtifacts' is not required, skipping update.
[        ] Artifact Instance of 'MacOSEngineArtifacts' is not required, skipping update.
[        ] Artifact Instance of 'LinuxEngineArtifacts' is not required, skipping update.
[        ] Artifact Instance of 'LinuxFuchsiaSDKArtifacts' is not required, skipping update.
[        ] Artifact Instance of 'MacOSFuchsiaSDKArtifacts' is not required, skipping update.
[   +1 ms] Artifact Instance of 'FlutterRunnerSDKArtifacts' is not required, skipping update.
[        ] Artifact Instance of 'FlutterRunnerDebugSymbols' is not required, skipping update.
[  +19 ms] Artifact Instance of 'MaterialFonts' is not required, skipping update.
[        ] Artifact Instance of 'GradleWrapper' is not required, skipping update.
[        ] Artifact Instance of 'AndroidMavenArtifacts' is not required, skipping update.
[        ] Artifact Instance of 'AndroidGenSnapshotArtifacts' is not required, skipping update.
[        ] Artifact Instance of 'AndroidInternalBuildArtifacts' is not required, skipping update.
[        ] Artifact Instance of 'IOSEngineArtifacts' is not required, skipping update.
[        ] Artifact Instance of 'FlutterWebSdk' is not required, skipping update.
[        ] Artifact Instance of 'FlutterSdk' is not required, skipping update.
[        ] Artifact Instance of 'WindowsEngineArtifacts' is not required, skipping update.
[   +5 ms] Artifact Instance of 'MacOSEngineArtifacts' is not required, skipping update.
[        ] Artifact Instance of 'LinuxEngineArtifacts' is not required, skipping update.
[        ] Artifact Instance of 'LinuxFuchsiaSDKArtifacts' is not required, skipping update.
[        ] Artifact Instance of 'MacOSFuchsiaSDKArtifacts' is not required, skipping update.
[        ] Artifact Instance of 'FlutterRunnerSDKArtifacts' is not required, skipping update.
[        ] Artifact Instance of 'FlutterRunnerDebugSymbols' is not required, skipping update.
[        ] Artifact Instance of 'IosUsbArtifacts' is not required, skipping update.
[        ] Artifact Instance of 'IosUsbArtifacts' is not required, skipping update.
[        ] Artifact Instance of 'IosUsbArtifacts' is not required, skipping update.
[        ] Artifact Instance of 'IosUsbArtifacts' is not required, skipping update.
[        ] Artifact Instance of 'IosUsbArtifacts' is not required, skipping update.
[        ] Artifact Instance of 'FontSubsetArtifacts' is not required, skipping update.
[  +24 ms] Using C:\src\flutter\.pub-cache for the pub cache.
[  +10 ms] executing: C:\src\flutter\bin\cache\dart-sdk\bin\pub.bat run build_runner build --delete-conflicting-outputs --verbose
Precompiling executable...
Precompiled build_runner:build_runner.
[INFO] Generating build script...
[INFO] Generating build script completed, took 347ms

[INFO] Creating build script snapshot......
[INFO] Creating build script snapshot... completed, took 13.4s

[INFO] BuildDefinition:Initializing inputs
[INFO] BuildDefinition:Building new asset graph...
[INFO] BuildDefinition:Building new asset graph completed, took 714ms

[INFO] BuildDefinition:Checking for unexpected pre-existing outputs....
[INFO] BuildDefinition:Checking for unexpected pre-existing outputs. completed, took 1ms

[INFO] Build:Running build...
[INFO] build_resolvers:Generating SDK summary...
[SEVERE] mobx_codegen:mobx_generator on test/app/app_controller_test.dart:

Bad state: Unexpected diagnostics:
C:\src\flutter\bin\cache\pkg\sky_engine\lib\ui\channel_buffers.dart:119:41 - This requires the 'non-nullable' language feature to be enabled.
C:\src\flutter\bin\cache\pkg\sky_engine\lib\ui\channel_buffers.dart:152:17 - This requires the 'non-nullable' language feature to be enabled.
C:\src\flutter\bin\cache\pkg\sky_engine\lib\ui\channel_buffers.dart:88:62 - This requires the 'non-nullable' language feature to be enabled.
C:\src\flutter\bin\cache\pkg\sky_engine\lib\ui\channel_buffers.dart:153:38 - This requires the 'non-nullable' language feature to be enabled.
C:\src\flutter\bin\cache\pkg\sky_engine\lib\ui\channel_buffers.dart:186:51 - This requires the 'non-nullable' language feature to be enabled.
C:\src\flutter\bin\cache\pkg\sky_engine\lib\ui\channel_buffers.dart:133:32 - This requires the 'non-nullable' language feature to be enabled.
C:\src\flutter\bin\cache\pkg\sky_engine\lib\ui\channel_buffers.dart:154:25 - This requires the 'non-nullable' language feature to be enabled.
C:\src\flutter\bin\cache\pkg\sky_engine\lib\ui\channel_buffers.dart:18:17 - This requires the 'non-nullable' language feature to be enabled.
C:\src\flutter\bin\cache\pkg\sky_engine\lib\ui\channel_buffers.dart:64:4 - This requires the 'non-nullable' language feature to be enabled.C:\src\flutter\bin\cache\pkg\sky_engine\lib\ui\channel_buffers.dart:168:32 - This requires the 'non-nullable' language feature to be enabled.
C:\src\flutter\bin\cache\pkg\sky_engine\lib\ui\channel_buffers.dart:47:14 - This requires the 'non-nullable' language feature to be enabled.
C:\src\flutter\bin\cache\pkg\sky_engine\lib\ui\channel_buffers.dart:159:38 - This requires the 'non-nullable' language feature to be enabled.
C:\src\flutter\bin\cache\pkg\sky_engine\lib\ui\channel_buffers.dart:132:37 - This requires the 'non-nullable' language feature to be enabled.
C:\src\flutter\bin\cache\pkg\sky_engine\lib\ui\channel_buffers.dart:118:48 - This requires the 'non-nullable' language feature to be enabled.
C:\src\flutter\bin\cache\pkg\sky_engine\lib\ui\channel_buffers.dart:19:11 - This requires the 'non-nullable' language feature to be enabled.

Answer: Esse é um problema do build_runner, faça um downgrade para o 1.10.1.
Pelo que entendi o build_runner depende do dart 2.10 que esta em prerelease, no canal dev.
Comment: Me salvou man, valeu!
Answer: Usando o canal stable você pode fazer um override na dependencia analyzer.
dependency_overrides:
    analyzer: '0.39.14'


How to replace characters from string starting from some index

Question: i want to replace all characters after 16 number of characters and replace it with ... how to do this any idea?
string foo = "something is going to happen";

output i want like this: "something is goi..."

Answer: You can check the Length property of the input string, and if it's longer than 16 characters, use the Substring method to get the first part of the string and add the ellipses to it, otherwise just use the input as-is:
string output = foo.Length > 16 ? foo.Substring(0, 16) + "..." : foo;

Answer: You can use the Substring method to do this.
string foo = "something is going to happen";

string output = "";

if (foo.Length > 16)
    output = foo.Substring(0, 16) + "...";
else
    output = foo;

Answer: There are multiple ways to truncate a string and multiples ways to append.
string foo = "something is going to happen";
string output = foo;
if (foo.Length > 16)
{
    //use one of these:
    //output = foo.Substring(0, 16) + "..."; //Substring
    output = foo.Remove(16) + "..."; //Remove
    //output = foo[.. 16] + "..."; //Range, from C# 8
}


mysql replace last group of digits in IP address

Question: I would like to replace the last digits of all IP:port's with a *.
For example: 192.168.1.1:2000 should become 192.168.1.*:2000
Comment: I suggest you do that outside of mysql, like in php or any other language you know to get ip in a loop, using . as a delimiter, change it and set the new value to the table where column like '%192.168.1.1:200%' . But do it outside of mysql to run your loops.
Answer: set @ip = '192.168.1.1:2000';
select concat(
    substring_index(substring_index(@ip, ':', 1), '.', 3),
    '.*:',
    substring_index(@ip, ':', -1)
);

If you want to understand how it works run the following query:
set @ip = '192.168.1.1:2000';
select @ip
    , substring_index(@ip, ':', 1)
    , substring_index(@ip, ':', -1)
    , substring_index(substring_index(@ip, ':', 1), '.', 3);

It will return
192.168.1.1  2000  192.168.1

You just need to concatenate the last two columns and the middle part (.*:)


What is differential execution?

Question: I stumbled upon a Stack Overflow question, How does differential execution work?, which has a VERY long and detailed answer. All of it made sense... but when I was done I still had no idea what the heck differential execution actually is. What is it really?
Comment: You may ask for further explanation commenting on that answers ...
Comment: Still want me to try to get it across? What did you have in mind as a possible explanation?
Answer: REVISED. This is my Nth attempt to explain it.
Suppose you have a simple deterministic procedure that executes repeatedly, always following the same sequence of statement executions or procedure calls.
The procedure calls themselves write anything they want sequentially to a FIFO, and they read the same number of bytes from the other end of the FIFO, like this:**

The procedures being called are using the FIFO as memory, because what they read is the same as what they wrote on the prior execution.
So if their arguments happen to be different this time from last time, they can see that, and do anything they want with that information.
To get it started, there has to be an initial execution in which only writing happens, no reading.
Symmetrically, there should be a final execution in which only reading happens, no writing.
So there is a "global" mode register containing two bits, one that enables reading and one that enables writing, like this:

The initial execution is done in mode 01, so only writing is done.
The procedure calls can see the mode, so they know there is no prior history.
If they want to create objects they can, and put the identifying information in the FIFO (no need to store in variables).
The intermediate executions are done in mode 11, so both reading and writing happen, and the procedure calls can detect data changes.
If there are objects to be kept up to date,
their identifying information is read from and written to the FIFO,
so they can be accessed and, if necessary, modified.
The final execution is done in mode 10, so only reading happens.
In that mode, the procedure calls know they are just cleaning up.
If there were any objects being maintained, their identifiers are read from the FIFO, and they can be deleted.

But real procedures do not always follow the same sequence.
They contain IF statements (and other ways of varying what they do).
How can that be handled?
The answer is a special kind of IF statement (and its terminating ENDIF statement).
Here's how it works.
It writes the boolean value of its test expression, and it reads the value that the test expression had last time.
That way, it can tell if the test expression has changed, and take action.
The action it takes is to temporarily alter the mode register.

Specifically, x is the prior value of the test expression, read from the FIFO (if reading is enabled, else 0), and y is the current value of the test expression, written to the FIFO (if writing is enabled).
(Actually, if writing is not enabled, the test expression is not even evaluated, and y is 0.)
Then x,y simply MASKs the mode register r,w.
So if the test expression has changed from True to False, the body is executed in read-only mode. Conversely if it has changed from False to True, the body is executed in write-only mode.
If the result is 00, the code inside the IF..ENDIF statement is skipped.
(You might want to think a bit about whether this covers all cases - it does.)
It may not be obvious, but these IF..ENDIF statements can be arbitrarily nested, and they can be extended to all other kinds of conditional statements like ELSE, SWITCH, WHILE, FOR, and even calling pointer-based functions. It is also the case that the procedure can be divided into sub-procedures to any extent desired, including recursive, as long as the mode is obeyed.
(There is a rule that must be followed, called the erase-mode rule, which is that in mode 10 no computation of any consequence, such as following a pointer or indexing an array, should be done. Conceptually, the reason is that mode 10 exists only for the purpose of getting rid of stuff.)
So it is an interesting control structure that can be exploited to detect changes, typically data changes, and take action on those changes.

Its use in graphical user interfaces is to keep some set of controls or other objects in agreement with program state information. For that use, the three modes are called SHOW(01), UPDATE(11), and ERASE(10).
The procedure is initially executed in SHOW mode, in which controls are created, and information relevant to them populates the FIFO.
Then any number of executions are made in UPDATE mode, where the controls are modified as necessary to stay up to date with program state.
Finally, there is an execution in ERASE mode, in which the controls are removed from the UI, and the FIFO is emptied.

The benefit of doing this is that, once you've written the procedure to create all the controls, as a function of the program's state, you don't have to write anything else to keep it updated or clean up afterward.
Anything you don't have to write means less opportunity to make mistakes.
(There is a straightforward way to handle user input events without having to write event handlers and create names for them. This is explained in one of the videos linked below.)
In terms of memory management, you don't have to make up variable names or data structure to hold the controls. It only uses enough storage at any one time for the currently visible controls, while the potentially visible controls can be unlimited. Also, there is never any concern about garbage collection of previously used controls - the FIFO acts as an automatic garbage collector.
In terms of performance, when it is creating, deleting, or modifying controls, it is spending time that needs to be spent anyway.
When it is simply updating controls, and there is no change, the cycles needed to do the reading, writing, and comparison are microscopic compared to altering controls.
Another performance and correctness consideration, relative to systems that update displays in response to events, is that such a system requires that every event be responded to, and none twice, otherwise the display will be incorrect, even though some event sequences may be self-canceling. Under differential execution, update passes may be performed as often or as seldom as desired, and the display is always correct at the end of a pass.

Here is an extremely abbreviated example where there are 4 buttons, of which buttons 2 and 3 are conditional on a boolean variable.

In the first pass, in Show mode, the boolean is false, so only buttons 1 and 4 appear.
Then the boolean is set to true and pass 2 is performed in Update mode, in which buttons 2 and 3 are instantiated and button 4 is moved, giving the same result as if the boolean had been true on the first pass.
Then the boolean is set false and pass 3 is performed in Update mode, causing buttons 2 and 3 to be removed and button 4 to move back up to where it was before.
Finally pass 4 is done in Erase mode, causing everything to disappear.

(In this example, the changes are undone in the reverse order as they were done, but that is not necessary. Changes can be made and unmade in any order.)
Note that, at all times, the FIFO, consisting of Old and New concatenated together, contains exactly the parameters of the visible buttons plus the boolean value.
The point of this is to show how a single "paint" procedure can also be used, without change, for arbitrary automatic incremental updating and erasing.
I hope it is clear that it works for arbitrary depth of sub-procedure calls, and arbitrary nesting of conditionals, including switch, while and for loops, calling pointer-based functions, etc.
If I have to explain that, then I'm open to potshots for making the explanation too complicated.

Finally, there are couple crude but short videos posted here.
** Technically, they have to read the same number of bytes they wrote last time. So, for example, they might have written a string preceded by a character count, and that's OK.

ADDED: It took me a long time to be sure this would always work.
I finally proved it.
It is based on a Sync property, roughly meaning that at any point in the program the number of bytes written on the prior pass equals the number read on the subsequent pass.
The idea behind the proof is to do it by induction on program length.
The toughest case to prove is the case of a section of program consisting of s1 followed by an IF(test) s2 ENDIF, where s1 and s2 are subsections of the program, each satisfying the Sync property.
To do it in text-only is eye-glazing, but here I've tried to diagram it:

It defines the Sync property, and shows the number of bytes written and read at each point in the code, and shows that they are equal.
The key points are that 1) the value of the test expression (0 or 1) read on the current pass must equal the value written on the prior pass, and 2) the condition of Sync(s2) is satisfied.
This satisfies the Sync property for the combined program.
Comment: I think the issue with your explanations is that you delve too deep into implementation details. 01, 10 and 11 are not really important, even the FIFO is not relevant for the main idea, it's just a handy way to store state for the elements. The functionality would be the same if each ui element had its state stored separately and then simply emit the instructions for its rendering. @Gene's "interpreter" explanation actually conveys the idea a bit clearer, IMHO; the data written into the FIFO are basically rendering instructions which will be interpreted.
Comment: @Groo: Thanks for your input. It's always a puzzle, how to present it. The real point is it's a domain-specific-language, but to make it work requires a control structure, and there are some hard-headed (which is good) readers who will think it's hooey unless I can explain it.
Answer: I read all the stuff I can find and watched the video and will take a shot at a first-principles description.
Overview
This is a DSL-based design pattern for implementing user interfaces and perhaps other state-oriented subsystems in a clean, efficient manner.  It focuses on the problem of changing the GUI configuration to match current program state, where that state includes the condition of GUI widgets themselves, e.g. the user selects tabs, radio buttons, and menu items, and widgets appear/disappear in arbitrarily complex ways.
Description
The pattern assumes:

A global collection C of objects that needs periodic updates.
A family of types for those objects, where instances have parameters.
A set of operations on C:

Add A P - Put a new object A into C with parameters P.
Modify A P - Change the parameters of object A in C to P.
Delete A - Remove object A from C.

An update of C consists of a sequence of such operations to transform C to a given target collection, say C'.
Given current collection C and target C', the goal is to find the update with minimum cost.  Each operation has unit cost.
The set of possible collections is described in a domain-specific language (DSL) that has the following commands:

Create A H - Instantiate some object A, using optional hints H, and add it to the global state. (Note no parameters here.)
If B Then T Else F - Conditionally execute command sequence T or F based on Boolean function B, which can depend on anything in the running program.

In all the examples,

The global state is a GUI screen or window.
The objects are UI widgets. Types are button, dropdown box, text field, ...
Parameters control widget appearance and behavior.
Each update consists of adding, deleting, and modifying (e.g. relocating) any number of widgets in the GUI.
The Create commands are making widgets: buttons, dropdown boxes, ...
The Boolean functions depend on the underlying program state including the condition of GUI controls themselves. So changing a control can affect the screen.

Missing links
The inventor never explicitly states it, but a key idea is that we run the DSL interpreter over the program that represents all possible target collections (screens) every time we expect any combination of the Boolean function values B has changed.  The interpreter handles the dirty work of making the collection (screen) consistent with the new B values by emitting a sequence of Add, Delete, and Modify operations.
There is a final hidden assumption: The DSL interpreter includes some algorithm that can provide the parameters for the Add and Modify operations based on the history of Creates executed so far during its current run. In the GUI context, this is the layout algorithm, and the Create hints are layout hints.
Punch line
The power of the technique lies in the way complexity is encapsulated in the DSL interpreter.  A stupid interpreter would start by Deleting all the objects (widgets) in the collection (screen), then Add a new one for each Create command as it sees them while stepping through the DSL program. Modify would never occur.
Differential execution is just a smarter strategy for the interpreter.  It amounts to keeping a serialized recording of the interpreter's last execution.  This makes sense because the recording captures what's currently on the screen. During the current run, the interpreter consults the recording to make decisions about how to bring about the target collection (widget configuration) with operations having least cost.  This boils out to never Deleting an object (widget) only to Add it again later for a cost of 2. DE will always Modify instead, which has a cost of 1.  If we happen to run the interpreter in some case where the B values have not changed, the DE algorithm will generate no operations at all: the recorded stream already represents the target.
As the interpreter executes commands, it is also setting up the recording for its next run.
An analogous algorithm
The algorithm has the same flavor as minimum edit distance (MED). However DE is a simpler problem than MED because there are no "repeated characters" in the DE serialized execution strings as there are in MED. This means we can find an optimal solution with a straightforward on-line greedy algorithm rather than dynamic programming. That's what the inventor's algorithm does.
Strengths
My take is that this is a good pattern for implementing systems with many complex forms where you want total control over placement of widgets with your own layout algorithm and/or the "if else" logic of what's visible is deeply nested.  If there are K nests of "if elses" N deep in the form logic, then there are K*2^N different layouts to get right.  Traditional form design systems (at least the ones I've used) don't support larger K, N values very well at all. You tend to end up with large numbers of similar layouts and ad hoc logic to select them that's ugly and hard to maintain. This DSL pattern seems a way to avoid all that. In systems with enough forms to offset the DSL interpreter's cost, it would even be cheaper during initial implementation. Separation of concerns is also a strength. The DSL programs abstract the content of forms while the interpreter is the layout strategy, acting on hints from the DSL. Getting the DSL and layout hint design right seems like a significant and cool problem in itself.
Questionable...
I'm not sure that avoiding Delete/Add pairs in favor of Modify is worth all the trouble in modern systems.  The inventor seems most proud of this optimization, but the more important idea is a concise DSL with conditionals to represent forms, with layout complexity isolated in the DSL interpreter.
Recap
The inventor's has so far has focused on deep details of how the interpreter makes its decisions. This is confusing because it's directed at trees while the forest is of greater interest. This is a description of the forest.
Comment: @MikeDunlavey Thanks Mike.  Hints seemed to make sense for complex forms.  Rather than just say "Button A" in the DSL, say "Button in column below Button B" or something similar. Else you lose the nice separation of concerns. Hints are similar to current traditional layout managers like Java Swing's. On the interpreter, you are describing forms in the DSL, and some chunk of code is processing the DSL to do the Adds, Deletes, Modifies. This chunk of code is by definition an interpreter. It's not new: Windows forms sinve v1.0 have the same for dialog resources, but their DSL has no conditionals!
Comment: Thanks for your attention and good description. Indeed, I think its usefulness comes from it being a DSL, and that's a part of software engineering that needs a lot more emphasis. I would only add 1) that the word "interpreter" is a good word but might be misleading, because the code is compiled - interpreters usually have an order of magnitude performance penalty, and 2) it doesn't claim to find minimum edit distance, merely reasonable.
Comment: ... also, I'm not sure what you're saying about layout hints. Each control has position and size, and I just compute those on the fly, either as arguments to the primitive procedures, or as "global" variables with side effects. (In computing those on the fly, the erase mode rule must be followed.) BTW, another issue is data binding, which can also be done on the fly, and doesn't require any additional data structure.
Comment: Right, the resource-compiler (RC) language was a good DSL - the problem was all the cruft you had to write around it, killing its value as a DSL, like data moving and event handlers, not to mention having to name everything. What I'm trying to do is embed the DSL in the main language and make it as flexible as the main language.
Comment: If you're interested, there's a small implementation in C++ with MFC [*here*](http://sourceforge.net/projects/dyndlgdemo/). (I'm afraid I've pre-dated the Java bandwagon, though I've been through VB and C# the last several years.) Also, if you're into formal proofs, there's a dry and boring correctness proof [*at the bottom of my Wikipedia page*](http://en.wikipedia.org/wiki/User:MikeDunlavey).
Comment: Adding modify operations is definitely worth it as you can implement them as slow transitions. The whole process reminds me of d3's exit/update/enter, except d3 implements "for" loops out of the box (as array data joins) while Mike Dunlavey's algo generalizez to all control structures.
Comment: @csiz: I finally got around to implementing this in javascript, and will soon put it in github. So far, the two files are really small. I'm a real newbie to js, css, html5, etc., so the web page it makes is painfully simple, but it does all the dynamic update and event handling.
Comment: @MikeDunlavey I would like to have a look when you put it on github :)
Comment: @csiz: It's in GitHub, under my name, repository DiffExecInJS. You just open the temp.htm file. It loads the .js file and runs the contents to make 2 buttons. Then you can increase or decrease the number of buttons, and if you show the console (F12) it will show if you click a middle button. It needs a lot more pizzaz, but it's got the basic works.

What is differential execution?


prove that in a complete oriented graph there is triangle

Question: prove that in a full complete oriented graph there is a triangle .
I tried to use something like red and blue edges. But I can't figure out how to choose directions of edges and which colour is every edge.
Comment: Are you working with [tournaments](https://en.wikipedia.org/wiki/Tournament_(graph_theory)#:~:text=A%20tournament%20is%20a%20directed,in%20an%20undirected%20complete%20graph.)? Also, what do you mean by triangle? Do you mean a directed 3-cycle?
Comment: This is only true if you know there is at least one cycle in the graph.
Comment: What about the complete directed graph with one vertex and no edges? Surely that graph doesn't contain a "triangle".
Comment: when does complete oriented graph have a cycle? And  problem says that there aren't any vertexes without edges. Also I don't know what problem means by triangle but if it was not directed 3-cycle,  the problem would not make sense so I think it is.
Answer: If by a "triangle" you mean a (directed) $3-$cycle, then this is false. Line the $n$ vertices up from left to right and make every edge a forward (left to right) edge. This tournament clearly does not have a $3-$cycle.
EDIT : As @Brandon pointed out in the comments, the statement is true if the graph has at least one cycle.
To see this, suppose we're given the cycle $u_k\rightarrow u_{k+1}\rightarrow u_{k+2}\cdots \rightarrow u_{k+m}\rightarrow u_{k}$, arrange the vertices of the cycle from left to right (the last edge in the sequence is a back edge).
If we have a forward edge $u_{k+1}\rightarrow u_{k+m}$ then we are done, since we then have the 3-cycle $u_k\rightarrow u_{k+1}\rightarrow u_{k+m}\rightarrow u_k$.
Otherwise, we have a smaller cycle $u_{k+1}\rightarrow u_{k+2}\cdots \rightarrow u_{k+m}\rightarrow u_{k+1}$
Continuing this reasoning, one can also see that unless all the edges from $u_{k+m}$ to the vertices $u_{k+2}, u_{k+3}\cdots$ in the cycle are back edges, you'll eventually find a 3-cycle. But if all of them are back edges, then we have the following $3-$cycle --
$u_{k+m-2}\rightarrow u_{k+m-1}\rightarrow u_{k+m}\rightarrow u_{k+m-2}$.
So we're done.
Comment: if the graph is full , can we say that there's a cycle passing to all vertexes?
Comment: I know but in my problem graph is full
Comment: @DeltaAccount What do you mean by full?
Answer: I will proove it using induction.
Base: For graph of size $3$ it is true.
Hypothesis: Assume for size $k$ it is true.
Induction: In graph of size $k+1$ consider any three consicutive vertices of cycle. Let $a, b, c$ such vertices with orientation $(a-b-c)$.
Case 1: If edge $ac$ has orientation $(a-c)$ it creates cycle with $k-1$ vertices and according to hypothesis this cycle contains a triangle.
Note: This cycle does not contain $b$. i.e. $cycle-b$
Case 2: If edge ac has orientation $(c-a)$ then $abc$ creates triangle.
Answer: An oriented complete graph (a.k.a. tournament) does not necessarily contain a directed $3$-cycle, but the counterexamples are very special.
Suppose your oriented complete graph contains no directed $3$-cycle. For vertices $a$ and $b$, define $a\lt b$ to mean that there is an arc from $a$ to $b$. Since the graph is complete and has no directed $3$-cycles, whenever we have $a\lt b$ and $b\lt c$ we must also have $a\lt c$. That is, $\lt$ is a transitive relation, and therefore it is a linear order relation, the other required properties being obvious.
So the only oriented complete graphs without directed $3$-cycles are linear orders (a.k.a. transitive tournaments), which have no directed cycles at all.


$\mathbb{Q},\mathbb{R}$ and $\mathbb{C}$-vector space isomorphism from $\mathbb{Z}$-module isomorphism.

Question: Let $A,B$ be $\mathbb{C}$-vector space. We can view them as a $\mathbb{Z}$-module. Suppose that there is a $\mathbb{Z}$-module isomorphism $\phi$ between $A$ and $B$. Then can we have a natural $\mathbb{Q}$(or even $\mathbb{R}$, $\mathbb{C}$)-vector space isomorphism between $A$ and $B$ from $\phi$?
I think at least we can have $\mathbb{Q}$-vector space isomorphism.
For example, Let $a\in A$ and denote $\frac{1}{n}a=\alpha\in A$ for some natural number $n$. Let $\phi$ be a $\mathbb{Z}$-module isomorphism from $A$ to $B$. Then, we have
$\phi(a)=\phi(n\alpha)=n\phi(\alpha)=n\phi(\frac{1}{n}a)$.
Thus, $\phi(\frac{1}{n}a)$ has to be $\frac{1}{n}\phi(a)$. Because $\mathbb{Q}$ is the field of fraction of $\mathbb{Z}$, we may have $\phi(\frac{m}{n}a)=\frac{m}{n}\phi(a)$ for all $a\in A$ and $\frac{m}{n}\in\mathbb{Q}$.
Am I right?
Now, I am struggling to extend to $\mathbb{R}$ or $\mathbb{C}$ vector space isomorphism.
Comment: I think your dream is unrealistic (the parts about going beyond $\Bbb{Q}$). After all, $\Bbb{R}$ and $\Bbb{R}^2$ are isomorphic as vector spaces over $\Bbb{Q}$. Both have continuum dimension. The question is interesting (+1), but I also think it has been covered earlier on the site.
Comment: No, use a Hamel basis to construct lots of automorphisms of $\mathbb R / \mathbb Q$.
Comment: If you add continuity for $\phi$ then you're getting somewhere. (for $\mathbb R$-linearity, anyway)
Comment: If you consider $A$ and $B$ as complex manifolds, assuming they are finite-dimensional, then a $\Bbb Z$-linear map is $\Bbb C$-linear iff it is holomorphic.
Comment: For $\Bbb R$-linearity, measurable is enough.
Answer: Your argument that $\mathbb{Z}$-linear implies $\mathbb{Q}$-linear is correct but it's not possible to go beyond this. In fact assuming the axiom of choice $\mathbb{C}$ and $\mathbb{C}^2$, for example, are isomorphic as $\mathbb{Q}$-vector spaces (since they both have the same dimension, namely $|\mathbb{R}|$).
On the other hand, it's consistent with ZF that every homomorphism between Polish groups is automatically continuous, and in particular that every homomorphism between finite-dimensional real or complex vector spaces is automatically continuous. If this is true then any $\mathbb{Z}$-linear isomorphism between finite-dimensional real or complex vector spaces is automatically $\mathbb{R}$-linear, so in the real case we're done, and in the complex case they have the same real dimension and hence the same complex dimension, so there is some other $\mathbb{C}$-linear isomorphism between them.


MS Word - Hiding a Row in a Table depending on Content Control value

Question: I have a very long word file, containing several tables.
Each table contains a list of items that may or may not be applicable to the user.
I am trying to find a way of hiding/masking rows that have not been filled by the user.
To do so, I was thinking of writing a sub that go through the entire document lookinf for content controls, then checks if the contentcontrol.text="NULL" and then deletes the table row (or hides it by setting the row height to 0).
Any ideas?
Below my partial attempt
Sub HideRows()
Dim d As Document
Set d = ActiveDocument
Dim cc As ContentControl

For Each cc In d.ContentControls
    If cc.Range.Text = "NULL" Then

        'Delete the table row where this content control is located

    End If
Next
End Sub

Answer: Assuming that:

each ContentControl covers the whole single row
you do not use nested tables in document

you can place this code inside your if statement:
CC.Range.Tables(1).Rows(CC.Range.Information(wdEndOfRangeRowNumber)).Delete


Comparison of measurement methods

Question: I have three sets of measurements (A, B, and C) of the same thing. One of them is the gold standard (say A). I want to determine if B and C overestimate or underestimate the true measurement (which is A) and by how much. Can I simply use the sum squared error between A and B, and A and C? If not, which other statistical tool can I use to determine that?
The measurement is a distance in centimeters and there are 32 subjects in the study.
Comment: The "gold standard" is more accurate then other measurement methods but it is not exact.
Comment: But I want to presume it is. It's the best possible measurement, sure, but it is also a costly one.
Comment: Assuming that it is perfect oversimplifies the situation.
Comment: Looks like a job for a regular linear model.
Answer: Let's start by slightly simplifying the problem to only consider the comparison of A (the "gold standard") versus B (the "experimental" measurement).
There are two questions here. The first is whether measurement B systematically over/underestimates the true measurement. For this, you can use a Wilcoxon signed-rank test. This would be a nonparametric approach, since you are not assuming anything about the distribution of the errors (where $error=A-B$). However, if you assume that the errors are normally distributed (which may or may not be a reasonable assumption; more info from you on what you're measuring and how you're measuring it would be needed to assess the reasonableness of this assumption), you could use a paired-sample t-test.
This being said, with a sample size of 32, it is unlikely that you will have the statistical power necessary to be able to detect a difference even if one exists (unless the difference is very large). Are you able to obtain more measurements?
For the second question - if there is a significant difference between the tests, how big is this difference? In theory, you could calculate a confidence interval (e.g. via bootstrapping) for the error in your measurement ($A-B$), but again, your sample size is very small and the confidence interval will be very wide (and probably not useful).
If you still want to know the details of how this would be done, let me know and I can add to this answer.
Comment: Actually, there are two groups of individuals. A control and an experiment group with 32 and 34 individuals respectively. Maybe, to check if B systematically under/overestimates A, I can use all 66 individuals as one group. Gathering more data than that isn't viable atm. --- I think it's safe to assume the error is normally distributed (A is measured on a tomographic image and B is measured directly on the subject with a specific tool, like a special ruler).
Comment: Let's say A's avg is 20 +- 0.87 and B's avg is 19.3 +- 0.77 (95% CI). Pearson's correlation is 0.89 (p=2.9e-22). And that paired t-test gives p-value = 0.00086 and t-value = -3.5. Which to me seems to indicate that B underestimates A. (They are correlated and there is a significant difference). I don't know how to get to the "by how much it underestimates" given the t-value, tho (from what I searched, the t-value is measured in stddev units). Am I completely off track here? Also, I'm not sure how to do the bootstrapping you mentioned.
Comment: I'm not sure how you're calculating these CIs and p-values, but if you post your data in a googledoc (and link to it from this post), I'd be happy to demonstrate both the Wilcoxon test and the paired t-test.

Comparison of measurement methods


Using recycled hardware at home?

Question: My employer is currently in the process of "greening" and upgrading our data center by replacing old standalone servers with Virtual Machines running on some new, very-powerful hardware, the details of which aren't important.
I was offered a dual processor (933Mhz) IBM eServer with hardware RAID (2 18Gb and 4 72Gb 10,000RPM SCSI drives) and 2.5 Gb of RAM. I took it, but how do I get started?
The drives are blank and the RAID is not configured. I won a copy of Win 2k3 at a Microsoft event last year, so an OS isn't a problem.
I plan on using the box for version control (probably SVN), and ASP.NET/MS SQL development on personal projects.
Answer: I'm going to guess you're a programmer, and so I'm going to say that this question is the sysadmin equivalent to "I want to learn a new language, where do I start?"  So, I offer the same advice - pick a project and implement it.  It sounds like you already have (that is, you have a goal for the purpose of the server).  So, instead of asking a broad question, break it into steps, try to accomplish, and ask questions on that specific implementation problem.
So, instead of this broad question, why not ask one that's just "I have an IBM eServer with hardware RAID (2 18Gb and 4 72Gb 10,000RPM SCSI drives) and 2.5 Gb of RAM. I intend to put Win 2k3 on it.  The drives are blank and the RAID is not configured.  Does raid initialization happen during OS install, or do I have to prepare the RAID first?  What tools do I need to prepare the RAID if Windows doesn't handle it for me?"
Comment: I suppose that's actually a pretty fair analogy! ;-)
Answer: The best thing to do is experiment, make this a learning experience. I have an old server at home that I use for this sort of thing and its always being formatted and upgraded (and broken), to aid my learning. Find out how to configure the RAID, find details about it on the net, find out how to get into the management interface, play about with configurations. When your done with that, get an OS on it, learn how to setup windows server, then look at software.
I feel you get the most enjoyment and satisfaction out of these sort of things when your learning and achieving things, especially things you had no idea how to do a day ago!
Answer: I just got a similar hand-me-down machine (sans the extra processor and most of the memory you got...).  I pulled the RAID configuration tool ISO's off of IBM's web site to create my volumes and then went from there.  There are different ISO's based on what model RAID controller you have.  Burn it to CD and boot from the CD.  It'll take you right into the configuration where you can add drives to create your volumes, etc.  When that's done you're good to install the OS.  That box should be great for what you're planning.  If it's anything like mine, though, it sounds like a jet idling on the tarmac.  Should be getting my first electric bill in the next few days after setting it up.  Can't wait for that...
Answer: A Linux OS, being free as in open to tinkering, might be easier to set up and maintain than that Windows Server CD that was free as in beer.
From within Linux you can then install the windows server CD into a virtual computer running on VMWare or Virtual Box... and the windows server will see standardized hardware instead of the true hardware.
But it all depends on what you want to do with it.

Using recycled hardware at home?