text:
Q: Tippmatic auto shut-off switch - how to use it? Some products in my company are now required to use an auto shut-off switch to be compliant with new regulations in European space (European Eco-Design Directive ErP).
I got word that the device being integrated into the current products will be the TIPPMATIC iF by Johnson Motor.
Can anyone please explain how these devices are supposed to operate?
The only datasheet I found for this is more of the mechanical kind, and has no guidelines whatsoever towards its use case.
The datasheet has a graph that displays a \$V_{coil}\$ level during a certain \$T_{(on)}\$ and then displays 0V during a \$T_{(off)}\$. It also provides the following values:

*

*\$I_{coil\,peak}: 1.0 +0.2/-0.3A\$

*\$I_{coil\,steady}: 20mA \,DC\$

*\$R_{coil}: 20 \pm1.5\Omega\$

*\$T_{(on)}: 3 \times 10^{-3}s\$ (coil command pulse length)

*\$T_{(off)}: 2s\$ mininum (dead time for next disconnection)

*\$V_{coil}: 20VDC\$

This is the representation it provides:

simulate this circuit – Schematic created using CircuitLab
From what I could make of it, I should  connect the mains' line between pins 1/1. and neutral to N. Then, should I pulse 20VDC for at least 3ms, and the switch should be "armed" (enabling operation on the load). Then I can't "arm" it again for at least 2s (even if it triggers meanwhile, disconnecting from the load). Can someone attest if this is correct?
Simply put, it's almost as the switch requires a "keep-alive" signal of sorts, that each 2s, requires a 20VDC for 3ms in order to remain closed, right?
EDIT: Still can't make much sense of what I read here - but I know the problem is me above anything else! :) Anyway, the manufacturer's FAE, told me this:

you have to connect the switch in this way.
N: neutral

*

*main voltage

  1 to the load (heater, etc...)
On the drawing the switch is shown in OFF position
  the puls 5vdc should be done during 1-2ms
  You have to wait at least 2s to do again the operation otherwise a shorter time will heat >up the coil.

This validates @SpehroPefhany suggestion (+1'd), although, I'm still missing the whole auto shut-off feature they claim. The way I figure it, if we enable (turn on, close) the switch manually, it should operate as if no switch was there. Then, should we want to disable (turn off, open) the switch we have to pulse it at 20V for 3ms, is that it? If so, at what point does it shut-off automatically?

A: So I finally was able to validate @SpehroPefhany's opinion.
When connected as indicated by the manufacturer, the switch operates correctly.
The logic behind the component is the following:

*

*The switch is normally off. Turning it on is a manual process.

*The only scenario in which the switch turns off automatically, is when the mains' power fails. This way, when it comes back up, the appliance using the switch isn't automatically turned on.

*To turn it off, it's only necessary to pulse a certain \$V_{coil}\$ (varies with version of the component) for at most \$T_{(on)}\$. This will make the coil release (open) the switch.

*In case the switch is turned on manually after pulsing the coil (powering on the circuit/appliance), the coil can only be pulsed again 2 seconds after this operation - otherwise it heats up, damaging the component.

As for connection of the switch, the instructions I added in the question edit are 100% correct and straightforward.
Hope this helps someone else who might have a similar problem.

A: My interpretation (which could be completely wrong) is that you pulse the switch coil with ~1A at 20V for 3msec to turn it off.
It can only be switched on manually but it can be remotely switched off. If the mains between 1. and N disappears it "drops out" (but maybe the switch rocker does not move?).
You need to wait 2s after switching it "off" before you command it "off" again, or the coil may overheat.
But that guess and $3 will about get you a cup of coffee.


text:
Q: how make a one2one relation without duplicated? openerp 7 So ...... suppose I have class "person" and "color". How to make it so if one
color is assigned to a person ... it can not be assigned to other person
class person(osv.Model):
    _name = 'person'

    _columns = {
            'name': fields.char('Person', size=50, help="Persona"),
            'color_p : fields.one2one('colors','Color'),
                }
person()

class colors(osv.Model):
    _name = 'colors'

    _columns = {
            'name': fields.char('Color', size=50, help="Color"),
                }
colors()

A: For OpenERP 7 you can try to use _inherits (see for example http://dirtyhandsphp.blogspot.in/2014/10/openerp-one2one-relational-field-example.html).
However, I've needed to set a one2one relationship in the past and this solution wasn't as succesful as I had expected. May be you think different ;)

A: If you have 2 models and you want to create a one2one relationship:
class ServiceLine(models.Model):
    _name = "service.line"

    title = fields.Char(string='Title')
    service_cost = fields.Float(string='Cost', track_visibility='onchange')

class ServiceExample(models.Model):
    _name = "service.example"

    _description = "My Awesome Singular Service Example"

    _inherits = {
        'service.line': 'service_line_id',
    }

    service_line_id = fields.Many2one(
        'service.line', string='Service Line ID', required=True, ondelete='cascade', unique=True, auto_join=True
    )

    service_example_details = fields.Char(string='Details', track_visibility='onchange')

This will make the magic! Now you can use any field of your one2one relationship in your service_example model:
service_example_record = self.env['service.example'].create({
  'title': 'My Awesome Service',
  'service_cost': 50.5,
  'service_example_details': 'My Awesome Details Service...'
})

redpajama_set_name: RedPajamaStackExchange


text:
Q: Select Columns of a View I'm attempting to select the column names of a view in a similar way as selecting from information_schema.columns.
I can't seem to find a way to do this. Has anyone else done this before or know if it is even possible?

A: information_schema.columns.Table_name (at least under Sql Server 2000) includes views, so just use
SELECT * FROM information_schema.columns WHERE table_name = 'VIEW_NAME'

A: I found this way working for views (SQL 2017). I was not able to get data from information_schema.columns and sys.columns:
    SELECT * FROM sys.all_columns WHERE object_id = OBJECT_ID('<view_name>')

A: INFORMATION_SCHEMA views holds metadata about objects within database. INFORMATION_SCHEMA.COLUMNS uses underlying sys tables to  retrive the metadata ( check sp_helptext   'master.Information_schema.columns' ). You can use this simpler query to select column names used in any view.
SELECT col.name
FROM <db_name>.sys.columns col, <db_name>.sys.views vew
WHERE col.object_id = vew.object_id
AND vew.name = '<view_name>'

A: Try this:
SELECT *
FROM sys.views

This gives you the views as such - if you need the columns, use this:
SELECT *
FROM sys.columns
WHERE object_id = OBJECT_ID('dbo.YourViewNameHere')

Not sure how you can do it using the INFORMATION_SCHEMA - I never use that, since it feels rather "clunky" and unintuitive, compared to the sys schema catalog views.
See the MSDN docs on the Catalog Views for all the details of all the views available, and what information they might contain.

A: SELECT distinct VIEW_NAME
  ,TABLE_SCHEMA
  ,TABLE_NAME
  ,COLUMN_NAME
FROM   INFORMATION_SCHEMA.VIEW_COLUMN_USAGE
--WHERE  TABLE_SCHEMA = 'Person'
ORDER BY
   VIEW_NAME
  ,TABLE_SCHEMA
  ,TABLE_NAME
  ,COLUMN_NAME

A: select schema_name(v.schema_id) as schema_name,
   object_name(c.object_id) as view_name,
   c.column_id,
   c.name as column_name,
   type_name(user_type_id) as data_type,
   c.max_length,
   c.precision
from sys.columns c
join sys.views v
 on v.object_id = c.object_id
order by schema_name,
     view_name,
     column_id;

A: I needed to create something similar, so I expounded on what Ghost suggested.  I needed to create a top 1000 view for every view in a database order by the first ordinal column descending.
SELECT CONCAT (
              'CREATE VIEW dbo.temp_',
              v.name,
              ' AS select top (1000) * from ',
              OBJECT_SCHEMA_NAME (v.object_id),
              '.',
              v.name,
              ' ORDER BY [',
              c.COLUMN_NAME,
              '] DESC;'
          ) AS viewName
FROM sys.views AS v
    LEFT OUTER JOIN INFORMATION_SCHEMA.COLUMNS AS c
             ON v.name = c.TABLE_NAME
WHERE c.ORDINAL_POSITION = 1;


text:
Q: How to create a list of numbers which are multiples of 3 and fall between a specific range? I am new to R and would appreciate any help on this 2 step task.
I need to write the R codes to create a list of numbers which are mutiples of 3  between 1 and 40.
The second part would need the codes to randomly select 6 numbers from the list above.

A: To generate number multiple of 3 try seq with by=3. And then use sample to pick 6 random samples out of that sequence. I have used set.seed(1) to get fixed output:
set.seed(1)
sample(seq(3,40,by=3), 6)
#[1] 12 15 21 30  6 24

A: Here is a solution in a step-by-step manner:
# 1. List of numbers between 1 and 40
list_numbers <- seq(1:40)

# 2. Filter
list_filter <- sapply(list_numbers, function(x) {x %% 3 == 0})

# 3. List of numbers multiple 3
list_numbers_multiple_3 <- list_numbers[list_filter]

# 4. Select 6 random numbers
sample(list_numbers_multiple_3, 6)


text:
Q: Installing multiple versions of Qt library I have installed QtSDK in windows and its Qt library version is 4.7.0.
Now i want to install Qt library version 4.8.2 for mingw and VS2008. How can i do this? How to introduce multiple versions to QtCreator?
Note : I have downloaded libraries from http://qt.nokia.com/downloads

A: Sure you can. Just extract the libraries in a different location and set Qt Creator to use those as well. You can find how here: http://doc.qt.io/qtcreator/creator-project-qmake.html.
You can then choose which configuration to use to compile in the properties of each project.


text:
Q: Why would the example test in Laravel fail for redirect? Please explain why Laravel 4's example test fails for me.
My "/" route redirects to "login" in my routes.php file.
(Oh, I've RTFMed and scoured several sites, blogs, and tuts.)
-sh-3.2$ phpunit
PHPUnit 4.0.7 by Sebastian Bergmann.

Configuration read from /home/dev/phpunit.xml

The Xdebug extension is not loaded. No code coverage will be generated.

F

Time: 83 ms, Memory: 13.50Mb

There was 1 failure:

1) ExampleTest::testBasicExample
Failed asserting that false is true.

/home/dev/app/tests/ExampleTest.php:14

FAILURES!
Tests: 1, Assertions: 1, Failures: 1.
-sh-3.2$

Here is the code from ExampleTest.php
<?php

class ExampleTest extends TestCase {

    /**
     * A basic functional test example.
     *
     * @return void
     */
    public function testBasicExample()
    {
        $crawler = $this->client->request('GET', '/');

        $this->assertTrue($this->client->getResponse()->isOk());
    }

}

A: The test is failing because you're getting 302 status code instead of 200 (since there is a redirection that wasn't in the default routes.php file).
If you want to test redirection, then Laravel provides several methods just for that.

*

*If you're using named routes:
$this->assertRedirectedToRoute('login');

*If not:
$this->assertRedirectedTo('login');

*For testing response status codes:
$this->assertResponseStatus(302);


text:
Q: How to understand this collision detection code from a book and point me to the right math? Please bear with me. I appreciate any pointers / patience and help in understanding the code pasted below.
All the lines marked with the '// ??' comment is where I don't have a clue what's happening.
I picked up the Building an HTML5 Game book (http://buildanhtml5game.com/) in the hopes of learning how to write a game, more especially in HTML5 and JavaScript.
To my surprise, the book does not really explain various background information or assumes the readers already know their way around.
I am not a mathematics expert and that's one big reason I am stuck with the code below. The book barely touches the surface and the explanation is in a line or two (leaving me more confused).
Please, I may ask, do provide me with links so I study the mathematics behind the formulas below and write some English explanation as well so I understand.
I don't want to skip the mathematics parts in this book because it defeats the purpose.
Much appreciated.
    var BubbleShoot = window.BubbleShoot || {};
    BubbleShoot.CollisionDetector = (function($){
        var CollisionDetector = {
            findIntersection : function(curBubble,board,angle) {
                // 'angle' is the angle between the 'curBubble' starting bubble
                // at the center of the screen and the mouse click's direction aimed at the bubbles
                // above.
                // I understand how that angle is computed in previous code snippets.

                // 'board' contains an array of bubble objects that are static and laid up on the board
                // waiting to be shot at with 'curbubble' and 'angle'.

                // Get the bubble rows container
                var rows = board.getRows();
                var collision = null;

                // Get the bubble's that will be shot from the center coordinates
                var pos = curBubble.getSprite().position();

                // The start coordinates are the bubble's center
                var start = {
                    left : pos.left + BubbleShoot.ui.BUBBLE_DIMS/2,
                    top : pos.top + BubbleShoot.ui.BUBBLE_DIMS/2
                };

                // ?? (A) what does this give us (mathematically speaking, what are those variables called)
                var dx = Math.sin(angle);
                var dy = -Math.cos(angle);

                for(var i=0;i<rows.length;i++){
                    // for each row
                    var row = rows[i];
                    for(var j=0;j<row.length;j++){
                        // Get bubble at i,j
                        var bubble = row[j];
                        if(bubble){
                            // Get bubble's coordinates. we want to see if the starting bubble
                            // will collidate with this static bubble if the starting bubble was fired
                            // with an angle 'angle'
                            var coords = bubble.getCoords();

                            // ?? (B) that's not the distance between the two points!
                            // ?? what do you call this mathematically?
                            var distToBubble = {
                                x : start.left - coords.left,
                                y : start.top - coords.top
                            };

                            // ?? (C) what is 't'? what does it give? can you please give me reference
                            // ?? so I study the proper math behind its purpose?
                            var t = dx * distToBubble.x + dy * distToBubble.y;

                            // ?? (D) why '-t' * dx and what does this give us?
                            var ex = -t * dx + start.left;
                            // ?? (E) same for 'ey'
                            var ey = -t * dy + start.top;

                            // distance between the two points (ex,ey) and (coords.left,coords.top)
                            // ?? (F) I am not sure what are 'ex' and 'ey'
                            var distEC = Math.sqrt((ex - coords.left) * (ex - coords.left) +
                            (ey - coords.top) * (ey - coords.top));

                            if(distEC<BubbleShoot.ui.BUBBLE_DIMS * .75){
                                // ?? (G) dt is what?
                                var dt = Math.sqrt(BubbleShoot.ui.BUBBLE_DIMS * BubbleShoot.
                                    ui.BUBBLE_DIMS - distEC * distEC);

                                // ?? (H) what's this?
                                var offset1 = {
                                x : (t - dt) * dx,
                                    y : -(t - dt) * dy
                            };
                            // ?? (I) and this?!
                            var offset2 = {
                                x : (t + dt) * dx,
                                y : -(t + dt) * dy
                            };

                            // ?? (J) distance between something
                            var distToCollision1 = Math.sqrt(offset1.x * offset1.x +
                            offset1.y * offset1.y);
                            var distToCollision2 = Math.sqrt(offset2.x * offset2.x +
                            offset2.y * offset2.y);

                            if(distToCollision1 < distToCollision2){
                                var distToCollision = distToCollision1;
                                var dest = {
                                    x : offset1.x + start.left,
                                    y : offset1.y + start.top
                                };
                            }else{
                                var distToCollision = distToCollision2;
                                var dest = {
                                    x : -offset2.x + start.left,
                                    y : offset2.y + start.top
                                };
                            }
                            if(!collision || collision.distToCollision>distToCollision){
                                collision = {
                                    bubble : bubble,
                                    distToCollision : distToCollision,
                                    coords : dest
                                };
                            };
                        };
                    };
                };
            };
        return collision;
    }
    };
    return CollisionDetector;
    })(jQuery);

You can play the game here just to see how it looks: http://buildanhtml5game.com/?page_id=20


text:
Q: What is the purpose of the Millennium Falcon's "mandibles"? This answer points out this page

from Millennium Falcon Haynes Manual which refers to the two projections on the bows of all YT-1300 Correlian Freighters as mandibles.
What is their purpose or function?

A: According to the book "Incredible Cross-Sections of Star Wars: The Ultimate Guide to Star Wars Vehicles and Spacecraft", the mandibles hold various sensors and an anti-concussion field generator. Three is also the freight barge clamp so the YT-1300 can act like a barge or tugboat and push around large cargo. Also on the port mandible there is the shield generator and projector. On the inner side of the mandibles there is a freight loading arm. Click on the image to see a larger version.

Another purpose is for moving freight around, where the mandibles attach to cargo and push them around, as shown here:

A: The Falcon, like other ships in its class can be used as a cargo pusher. The (canon) Star Wars: Rebel Files has an image of a newer YT-model freighter moving what appears to be a smaller ship.


text:
Q: Create a new google cloud instance using shut-down script I am trying to use a shutdown-script to create a new instance from within the the instance that is shutting down now.
The script has three tasks,
1. creates an empty file
2. get the name of the new instance to be created
3. generates a name for the next new instance to be spawned
4. creates a new instance from within this instance with the name generated.
Here is the script:
#!/bin/bash

touch /home/ubuntu/newfile.txt

new_instance_name=$(curl http://metadata.google.internal/computeMetadata/v1/instance/attributes/next_instance_name -H "Metadata-Flavor: Google")

next_instance_name="instance-"$(printf "%04d" $((${new_instance_name: -4}+1)))

gcloud beta compute --project=xxxxxxxxx instances create $new_instance_name --zone=us-central1-c --machine-type=f1-micro --subnet=default --network-tier=PREMIUM --metadata=next_instance_name=$next_instance_name --maintenance-policy=MIGRATE --service-account=XXXXXXXX-compute@developer.gserviceaccount.com --scopes=https://www.googleapis.com/auth/cloud-platform --image=image-1 --image-project=xxxxxxxx --boot-disk-size=10GB --boot-disk-type=pd-standard --boot-disk-device-name=$new_instance_name

This script is made executable using chmod +xand the file-name of the script is /home/ubuntu/shtudown_script.sh.he metadata shutdown-script for this instance is also /home/ubuntu/shtudown_script.sh.
All parts of the script runs fine when I run it manually from within the instance, so a new file is created and also a new instance is created when the current instance shuts-down.
But when it is invoked from API when I stop the instance, it only creates the file I create using touch command, but no new instance is created as before.
Am I doing something wrong here?

A: So I was able to reproduce the behavior you described. I ran a bash script similar to the one you have provided as a shutdown script, and it would only create the empty file called "newfile.txt".
I then decided to append the output of the gcloud command to see what was happening. I had to tweak the bash script to fit my project. Here is the bash script I ran to copy the output to a file:
#!/bin/bash

touch /home/ubuntu/newfile.txt

gcloud beta compute --project=xxx instances create instance-6 --zone=us-central1-c --machine-type=f1-micro --subnet=default --maintenance-policy=MIGRATE --service-account=xxxx-compute@developer.gserviceaccount.com --scopes=https://www.googleapis.com/auth/cloud-platform --boot-disk-size=10GB --boot-disk-type=pd-standard --boot-disk-device-name=instance-6 > /var/output.txt 2>&1

The output I received was the following:
ERROR: (gcloud.beta.compute.instances.create) Could not fetch resource: - Insufficient Permission
This means that my default service account did not have the appropriate scopes to create the VM instance.
I then stopped my VM instance and edited the scopes to give the service account full access as described here. Once I changed the scopes, I started the VM instance back up and then stopped it again. At this point, it successfully created the VM instance called "instance-6". I would not suggest giving the default service full access. I would suggest specifying which scopes it should have, but make sure that it has full access to Compute Engine if you want the shutdown script to work.

A: If the shutdown script works when you stop the VM instance using the command:
$sudo shutdown -h now
And does not work when stopping the VM instance from the Cloud Console by pressing the "Stop" button, then I suspect this behavior is to be expected.
A shutdown script has a limited period of time to run when you stop a VM instance; however, this limit does not apply if you request the shutdown using the "sudo shutdown" command. You can read more about this behavior here.
If you would like to know more about the shutdown period, you can read about it here.

A: I already had given my instance proper scope by giving the service account full access (which is a bad practice).
But the actual problem was solved when I reinstalled google-cloud-sdk using
sudo apt-get install google-cloud-sdk

When I was running those scripts before reinstalling gcloud by sshing into the instance it was using the gcloud command from preinstalled directory /snap/bin/gcloud. But when it runs from the startup or shutdown script, for some reason it can not get an access to the preinstalled /snap/bin/ directory, and when I reinstall google cloud sdk using apt-get the gcloud command was being accessed from /usr/bin/gcloud which I think is accessible by the startup or shutdown script.


text:
Q: How to deny WCF entities to show in some endpoints i have a wcf service with 3 endpoints and i have within the service entities decorated with DataContract and DataMember.
my question is, is it possible to deny the datacontractserializer to do his job in some endpoints or i should create a new wcf service?
thanks.

A: This has been asked before at Exclude property on WCF DataContract
The answer: no, it violates the contract defined on the class decorated with the DataContract and DataMember attributes.


text:
Q: How to work with multidimensional-arrays in Javascript? I'm trying to make a code that works like this:

*

*Get number of teams (y) and number of players(x).

*Get x names and x ranks.

*Create balance teams based on the player ranks.
Each team should have x/y players.

*Print each team separately.

I can't see where is my problem and why my code doesn't work. Hope you guys could help.
This is my code:

function step1() {
 var teams = document.getElementById("teams").value;
 var players = document.getElementById("players").value;
 var main = document.getElementById("main");
 main.innerHTML="";
 for(var i=1;i<=players;i++){
  main.innerHTML += "<input class='names' placeholder='Player "+i+"' type='text' style='width:100px'/>   "+
  "<input class='ranks' placeholder='Rank' type='text' style='width:40px'/>
";
 }
 main.innerHTML+="
<button onclick='buildTeams("+players+","+teams+")'>Build</button>";
}
function buildTeams(playersInt,teamsInt) {
 var error=0;
 var names = new Array(playersInt);
 var ranks = new Array(playersInt);
 var nameInp = document.getElementsByClassName("names");
 var rankInp = document.getElementsByClassName("ranks");
 for(var i=0;i<playersInt;i++) {
  names[i] = nameInp[i].value;
 }
 for(var i=0;i<playersInt;i++) {
  ranks[i] = rankInp[i].value;
 }
 var teams = new Array(teamsInt);
 for(var i=0;i<teamsInt;i++) {
  teams[i]=new Array(playersInt/teamsInt);
 }
 for(var i=0;i<(playersInt/teamsInt);i++) {
  for(var j=0;j<teamsInt;j++) {
   teams[i][j]=names[checkMvp(ranks)];
   ranks[checkMvp(ranks)]=-1;
  }
 }
 for(var i=0;i<teamsInt;i++) {
  alert(teams[i]);
 }

}
function checkMvp(ranks) {
 var high= ranks[0];
 var bpi=0;
 for(var i=1;i<ranks.length;i++) {
  if(ranks[i]>high) {
   bpi=i;
  }
 }
 return bpi;
}

Power Balance

Number of teams:
<input type="text" id="teams" style="width:30px"/>

Number of players:
<input type="text" id="players" style="width:30px"/>

<input type="button" onclick="step1()" value="Next"/>

A: Check out my solution here. It should be working fine. You mistakenly swapped the logic in the loop for adding players to teams. Also, it's a good habit to use Array.prototype.push than to create new element using a loop function after creating the array with new Array(length).
function step1() {
    var teams = document.getElementById("teams").value;
    var players = document.getElementById("players").value;
    var main = document.getElementById("main");
    main.innerHTML="";
    for(var i=1;i<=players;i++){
        main.innerHTML += "<input class='names' placeholder='Player "+i+"' type='text' style='width:100px'/>   "+
        "<input class='ranks' placeholder='Rank' type='text' style='width:40px'/>
";
    }
    main.innerHTML+="
<button onclick='buildTeams("+players+","+teams+")'>Build</button>";
}
function buildTeams(playersInt,teamsInt) {
    var error=0;
    var names = [];
    var ranks = [];
    var nameInp = document.getElementsByClassName("names");
    var rankInp = document.getElementsByClassName("ranks");
    for(var i=0;i<playersInt;i++) {
        names.push(nameInp[i].value);
    }
    for(var e=0;e<playersInt;e++) {
        ranks.push(rankInp[e].value);
    }
    var teams = [];
    for(var x=0;x<teamsInt;x++) {
        teams.push([]);
    }
    for(var a=0;a<teamsInt;a++) {
        for(var j=0;j<(playersInt/teamsInt);j++) {
            console.log(teams[a]);
            teams[a].push(names[checkMvp(ranks)]);
            ranks[checkMvp(ranks)]=-1;
        }
    }
    alert(teams);
    for(var w=0;w<teamsInt;w++) {
        alert(teams[w]);
    }

}
function checkMvp(ranks) {
    var high= ranks[0];
    var bpi=0;
    for(var i=1;i<ranks.length;i++) {
        if(ranks[i]>high) {
            bpi=i;
        }
    }
    return bpi;
}


text:
Q: What book - boy travels from home city and gets distended by gravity? I read a very special book a few years back. We follow a boy who lives in a world where, if one moves far enough in a direction, that person gets distended and changed in size.
The boy works on laying tracks for the train, on which his city is. The city has to continually keep moving or it also will get squashed.
It's like a world like if one end is pinched and then dragged out like a piece of rubber string or bubble gum.
The book is not older than 10 years I think.
Hope I was clear enough...

A: That sounds like Inverted World by Christopher Priest, although it's forty years old.
To quote from the linked Wikipedia article:

Helward lives in a city called "Earth", which is slowly being winched along at an average speed of 0.1 miles per day (0.16 km per day) on four railroad tracks northward toward an ever-moving, mysterious "optimum".
Upon reaching adulthood at the age of "650 miles", Helward leaves the crèche in which he has been raised and becomes an apprentice Future Surveyor. His guild surveys the land ahead, choosing the best route.
When Helward is assigned to escort three women back south to their village, he is astonished by what he learns about the alien nature of the world. As they go further south, the women's bodies become shorter and wider, and they begin to speak faster and in a higher pitch.


text:
Q: Array length question This question concerns optimization. Suppose I need the array length of an array A at two places in my code. Should I use the function a.length() in the two places, or is it faster to assign a local variable the value of a.length() and use it at the two places.
By "faster" I mean in terms of running time. Moreover, i am talking asymptotically.

A: The asymptotic complexity of calling the function twice is the same - any constant number of calls to the same (pure) function on the same arguments has the same asymptotic complexity as a single call to that function, since you can just roll the constant number of calls into the big-O's hidden constant.
As for what will be faster, there's no guarantee which one will be faster.  It depends on the language and compiler.  I'd suggest just writing it both ways and timing the result to see if there's an appreciable difference.  That said, if you are writing something that is so performance-critical that you can't afford to call .length() twice, you may need to reconsider your approach in general to see if there's a better global solution to the problem.  Microoptimizations are rarely worth the effort unless you have a compelling reason to believe that your program is markedly slower in the unoptimized version.

A: If you have to ask the question, you're not at a point where it matters yet.  If you were, you'd already have code that you've profiled, and you could just try it and see.  This kind of thing depends heavily on your language and compiler, and the only results that matter are the ones you see.
Don't worry about micro-optimizations til you find you need to shave cycles, and even then the algorithm is the first thing to check.

A: What language? In many languages, such calls are optimized away (either at compile time or by a JIT compiler) into direct access to the length field of the array object.


text:
Q: Cannot resolve symbol 'support' (using Android Studio, following getting started guide) I am getting started with Android development.
I have followed this Getting Started guide and use Android Studio (not eclipse).
I ran Hello World on my device, so far so good.  But..
Problem starts when adding this import: (as instructed by the guide)
import android.support.v4.app.NavUtils;  // cannot resolve symbol 'support'

Seems its needed by this line (commenting it and auto-resolving the import didnt work)
NavUtils.navigateUpFromSameTask(this);

The support import is red underlined, mouseover tells me Cannot resolve symbol 'support'
Build wont work either ofcourse. I have seen answers to similar questions such as;
suggesting clearing cache and retarting (tried that),
suggesting running SDK Manager as Administrator and updating (tried that),
and some other problems/solutions that seem eclipse specific.
I am new to Android development and the IDE. How about fixing this in Android Studio v0.2.9 ?
Edit:
Contents of my build.gradle file
buildscript {
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:0.5.+'
    }
}
apply plugin: 'android'

repositories {
    mavenCentral()
}

android {
    compileSdkVersion 17
    buildToolsVersion "17.0.0"

    defaultConfig {
        minSdkVersion 7
        targetSdkVersion 16
    }
}

dependencies {

    // You must install or update the Support Repository through the SDK manager to use this dependency.
    // The Support Repository (separate from the corresponding library) can be found in the Extras category.
    // compile 'com.android.support:appcompat-v7:18.0.0'
}

A: Fix in Android Studio using the GUI, without the direct editing of the Gradle files (validated for Android Studio starting v1.0.1 to v2.2.3):

*

*Right-click your module in the project tree. It is one, in most cases the first, of the root nodes. By default, it is called app.

*In the menu choose Open Module Settings:

*Switch to Dependencies tab.

*Click the add button (+) at the bottom of the dialog window.

*Choose Library Dependency.

*Choose support-v4 from the list.

*Click OK and rebuild.

A: Instead of editing the build.gradle I did it the maven way with right mouse on your root project -> Open Module Settings -> Dependencies Tab -> + -> Maven Dependency -> Search For "NavUtils" and select com.google.android:support-v4:r7@jar.
SDK Version 19 and Android Studio 0.4.2

A: Modify your gradle file like below and try if it works.
......

    dependencies {
       compile 'com.android.support:support-v4:18.0.0'

        // You must install or update the Support Repository through the SDK manager to use this dependency.
        // The Support Repository (separate from the corresponding library) can be found in the Extras category.
        // compile 'com.android.support:appcompat-v7:18.0.0'
    }


text:
Q: Ломается блок авторизации при масштабировании окна в браузере При масштабировании окна в браузере ломается блок авторизации, перепробовал кучу всего, ничего не выходит.
    <!DOCTYPE html>

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="viewport" content="width=device-width" />

<form action="/hello.php">

C3000-HUB

s/n MadiHub

    <input type="text" placeholder="login" name="login" required>

    <input type="password" placeholder="password" name="password" required>

    <button type="submit" class="registerbtn">Войти</button>

</form>

A: Так как ваша форма достаточно небольшая по размеру, то думаю можно сразу ей задать ширину статичной переменной. В противном случае можете сделать через @media что бы при масштабировании экрана изменялись первоначально заданные стили.

body {
  font-family: Arial, Helvetica, sans-serif;
  background-color: white;
  position: relative;
}

H1 {
  font-size: 150%;
  font-family: Verdana, Arial, Helvetica, sans-serif;
}

.container {
  width: 12rem;
  padding: 2%;
  background: linear-gradient(MediumBlue, SteelBlue);
  margin: 3% auto;
  border-radius: 1rem;
  color: white;
  text-align: center;
  line-height: 40%;
  font-size: 60%;
}

input[type=text],
input[type=password] {
  width: 90%;
  padding: 7%;
  margin: 0.5% 0 6% 0;
  display: inline-block;
  border: none;
  background: #f1f1f1;
  position: relative;
  border-radius: 1rem;
}

.registerbtn {
  background: linear-gradient(LightSkyBlue, DodgerBlue);
  color: white;
  padding: 0.5rem 1.75rem;
  margin: 0 auto;
  border: none;
  cursor: pointer;
  width: 60%;
  border-radius: 1rem;
  font-size: 200%;
  margin-bottom: 0.5%;
}
<!DOCTYPE html>

  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  <meta name="viewport" content="width=device-width" />

  <form action="/hello.php">

C3000-HUB

s/n MadiHub

      <input type="text" placeholder="login" name="login" required>

      <input type="password" placeholder="password" name="password" required>

      <button type="submit" class="registerbtn">Войти</button>

  </form>


text:
Q: Memory allocation during linux booting? I have tried to search this topic on google and this site but I can't find a proper answer.
I am trying to allocate a big continuous block of memory (a few MB) at a set physical address during the Linux booting process. But I am still not clear where I should place my "alloc_bootmem" function. I am running Linux on an ARM processor.

*

*AFAIK, there is a way to create a driver which contains a call to "alloc_bootmem" and then compile that driver directly to into the kernel.

*Another method is to add "alloc_bootmem" somewhere in the Linux kernel source.

*The last method that I think exists is to create a settings file like boot.rc?(not sure) so that during booting Linux will reserve the memory I want allocated.
If there is a clear way or a link to an answer to this question, I really would appreciate everyone's help. The basic question is "where should I call "alloc_bootmem" so it will work during booting?"
Thanks,
Shahril

A: Take a look at: http://lwn.net/Kernel/LDD3/ chapter 8 it explains the memory allocation for early booting stages.
Further information about booting memory allocation can be found here:
https://www.kernel.org/doc/gorman/html/understand/understand022.html
This feature is used for allocating large memory chunks during the system boot up and it uses the physical rather than virtual memory. After MMU is up and running there is no possible way of accessing the memory AFAIK
If you are looking for a large continues memory allocation you should probably use different allocator take a look at:
http://lwn.net/Articles/396702/


text:
Q: Batch script to launch an application and insert file name and then replication I want to run the "mIRT-PP" program, and put in file names on the cmd screen.
The format of the program is as follows.
When I run the "mIRT-PP.exe", 'Control card file name:' will pop up on a cmd screen where I need to insert USH_passage_BF_1.CRD:

I need a batch file for this.
How can I do this?


text:
Q: How to style action in MS teams adaptive card My intention is to emphasize button in the adaptive card, I noticed that adaptive card designer allows to choose from 3 different styles eg Default, Positive, Destructive, when you chose anything else than Default one it doesn't get applied neither in card designer nor in real MS teams message, here's the example of the message sent
{
    "type": "AdaptiveCard",
    "$schema": "http://adaptivecards.io/schemas/adaptive-card.json",
    "version": "1.2",
    "actions": [
        {
            "type": "Action.Submit",
            "title": "Action.Submit",
            "style": "destructive"
        }
    ]
}

what I see as result

Does anyone know how to change default action design in MS teams?

A: This is a Bug in Adaptive Card action button styling. I've filed a Bug for Adaptive Card team. I will update you once this got resolved

A: Currently, Teams Does not support Card action button styling in adaptive card. This is by design.


text:
Q: Deserialize JSON in C# to a LinkedList of Tuples I have a collection of tickets in my HTML code, from which I'm colleting information with JQuery and successfully posting in JSON to codebehind via AJAX.
 Here is the JSON file:
{
                'arrayTickets':
                               [
                                               {"num":1,"rec":"SWAFAD","temp":"0","id":"f39443aa-1ae1-4d18-82b8-468f14dac507"},

                                              {"num":1,"rec":"admin","temp":"0","id":"20bf1fea-b03e-4a28-922a-9618c8c8a73f"}                                           ]
}

The problem is I can't seem to be able to deserialize it to the type of structure I want:
[WebMethod]
public static void cmd_gravar_Click(string arrayTickets)
{
    JavaScriptSerializer json = new JavaScriptSerializer();

    LinkedList<Tuple<int, string, string, string>> tickets = json.Deserialize<LinkedList<Tuple<int, string, string, string>>>(arrayTickets);
}

I get the error:

No parameterless constructor defined for type of
  'System.Tuple`4[[System.Int32, mscorlib, Version=4.0.0.0,
  Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.String,
  mscorlib, Version=4.0.0.0, Culture=neutral,
  PublicKeyToken=b77a5c561934e089],[System.String, mscorlib,
  Version=4.0.0.0, Culture=neutral,
  PublicKeyToken=b77a5c561934e089],[System.String, mscorlib,
  Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]'.

I would like to keep using this structure as I already created a working method that saves the data to the DB with it. This is being done in webforms.
Edit: using VS2012

A: From what I remember the .net deserializer has issues with Tuples. I think JSON.net should solve your issue
https://www.nuget.org/packages/Newtonsoft.Json/
Usage:
 var result = JsonConvert.DeserializeObject<LinkedList<Tuple<int, string, string, string>>>(arrayTickets);


text:
Q: Why is the year dropdown in JQuery datepicker not being displayed in firefox 25.0? I'm using the JQuery datepicker in a modal. Everything works fine except that the year dropdown is not showing up when clicked. The z-index of the modal is less than that of the datepicker. All other components on the datepicker respond to click event but not the year dropdown. It works perfectly in chrome.
I checked the z-index by inspecting elements. The z-index is 3 as shown in the html but in the css panel it shows that the z-index: 3 has be striked off and a value of 10000 !important is being used which I put on purpose.But it still won't work


text:
Q: Foreign Data Wrappers, ogr_fwd layer Postgresql I have make correctly(it connects me) a Server with foreign data this way:
CREATE SERVER myserver
  FOREIGN DATA WRAPPER ogr_fdw
  OPTIONS (
   datasource 'C:\Program Files\PostgreSQL\9.5\tmp\test\myfile.dbf',
    format 'ESRI Shapefile' );

Then i make a foreign table like this:
CREATE FOREIGN TABLE pt_test (
  "field1" integer,
  "field2" varchar,
  "field3" varchar,
  "field4" varchar,
  "field5" varchar)
  SERVER myserver
  OPTIONS (layer 'pt_two');

When i make a Select to pt_test, it gives me this error:
SQL Error: ERROR:  unable to connect to layer to "pt_two"
HINT:  Does the layer exist?

I dont now what is layer.
Any help?

A: Run command ogr_fdw_info -s "C:\Program Files\PostgreSQL\9.5\tmp\test\myfile.dbf" this can provide list of layers in your file. Select existed one and pass it into 'layer' option from CREATE FOREIGN TABLE command. More info can be found here.


text:
Q: Minimizing pen lifts in a pen plotter or similar device I'm looking for references to algorithms for plotting on a mechanical pen plotter.
Specifically, I have a list of straight vectors, each representing a line to be plotted. First I want to remove duplicate vectors, so each line is only plotted once. That's easy enough.
Second, there are many vectors that intersect, sometimes at endpoints, but not always. They can be plotted in any order, but I want to find an order that reduces the number of times the pen must be lifted, preferably to a minimum though I understand that may take a long time to compute, if it's computable at all. Vectors that intersect can be broken into smaller vectors if that helps. But generally, if the pen is moving in a straight line, it's best to keep it moving that way as long as possible. So, two parallel vectors joined end to end could be combined into a single vector, etc.
This sounds like some variety of graph theory problem, but I don't know much about that. Can anyone point me to references or algorithms I need to study? Or maybe example code?
Thanks,
Neil

A: The problem is an example of the Chinese postman problem which is an NP-complete problem. The most wellknown NP-complete problem is the Travelling Salesman. Common for all NP-complete problems are that they can all be translated into eachother. There are no known algorithms for solving any of them in a time that is polynomial dependent of the number of nodes in the input, they are non-polynomial (NP).
For your case I would suggest some simple heuristics. Don't overdo it, just pick anything quite simple like going in a straight line as long as possible and then lift the pen to the closest available starting point and go on from there.


text:
Q: Best way to numerically evaluate derivative of complete elliptic integral 2 kind (C++) I need to compute numerically
$$
\frac{d}{dk}E(k) = \frac{E(k)-K(k)}{k}
$$
where E and K are the complete elliptic integrals of the second and first kind respectively.
Note that Wolfram uses $m=k^2$. In C++ we have these functions. To go from the C++ function to the wolfram function just raise k to 2 in wolfram or take the sqrt root in C++.
I have to compute with accuracy this derivative in the complete domain [0,1], therefore using the representation I put before or central differences do not give good enough results. I also tried a series expansion which works fine for small k, but not for big k.
What is a good way to evaluate this derivative numerically? In this case, I care about performance.

A: Taking into account all your requirements, for the computation of
$$\frac{d}{dk}E(k) = \frac{E(k)-K(k)}{k}$$what I should use is a spline function for
$$g(k)=\exp\Big[E(k)-K(k) \Big]$$ which is a nice and smooth function.
You only need one creation of this spline (or any other interpolating function).


text:
Q: Persistence frameworks and common sense I have studied some persistence frameworks mainly Hibernate, DORM, TMS Aurelius and I'm wondering. In a model of type:
TOrderFiscal < > ----- > Items < > -------- > TOrderItem ------- > TProduct

TOrderFiscal --------- > TSuplier --------- > TCidade -------- > State

Each class of this with countless attributes, all mapped correctly to their corresponding tables and fields. When carrying a note without using "Lazy Load" would always be done with several joins select all fields to come from each of these classes.
But it would be a waste since the note need only the supplier code and name attributes, the attributes OrderItem need only code, qty name. stock.
What solution should be taken to create a specific class supplier of note just with these attributes ? eg
TOrder <> ----- > Items <> -------- > TOrderItem ------- > TNotaItemProduct

TOrder -------- > TOrderSupplier

If this is the solution , what happens when a business rule in TProduct should also be TOrderItemProduct? I duplicate code in both classes? Do heritage, eg TORderItemProduct and TProduct both inheriting from TBaseProduct ?
Or is this a concern that we programmers we should not have ?

A: This is what we use the Hibernate Query Language (hql) for - to select only the desired data when the entire object web is not needed. For example:
select new map (s.code as sCode, s.name as sName, i.code as iCode, i.qty as qty, i.name as iName, i.stock as stock)
from TOrderFiscal tof
join tof.suplier s
join tof.items i
join i.product p
where p.id = 12345;

You will get back a list of map of string to object, where each item in the list is a row in the result set represented as a map of the selected field aliases to the field values.


text:
Q: Regexp for cleaning the empty, unnecessary HTML tags I'm using TinyMCE (WYSIWYG) as the default editor in one of my projects and sometimes it automatically adds <p> </p> , <p> </p> or divs.
I have been searching but I couldn't really find a good way of cleaning any empty tags with regex.
The code I've tried to used is,
$pattern = "/<[^\/>]*>([\s]?)*<\/[^>]*>/";
$str = preg_replace($pattern, '', $str);

Note: I also want to clear &nbsp too :(

A: Try
/<(\w+)>(\s| )*<\/\1>/
instead. :)

A: That regexp is a little odd - but looks like it might work.  You could try this instead:
$pattern = ':<[^/>]*>\s*</[^>]*>:';
$str = preg_replace($pattern, '', $str);

Very similar though.

A: I know it's not directly what you asked for, but after months of TinyMCE, coping with not only this but the hell that results from users posting directly from Word, I have made the switch to FCKeditor and couldn't be happier.
EDIT: Just in case it's not clear, what I'm saying is that FCKeditor doesn't insert arbitrary paras where it feels like it, plus copes with pasted Word crap out of the box. You may find my previous question to be of help.

A: You would want multiple Regexes to be sure you do not eliminated other wanted elements with one generic one.
As Ben said you may drop valid elements with one generic regex
<\s*[^>]*>\s*` `\s*<\s*[^>]*>
<\s*p\s*>\s*<\s*/p\s*>
<\s*div\s*>\s*<\s*/div\s*>

A: Try this:
<([\w]+)[^>]*?>(\s| )*<\/\1>


text:
Q: How to trigger same function of two different jQuery version using simple code snippet..? I want to register onchange event on this select box ..
   <select id="demo">
        <option>Apple</option>
        <option>Orange</option>
        <option>Banana</option>
    </select>

There are two versions of jQuery included on my page that are separated using noConflict

I have put this code in the script tag..

I have triggered onchange event on selectbox using
$("#demo").val("Orange").trigger("change")

then it execute the
 $("#demo").on("change",function(){..})

but don't execute the second one
($m("#demo")..)

How can I trigger the onchange event which calls both the event handlers ($ and $m)?

A: I'm not sure if there's a way to do this by using jQuery, but you can do it by dispatching a plain javascript event like this:
var event = new Event('change', {
    bubbles: true
});

$("#demo").val("Orange")[0].dispatchEvent(event);

Working Example

$("div#hello").on("change","select#demo",function (){
 console.log("in $ on function");
});
$m("select#demo").on("change",function(){
 console.log("in $m on function");
});

$('#trigger_event').on('click', function(e) {
  var event = new Event('change', {
    bubbles: true
  });

  $("#demo").val("Orange")[0].dispatchEvent(event);
});

<select id="demo">
    <option>Apple</option>
    <option>Orange</option>
    <option>Banana</option>
</select>

<button id="trigger_event">Trigger Event</button>

EDIT
Here is the same technique and now triggers the event on document ready without clicks. Tested on Chrome, IE and Mozilla and it's working fine:

$("div#hello").on("change","select#demo",function (){
    console.log("in $ on function");
});
$m("select#demo").on("change",function(){
    console.log("in $m on function");
});

$(document).ready(function() {
    console.log('On document ready');

    var event = new Event('change', {
        bubbles: true
    });

    $("#demo").val("Orange")[0].dispatchEvent(event);
});

<select id="demo">
    <option>Apple</option>
    <option>Orange</option>
    <option>Banana</option>
</select>

My working test link: http://zikro.gr/dbg/html/multijq-trigger/
As you can see it's even working inside the document ready event.


text:
Q: Can there be Neutrino and antineutrino oscillations? I don't know have rigor knowledge in neutrino oscillations. I just know that there is not a definite mass state for a definite flavor Just like with spin where you might have eigenstate $|+\rangle_z$ but that would not have definite spin angular momentum in $x$ or $y$ direction.

For two-level system, We can see the mixing of the state with
$$\begin{pmatrix}
\nu_e\\
\nu_\mu
\end{pmatrix}=\begin{pmatrix}
\cos\theta& \sin\theta\\
-\sin\theta& \cos\theta
\end{pmatrix}\begin{pmatrix}
\nu_1\\
\nu_2
\end{pmatrix}$$
If we start  with $\psi(0)=|\nu_e\rangle $ then at later instant of time
$$|\psi(t)\rangle =U(t)|\psi(0)\rangle =U(t)|\nu_e\rangle=U(t)[|\nu_1\rangle \cos \theta+|\nu_2\rangle \sin\theta]=e^{-iE_1 t/\hbar}\cos\theta|\nu_1\rangle +e^{-iE_2t/\hbar}\sin\theta|\nu_2\rangle  $$
One can find the transition probability  $P(\nu_e\rightarrow \nu_\mu)$.

Is there oscillation between neutrino and antineutrino states? I don't how to work with neutrino and antineutrino. How to represent an antineutrino state? According to Wikipedia, It says, they are denoted by the complex conjugate. Is that mean  bra vector $\langle \nu_e|$?

A: There is an additional intricacy involved when discussing antineutrinos. Roughly speaking there are two possible ways of introducing mass terms for Fermions in QFT: We can have either Majorana or Dirac Fermions.
All charged Fermions need to be Dirac Fermions since for Majorana Fermions particle and antiparticle coincide i.e. cannot have opposite electric charges unless they are neutrally charged.
For neutrally charged particles such as Neutrinos, Majorana mass terms are a plausible option. There are actually several good reasons why Neutrinos should indeed be Majorana Fermions. On the one hand, the seesaw mechanism could then be used to produce extremely light left handed neutrinos and (yet unobserved) very heavy right handed neutrinos. This naturally explains the small neutrino masses that we observe. On the other hand, if the neutrinos were Majorana Fermions, then they would provide Lepton number violating processes. These can be relevant for Lepto- and Baryogenesis as is explored for example in Common origin of baryon asymmetry, dark matter and neutrino mass.
The difference between Majorana and Dirac Fermions can often lead to confusion - especially if it is not explicitly stressed in the literature that you are using. So maybe this is also the source of your problem.


text:
Q: Opencv Histogram Data from Mat So I'm trying to get the actual data from the histogram I generated in OpencCV.  I'm using the code located here and can be seen below.  However, I don't exactly know how to get the data from this Mat.  I saw this post, but the post uses hist.get(i, 0) to get the histogram data.  However, my histogram Mat only contains 1 row... and 16384 cols.  The pertinent code is below.
static Mat spatial_histogram(InputArray _src, int numPatterns,
                         int grid_x, int grid_y, bool /*normed*/)
{
    Mat src = _src.getMat();
    // calculate LBP patch size
    int width = src.cols/grid_x;
    int height = src.rows/grid_y;
    // allocate memory for the spatial histogram
    Mat result = Mat::zeros(grid_x * grid_y, numPatterns, CV_32FC1);
    // return matrix with zeros if no data was given
    if(src.empty())
        return result.reshape(1,1);
    // initial result_row
    int resultRowIdx = 0;
    // iterate through grid
    for(int i = 0; i < grid_y; i++) {
        for(int j = 0; j < grid_x; j++) {
            Mat src_cell = Mat(src, Range(i*height,(i+1)*height), Range(j*width,(j+1)*width));
            Mat cell_hist = histc(src_cell, 0, (numPatterns-1), true);
            // copy to the result matrix
            Mat result_row = result.row(resultRowIdx);
            cell_hist.reshape(1,1).convertTo(result_row, CV_32FC1);
            // increase row count in result matrix
            resultRowIdx++;
        }
    }
    // return result as reshaped feature vector
    return result.reshape(1,1);
}

result becomes a Mat of size 1 x 16384 and the values are sparse in the Mat... So how would I get the proper histogram data?


text:
Q: Blob Storage of images and text I have a blob (storage account) that is housed on Azure.  I also have a sql server table that is housed on Azure.  I have a couple of questions

*

*Is it possible to create a join between the blob and the table

*Is it possible to store all of the information in the blob?
The table has address information on it and I wanted to be able to pull that information from the table and associate it or join it to the proper image by the ID in the sql table (if that is the best way)

A: Azure Storage (blob, in your case) and SQL Server are completely separate, independent data stores. You cannot do joins, transactions, or really any type of query, across both at the same time.
What you store in each is totally up to you. Typically, people store searchable/indexable metadata within a database engine (such as SQL Server in your case), and non-searchable (binary etc) content in bulk storage (such as blobs).
As far as "best way"? Not sure what you're looking for, but there is no best way. Like I said, some people will store anything searchable in their database. On top of this, they'd store a url to specific blobs that are related to that metadata. There's no specific rule about doing it this way, of course. Whatever works for you and your app...
Note: Blobs have metadata as well, but that metadata is not indexable; it would require searching through all blobs (or all blobs in a container) to perform specific searches.

A:
Is it possible to create a join between the blob and the table?

No.

Is it possible to store all of the information in the blob?

You possibly could (by storing the address information as blob metadata) but it is not recommended because then you would lose searching capability. Blob storage is simply an object store. You won't be able to query on address information.

The table has address information on it and I wanted to be able to
  pull that information from the table and associate it or join it to
  the proper image by the ID in the sql table (if that is the best way)

Recommended way of doing this is storing the images in blob storage. Each blob in blob storage gets a unique URL (https://account.blob.core.windows.net/container/blob.png) that you can store in your database along with other address fields (e.g. create a column called ImageUrl and store the URL there).


text:
Q: Reading the userAgent with C# I have the following code which reads the userAgent and does some logic based on the values matched using indexOf:
String userAgent;
userAgent = Request.UserAgent;
// If it's not IE
if (userAgent.IndexOf("MSIE") < 0)
{
    return RedirectToAction("Index", "Home", new { area = "Dashboard" });
}
// If it's IE BUT ChromeFrame
else if(userAgent.IndexOf("ChromeFrame") > -1)
{
    return RedirectToAction("Index", "Home", new { area = "Dashboard" });
}
// It's just IE
else
{
    return View("ChromeFrame");
}

If it's IE then it should return the view or if its IE but contains ChromeFrame then it should redirect and it's another browser then it should redirect as well.
I think the problem is with the > 0 part of the code. What is the correct way of comparing info? Thanks.

A: Just use the  contains method, which will make your code less cryptic and less error-prone.
if (userAgent.Contains("MSIE"))
{
    return RedirectToAction("Index", "Home", new { area = "Dashboard" });
}

A: You should be using > -1 as otherwise it will not work if the substring is at the beginning of the string.

A: IndexOf returns -1 if the string is not found... see MSDN for reference.


text:
Q: How to draw a Divider Line with Name Title before the output display I have written a script which displays Name and department of the user and that works.Moreover i am trying to draw a divider line with Name title assign to the columns as they needed. I am trying to do it with printf but somehow not able to get it as of now.. any help will be appreciated..
below is the script and expected result..
#!/bin/sh
for names in `cat namefile`;

do

DATA1="`/grid/common/bin/cod -u $names | awk -F: '/Department/ {print $2}'`"
DATA2="`/grid/common/bin/cod -u $names | awk -F: '/Name/ {print $2}'`"

#printf '%*s\n' "${COLUMN'S:-$(tput cols)}" '' | tr ' ' -
printf "%-50s : %10s\n" "$DATA2" "$DATA1"
done
bash-4.1$ sh Userdetail.sh
        Karn Kumar                                 :   TT, Infra, VM & India
        Manas .                                    :   TT, Infra, VM & India
        Pranjal Agrawal                            :   TT, Infra, VM & India
        Rogen Mana                                 :   PP OPS-Brazil

I'm trying to find a way draw a line with Titles before the output will display like below expected:
  Name                                         Department

--------------------------------------------------
Karn Kumar                                 :   TT, Infra, VM & India
Manas .                                    :   TT, Infra, VM & India
Pranjal Agrawal                            :   TT, Infra, VM & India
Rogen Mana                                 :   PP OPS-Brazil

Just for more how to know on the command part..

bash-4.1$ /grid/common/bin/cod -u karn
        Name:        Karn Kumar
        Title:       IT -Staff Systems Engineer

        Department:  TT, Infra, VM & India
        Mgr:         KK LIN
        Mgr Login:   ttlin
        E-Mail:      karn@abc.com
        Phone:       09999999999
        Internal #:
        Ext:         4848
        Cell:        8777880559
        Fax:            -
        Building:    NOIDA 03
        Floor:       03
        Room:        3.3.109

A: You have printf "%-50s : %10s\n" "$DATA2" "$DATA1" , which tells me in total you will have 63-character wide line (including spaces and :). Thus we will want to printf "%63s" string. Simple approach is to print spaces and then convert them all to - like so
printf "%60s" " " | tr ' ' '-'

We certainly could use simpler approach, but it is specific to bash. We can, however, modify it slightly:
printf "=%.0s"  $(seq 1 63)

This will work in any shell and system that has seq installed.
Thus, print the header before going into the loop. For example, here's very very simple case:
$ cat ./print_header.sh
#!/bin/bash
# print header
printf "%-50s : %10s\n" "Name"  "Department"
# print separator
printf "=%.0s"  $(seq 1 63)
# insert a newline
printf "\n"
# and this is where your for loop would begin.
# just for the sake of example, there's only one line
printf "%-50s : %10s\n" "John Doe"  "IT,Infra"
$ ./print_header.sh
Name                                               : Department
===============================================================
John Doe                                           :   IT,Infra


text:
Q: Choosing the right database on cloud, Azure SQL We are building an application, an ad serving platform, which will include many processes such as reporting, storing user data, requests, advertiser info, pubisher info etc. Moreover, we will be generating optimization files to serve better ads.
We are using azure for cloud services. We are hoping to benefit from appfabric on azure and their architecture.
My question is related to Azure SQL. Does anyone have any experience with Azure DB, what are the advantages, disadvantages? Performance, reliability, challenges?
While choosing Azure DB, what are things should we benchmark or prototype?
Any ideas or thought, you would like to share, especially related to database on cloud? COnsistency, availability, Partial Tolerance, replication?
Thanks.

A: Advantage of SQL Azure is that you can develop against a pretty standard SQL database that people have lots of experience with. Make migration of an app to Azure pretty easy.
The disadvantages i have seen are:
1. Limited backup. This is getting better soon, but it may never be the kind of backup many people want.
2. Some SQL Server features not available, but 95% are.
3. No real control over database server hardware.
4. Price might be an issue, depending on your database size.
Other than that, SQL Azure works well for me.

A: You really need to size your data.
SQL Azure is perfect for small (<1 GB or few GBs) with relational requirements. It provides easy on-boarding for existing sql server developers and makes it really easy to develop complex reports.
However once the data size increases beyond a few GBs, it starts becoming more expensive. Also the patterns for scaling SQL Azure is not as simple as scaling Windows Azure Database - although the new feature of Federations is supposed to make it simpler, it is still not the same as scaling SQL Server (which people would normally scale-up - here in SQL Azure there is a limit of 50 GB and the recommended pattern is to scale-out to more databases).
So, going by what you have (requests, maybe user click data, etc) which can really increase a lot, it might be better to save all this in Windows Azure database instead of SQL Azure. You can also take a dual approach, by saving some data in SQL Azure so that it is easier to report against, and then have high quantity data saved in Windows Azure.
Architect well! It could save a lot!

A: We used this for a web application.
Experience:
We faced hardly any challenges as it was easy to use because it provides the same TDS interface as the more familiar SQL server so developers can easily adapt if need be. This saved us a lot of time that is usually taken up with Developers having to learn new tools.
Overall I found it to be consistent with good performance and quite reliable.
Other thoughts:
-Manageability

*

*offers easy manageability, thus
saving on a lot of IT related costs

-Scalability

*

*runs in worldwide data centers so can
reach new markets easily

*Can choose a pay as you go pricing
model

Hope this helps!

A: Although this has been answered already, I'd figure I add some more info to it anyway.
In the cloud, you have three storage options, each for its own set of data:

*

*SQL Azure - this is your standard MS SQL database, with some features currently disabled (note: the team has said, several times, all of the features will be turned on eventually). It guarantees reliability (AFAIK) by keeping three copies of your data available at any given time. You also get some issues, like connection drops here and there, and you need to plan for that (in the repository logic, you need to have retry logic). Obviously, as with other relational databases, this is mostly useful for storing relational data. Pricing is OK up to 1 GB (~ 10 USD) and goes up dramatically with up to 10 GB (~ 100 USD) so make sure you need it.

*Azure Table Storage - this is a simple table storage. You primary key is defined based on two IDs (Column & Row keys) and you can store in it, more or less, whatever you like. You cannot index the data (but the key columns are indexed, so your queries can be pretty optimized if you know what you are doing). This is cheap (you pay by transaction), I think the price is around $0,01 per 10.000 transactions. You can use this storage for a lot of things, and you can also implement relations to some extent if you do it right.

*Blob Storage - you can use this to store your optimization files. It costs around $0.15 per GB/month if I remember correctly.

As for performance considerations, the blob storage is really fast. I didn't expect it to be this fast. SQL does good as well, it is after all your normal MS SQL database. Since it's located "close" to your instance, the network latency is not that much bigger than it would be were it located in a separate machine in your data center.
For up to date info on pricing, look at this Windows Azure Platform Offers. I'm not an expert in pricing, so my figures are rough estimates.

A: You can find out more about SQL DB offerings and their corresponding throughput on the SQL DB pricing page. Also, do check out details on the new SQL DB V12 that provides nearly complete compatibility with SQL Server engine.
Edit (4/29) :
Check out the new Elastic DB offering (Preview) announced at Build today. The pricing page has been updated with Elastic DB price information.

A: The first thing to do is look at SQL Azure's feature list to ensure this meets your needs (it probably will), and then the get started page.
Then there are free Labs: SQL Azure Labs.
You can get a live, free 1GB database for 30 days.
The SQL Azure Team blog may be of interest.


text:
Q: Accessing the values of a key I have a dictionary like:
Data = {
    "weight_factors" : {
        "parameter1" : 10,
        "parameter2" : 30,
        "parameter3" : 30
        },
    "other_info" : {
        }
}

I want to get the sum of all values that are under the key "weight_factors":
sum = Data["weight_factors"]["parameter1"] +
      Data["weight_factors"]["parameter2"] +
      Data["weight_factors"]["parameter3"]

Currently, in order to avoid entering Data["weight_factors"] repeatedly, I use the following commands:
d = Data["weight_factors"]
d["parameter1"] + d["parameter2"] + d["parameter3"]

But, I guess there should be an operator that does the same thing, without storing Data["weight_factors"] as an intermediate variable. I was wondering if such a command or an operator exists.
Data["weight_factors"]<unknown operator>(["parameter1"] +
                                         ["parameter2"] +
                                          ...
                                         ["parametern"])<unknown operator>

EDIT:
In the example given above, it was just a sum operation. But it could for example be:
Data["weight_factors"]["parameter1"] * Data["weight_factors"]["parameter2"] + Data["weight_factors"]["parameter3"]

But I do not want enter Data["weight_factors"] repeatedly. That's the thing I am searching for... I don't know whether such an operator exists. (In MATLAB, there exists such a thing for cell structures).

A: No, that kind of operator does not exist for the built-in dict type.
I suppose you could make your own dict type that inherited from dict and overloaded an operator:
class MyDict(dict):
    def __add__(self, other):
        """Overload the + operator."""
...

but that is somewhat inefficient and not very good for readability.
If you just want to sum the values, you can use sum and dict.values (dict.itervalues if you are using Python 2.x):
>>> Data = {
... "weight_factors" : {
...     "parameter1" : 10,
...     "parameter2" : 30,
...     "parameter3" : 30
...     },
... "other_info" : {
...     }
... }
>>> sum(Data["weight_factors"].values())
70
>>>

Otherwise, I would just use what you have now:
d = Data["weight_factors"]
myvar = d["parameter1"] * d["parameter2"] + d["parameter3"]

It is about as clean and efficient as you can get.

A: For a general solution to repeatedly get the same item from a mapping or index, I suggest the operator module's itemgetter:
>>> import operator

>>> Data = {
    "weight_factors" : {
        "parameter1" : 10,
        "parameter2" : 30,
        "parameter3" : 30
        },
    "other_info" : {
        }
    }

Now create our easy getter:
>>> get = operator.itemgetter('weight_factors')

And call it on the object whenever you want your sub-dict:
>>> get(Data)['parameter1']

returns:
10

and
>>> sum(get(Data).values())

returns
70

A: If this is just "how do I access a dict's values easily and repeatedly?" you should just assign them like this, and you can reuse them again and again.
In Python 2:
vals = Data['weight_factors'].values()

In Python 3, values returns an iterator, which you can't reuse, so materialize it in a list:
vals = list(Data['weight_factors'].values())

and then you can do whatever you want with it:
sum(vals)
max(vals)
min(vals)

etc...


text:
Q: How to find uncommented public methods using Resharper I am using Resharper 7.1 with Visual Studio 2010. Is there a way to find all uncommented (without method summary and parameter descriptions) public methods through the entire solution?

A: You don't need Resharper for this.
Simply check "Generate XML documentation file" in the build tab in project properties, and the compiler will warn you about every missing comment.

A: You could do this with the Agent Smith plugin for ReSharper. I wrote about how to do it a long time ago in my blog, but honestly I don't know if this method still works. You can read about it here: http://hmemcpy.com/2010/11/documenting-your-public-api-easily-with-resharper-and-ghostdoc/
Looks like there's a version of Agent Smith plugin available for ReSharper 7.1, so you might be in luck!


text:
Q: bind9, Resolve example.com but forward *.example.com to a forwarder possible? is it possible in bind to resolve example.com with a zone but resolve all subdomains of example.com with a forwarder?
If somebody knows how this can work or has some simple sample configurations i would love to hear about it.
Thanks!


text:
Q: How can i write ( draw string ) on ImageSource? I have some simple ImageSource.
I want to 'draw' some string every 20 pixels and show the result on the Image control.
In simple WPF i did it by using Graphics (  using ( Graphics g = Graphics.FromImage( imgTarget ) ) )
But in silverlight i can't use Graphics.
So, How can i do it in silverlight ?
Thanks for any help.

A: you need to use WriteableBitmap.  There is one caveate, tho. If you get an image from an external link into WriteableBitmap, you won't be able to alter it due to security restrictions placed on the class.
WriteableBitmap is a bit primative, so i would recommend the WriteableBitmapEx library on codeplex. It is a really nice extention library for WriteableBitmap that gives you things like Bliting and shapes and transformations, etc.
[Edit]
As suggested by @Samvel Siradeghyan, you should (probably) use the code here to render text to your WriteableBitmap

A: You can use WriteableBitmap class.
You can find simple code about how to do that here: Rendering Text to a WriteableBitmap with Silverlight 3's Bitmap API
Other solution is in http://forums.silverlight.net (not as good as in first article).


text:
Q: ExtJs 4.1: Destroy components on closing a dynamically created tab I am creating new ExtJs tabpanels and rendering panels inside it programmatically.
The panels (rendered inside tabs) are all written in separate JS files.
Opening, rendering and closing of the tabs is working completely fine.
But when I debug the code I see that the previous components of the closed tabs are still active in the memory. As a result of which the functioning of the components gets affected when the tab is reopened.
I want to destroy all the components inside the tab panels (if ExtJs, for some reasons, is not able to do it).
How can I do this?
Below is a sample code which I am trying:
Main Tab:
var tabs = new Ext.TabPanel({
    id : 'screensTabPanel',
    layout : 'fit',
    enableTabScroll : true,
    height : Ext.getBody().getStyleSize().height - 60,
    activeTab : 0,
    //enableTabScroll : true,
    autoScroll : true,
    autoRender : true,
    border : false,
    plugins : [ {
        ptype : 'tabscrollermenu',
        maxText : 30,
        pageSize : 5
    } ]
});

Dynamic Tab object:
var tabConfig = {
            title : text,
            bodyPadding : 3,
            closeAction:'destroy',
            autoScroll : true,
            id : 'tab' + id,
            closable : closable,
            loader : {
                loadMask : 'loading...',
                autoLoad : true,
                url : url,
                scripts : true,
                params : {
                    userId : 1
                },
            border : false,
            appId : appIdx,
            screenId : screenId,
            gridType : gridType,
            listeners : {
                beforeclose : function(tab) {
                    debugger;
                    tab.removeAll(); //I tried doing this
                    tab.destroy(); //I tried doing this as well
                    return true;
                }
            }
        };

Internal Panel code:
Ext.define('Ext.ux.window.VisualSQLQueryBuilder', {
extend: 'Ext.panel.Panel',
itemId: 'qb-VisualSQLQueryBuilderId',
renderTo: Ext.Element.get('divQueryBuilder'),
layout: {
    type: 'border'
},
listeners:{
    beforerender: function(thisa, eOpts ){
        debugger;
        /*if(Ext.ComponentQuery.query("#qb-VisualSQLQueryBuilderId").length > 1){
            Ext.ComponentQuery.query("#qb-VisualSQLQueryBuilderId")[0].destroy();
        }*/
        Tab.MainTab = Ext.ComponentQuery.query("#qb-VisualSQLQueryBuilderId")[Ext.ComponentQuery.query("#qb-VisualSQLQueryBuilderId").length - 1];
    }
},
items: [ .... screen components ... ]
});

Add Panel object to tab:
addedTab = ExtCont.add(tabConfig);
addedTab.show();
ExtCont.setActiveTab(addedTab);

Now this is what happens:

*

*Open Tab (Name - Query Builder)

*Code reaches the beforerender listener.

*Ext.ComponentQuery.query("#qb-VisualSQLQueryBuilderId") has only one object inside it.

*Everything works fine.

Now the problem starts

*

*Close the tab

*Code reaches beforeclose listener. Trying tab.removeAll() and tab.destroy()

*Reopen tab - Query Builder

*Code reaches beforerender listener.

*Now Ext.ComponentQuery.query("#qb-VisualSQLQueryBuilderId") has two objects inside it. So it is retaining the object of the tab opened first time. And the second one is that of the tab opened just now.

How do I ensure whenever a tab is closed all its components get smoothly destroyed?

A: from TabPanel:

Note: By default, a tab's close tool destroys the child tab Component and all its     descendants. This makes the child tab Component, and all its descendants unusable. To enable re-use of a tab, configure the TabPanel with autoDestroy: false.

so it could really be an ExtJS Bug cause autoDestroy: true is default. maybe you could open a ticket.


text:
Q: Overide methods when instantiated using findviewbyid I had a question on overriding methods.
When i instantiate a view i'm having 2 options.
1.Instantiate view programatically.
View view = new View( .... ){
      onDraw(){

         .......
      }

 };

2.Instantiate view from layout.
View view = findViewbyid(...){

        onDraw(){
           .......
        }
};

My question is, is there any possibility to override methods as shown in 2nd option.?
Thanks & Regards,
Sha.

A: No, the second option is not possible. However, you may create your custom class which extends View and override whatever you want inside.

A: No, You can't do it with the second option.
when you use findViewById you are already instantiating the native Android View class, and it calls the constructor:
public View (Context context, AttributeSet attrs).
You must create your custom View and override there the implementation of
onDraw(Canvas canvas) to adapt to your needs.


text:
Q: How to sync two folders with command line tools? Having migrated to Linux from Windows, I would like to find an alternative software to Winmerge or rather learn command line tools to compare and sync two folders on Linux. I would be grateful if you could tell me how to do the following tasks on the command line... (I have studied diff and rsync, but I still need some help.)
We have two folders: "/home/user/A" and "/home/user/B"
Folder A is the place where regular files and folders are saved and folder B is a backup folder that serves as a complete mirror of folder A. (Nothing is directly saved or modified by the user in folder B.)
My questions are:

*

*How to list files that exist only in folder B? (E.g. the ones deleted from folder A since the last synchronization.)

*How to copy files that exist in only folder B back into folder A?

*How to list files that exist in both folders but have different timestamps or sizes? (The ones that have been modified in folder A since last synronization. I would like to avoid using checksums, because there are tens of thousands of files and it'd make the process too slow.)

*How to make an exact copy of folder A into folder B? I mean, copy everything from folder A into folder B that exists only in folder A and delete everything from folder B that exists only in folder B, but without touching the files that are the same in both folders.

A: This is what I'm using for backing up personal files, where I don't care about everything covered by -a, and want more useful information printed.
rsync -rtu --delete --info=del,name,stats2 "/home/<user>/<src>/" "/run/media/<user>/<drive>/<dst>"

From the rsync man page:

-r, --recursive
This tells rsync to copy directories recursively.
-t, --times
This tells rsync to transfer modification times along with the files and update them on the remote system.
-u, --update
This forces rsync to skip any files which exist on the destination and have a modified time that is newer than the source file. (If an existing destination file has a modification time equal to the source file's, it will be updated if the sizes are different.)
--delete
This tells rsync to delete extraneous files from the receiving side (ones that aren't on the sending side), but only for the directories that are being synchronized.
--info=FLAGS
This option lets you have fine-grained control over the information output you want to see.

From rsync --info=help
DEL        Mention deletions on the receiving side
NAME       Mention 1) updated file/dir names, 2) unchanged names
STATS      Mention statistics at end of run (levels 1-3)

While less explicit, this is seemingly equivalent and shorter:
rsync -rtuv --delete --info=stats2 "/home/<user>/<src>/" "/run/media/<user>/<drive>/<dst>"

-v, --verbose
A single -v will give you information about what files are being transferred and a brief summary at the end [stats1].

A: This puts folder A into folder B:
rsync -avu --delete "/home/user/A" "/home/user/B"

If you want the contents of folders A and B to be the same, put /home/user/A/ (with the slash) as the source. This takes not the folder A but all of it's content and puts it into folder B. Like this:
rsync -avu --delete "/home/user/A/" "/home/user/B"

*

*-a Do the sync preserving all filesystem attributes

*-v run verbosely

*-u only copy files with a newer modification time (or size difference if the times are equal)

*--delete delete the files in target folder that do not exist in the source

Manpage: https://download.samba.org/pub/rsync/rsync.html

A: You might have a look at Fitus/Zaloha.sh. It is a synchronizer implemented as a bash shell script that uses only standard Unix commands. It is easy to use:
$ Zaloha.sh --sourceDir="test_source" --backupDir="test_backup"

A: You could unison tool developed by Benjamin Pierce at U Penn.
Let us assume you have two directories,
/home/user/Documents/dirA/ and /home/user/Documents/dirB/
To synchronize these two, you may use:
~$unison -ui text /home/user/Documents/dirA/ /home/user/Documents/dirB/
In output, unison will display each and every directory and file that is different in the two directories you have asked to sync. It will recommend to additively synchronize (replicate missing file in both locations) on the initial run, then create and maintain a synchronization tree on your machine, and on subsequent runs it will implement true synchronization (i.e., if you delete a file from .../dirA, it will get deleted from .../dirB as well. You can also compare each and every change and optionally choose to forward or reverse synchronize between the two directories.
Optionally, to launch graphical interface, simply remove the -ui text option from your command, although I find the cli simpler and faster to use.
More on this: Unison tutorial at Unison user documentation.

A: The answer from TuxForLife is pretty good, but I strongly suggest you use -c when syncing locally. You can argue that it's not worth the time/network penalty to do it for remote syncs, but it is totally worth it for local files because the speed is so great.

-c, --checksum
       This forces the sender to checksum every regular file using a 128-bit  MD4
       checksum.   It  does this during the initial file-system scan as it builds
       the list of all available files. The receiver then checksums  its  version
       of  each  file  (if  it exists and it has the same size as its sender-side
       counterpart) in order to decide which files need to be updated: files with
       either  a  changed  size  or a changed checksum are selected for transfer.
       Since this whole-file checksumming of all files on both sides of the  con-
       nection  occurs  in  addition to the automatic checksum verifications that
       occur during a file's transfer, this option can be quite slow.

       Note that rsync always verifies that each transferred file  was  correctly
       reconstructed  on  the receiving side by checking its whole-file checksum,
       but that automatic after-the-transfer verification has nothing to do  with
       this  option's  before-the-transfer  "Does  this file need to be updated?"
       check.

This shows how having the same size and time stamps can fail you.
The setup
$ cd /tmp

$ mkdir -p {A,b}/1/2/{3,4}

$ echo "\___________from A" | \
      tee A/1/2/x  | tee A/1/2/3/y  | tee A/1/2/4/z  | \
  tr A b | \
      tee b/1/2/x  | tee b/1/2/3/y  | tee b/1/2/4/z  | \
      tee b/1/2/x0 | tee b/1/2/3/y0 >     b/1/2/4/z0

$ find A b -type f | xargs -I% sh -c "echo %; cat %;"
A/1/2/3/y
\___________from A
A/1/2/4/z
\___________from A
A/1/2/x
\___________from A
b/1/2/3/y
\___________from b
b/1/2/3/y0
\___________from b
b/1/2/4/z
\___________from b
b/1/2/4/z0
\___________from b
b/1/2/x
\___________from b
b/1/2/x0
\___________from b

The rsync that copies nothing because the files all have the same size and timestamp
$ rsync -avu A/ b
building file list ... done

sent 138 bytes  received 20 bytes  316.00 bytes/sec
total size is 57  speedup is 0.36

$ find A b -type f | xargs -I% sh -c "echo %; cat %;"
A/1/2/3/y
\___________from A
A/1/2/4/z
\___________from A
A/1/2/x
\___________from A
b/1/2/3/y
\___________from b
b/1/2/3/y0
\___________from b
b/1/2/4/z
\___________from b
b/1/2/4/z0
\___________from b
b/1/2/x
\___________from b
b/1/2/x0
\___________from b

The rsync that works correctly because it compares checksums
$ rsync -cavu A/ b
building file list ... done
1/2/x
1/2/3/y
1/2/4/z

sent 381 bytes  received 86 bytes  934.00 bytes/sec
total size is 57  speedup is 0.12

$ find A b -type f | xargs -I% sh -c "echo %; cat %;"
A/1/2/3/y
\___________from A
A/1/2/4/z
\___________from A
A/1/2/x
\___________from A
b/1/2/3/y
\___________from A
b/1/2/3/y0
\___________from b
b/1/2/4/z
\___________from A
b/1/2/4/z0
\___________from b
b/1/2/x
\___________from A
b/1/2/x0
\___________from b

A: Another option: https://github.com/mikkorantalainen/rsync-continuous
This script uses bash, inotifywait and rsync over ssh to create very fast one-way sync because only modified files need to be transferred and if only part of the file has been modified, rsync will only transfer the modified part.

A: You can use it this way:
rsync -avu --delete /home/user/A/* /home/user/B/

This way you will copy the content of folder A into folder B, not the content of folder A itself.

A: Old thread but used this to sync up two 2TB drives.
Using
 $ rsync -cavu --delete /home/user/A/* /home/user/B/

did not work (says "no such directory exists"), but using
 $ rsync -cavu --delete /home/user/A /home/user/B

did work...


text:
Q: what characters should be escaped in sql string parameters I need a complete list of characters that should be escaped in sql string parameters to prevent exceptions. I assume that I need to replace all the offending characters with the escaped version before I pass it to my ObjectDataSource filter parameter.

A: No, the ObjectDataSource will handle all the escaping for you.  Any parametrized query will also require no escaping.

A: As others have pointed out, in 99% of the cases where someone thinks they need to ask this question, they are doing it wrong. Parameterization is the way to go. If you really need to escape yourself, try to find out if your DB access library offers a function for this (for example, MySQL has mysql_real_escape_string).

A: SQL Books online:
Search for String Literals:
String Literals
A string literal consists of zero or more characters surrounded by quotation marks. If a string contains quotation marks, these must be escaped in order for the expression to parse. Any two-byte character except \x0000 is permitted in a string, because the \x0000 character is the null terminator of a string.
Strings can include other characters that require an escape sequence. The following table lists escape sequences for string literals.
\a
 Alert
\b
 Backspace
\f
 Form feed
\n
 New line
\r
 Carriage return
\t
 Horizontal tab
\v
 Vertical tab
\"
 Quotation mark
\
 Backslash
\xhhhh
 Unicode character in hexadecimal notation

A: Here's a way I used to get rid of apostrophes.  You could do the same thing with other offending characters that you run into. (example in VB.Net)
Dim companyFilter = Trim(Me.ddCompany.SelectedValue)

If (Me.ddCompany.SelectedIndex > 0) Then
      filterString += String.Format("LegalName like '{0}'", companyFilter.Replace("'", "''"))
End If

Me.objectDataSource.FilterExpression = filterString

Me.displayGrid.DataBind()


text:
Q: How do I get the sum of items of several document libraries using JavaScript I have document library A, document library B and document library C.
Every library has kinda many items in it. Now I would like to have a counter, which counts the amount of all items and makes a sum out of it. I'm searching for a JavaScript solution for this, so that I can display the amount of items for example in a Content Editor Web Part on any other Site of the same Site Collection.

A: I answered a similar question here.
Your JavaScript would look similar to this (note the use of jQuery):
var count = 0;

$.when(
    RestGet("listname1", "yourErrorDiv", "Couldn't get from listname1"),
    RestGet("listname2", "yourErrorDiv", "Couldn't get from listname2"),
    RestGet("listname3", "yourErrorDiv", "Couldn't get from listname3")).done(function () {
        // Output results to screen, e.g.:
        yourdiv.html(count);
    });

// @listName, the name of the list to pull data from
// @errorDiv, a string containing the ID attribute of the DIV that the error message should be displayed in. If this is ommitted, no error message will be displayed on the page
// @errorMessage, a string containing the error message that should be displayed if the call fails
function RestGet(listName, errorDiv, errorMessage) {
    var dfd = $.Deferred();
    $.ajax({
        url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getbytitle('" + listName + "')/items",
        type: "GET",
        headers: {
            "accept": "application/json;odata=verbose",
        },
        success: function (data) {
            count = count + data.d.results.length;
            dfd.resolve();
        },
        error: function (data) {
            $(String.format("[id='{0}']", errorDiv)).html(message + " Check your browser's console for details of the error.");
            console.log(JSON.stringify(data));
            dfd.reject();
        }
    });
    return dfd;
}


text:
Q: Rails 4: Group by Month In Rails/Ruby, how do I group by and aggregate a measure by month, based on a date column in the table.
I have tried the following technique from Railscasts.
http://railscasts.com/episodes/29-group-by-month
So far, my code look like this
result = result.where(transaction_date: start..Date.current)
result = result.select(:transaction_date, :quantity)
result.group_by { |t| t.transaction_date.beginning_of_month }

I guess, I need a Ruby equivalent of SQL GROUP BY to rollup the quantity.
The SQLite3 version of what I am looking for is:
select strftime('%m', transaction_date)
     , sum(quantity)
from transactions
group by strftime('%m', transaction_date)

A: So this is a good example of why you should use the same database in dev and prod, because you really want to do this in SQL which will be different for the two databases you've specified.  I'll give you the Postgres version.
Assuming your model is called 'Entity' and you're summing an attribute called quantity, you're going to want to do something like this:
Entity
  .select("DATE_TRUNC('month', created_at) AS month, SUM(quantity) AS total_quantity")
  .group('month')

The resulting Entity objects will have virtual attributes 'month' and 'total_quantity' which you can use for your reporting.


text:
Q: Unable to center button: what am I missing? I have a few animated buttons on my page.  I stepped away from this project (and code in general) for a while.  There is 12px of padding that is causing the hamburger to shift to the right, creating a look that is awfully unaligned.  I wouldn't doubt that it is something farther down the line in the code, but I'm just looking for any kind of direction at this point because nothing I try seems to work.  If I am missing parts of the code that would aid in figuring out what the issue is, just say the word and I'll point out what's needed.
I would have posted a screeshot of the issue, but my reputation points are not high enough...  That said, the developer tools are telling me it's ~12px of padding from bootstrap.  More specifically it says:
padding: .25rem .75rem

Could've sworn if I specify something it overwrites bootstrap...
My apologies if this is a total noob question, or asked in a total noob way, I've never posted on stackoverflow before.  I've tried to search for an answer, but I can't find anything that helps.
The button is sitting in a fluid container which is inside a flex-column, but I'm not sure that matters because it appears as though the 12px of padding is the issue.
I've tried position, various versions of align, adjusting the padding/margins/border, and all of the above on various surrounding items: changing anything only makes it worse.  The following is my css:
.nav-btn {
    width: 50px;
    height: 32px;
    position: relative;
    margin: auto;
    padding: auto;
}

.nav-btn span {
    display: block;
    position: absolute;
    margin: auto;
    padding: auto;
    height: 4px;
    width: 80%;
}

Here is some of the html, I tried to trim as much as I could...

                <button class="navbar-toggler flex-column nav-btn">

                </button>

I need the hamburger to align vertically with the rest of the page (and by "the rest of the page" I mean "the rest of the aside class=col-md-3 after stacking itself onto section class=col-md-9 when shrunk down past 768px for the width of any given screen", but TL/DR amiright?).  Any help would be greatly appreciated.  I'm sure there's always a better way to do something too, so by all means; there's always a "better" way to do eavneyrything.


text:
Q: Is saying that $Re(f(z))\to 0, z\to \infty$ "correspondent" to saying $Re(f(z))\le M, \forall z \in \mathbb{C}, M \in \mathbb{R}$ and $ M$ constant? Let $f:\mathbb{C} \to \mathbb{C}$ entire . Is saying that $Re(f(z))\to 0, z\to \infty$ "correspondent" to saying $Re(f(z))\le M, \forall z \in \mathbb{C}, M \in \mathbb{R}$ and $ M$ constant?

A: If $$\lim_{|z|\to\infty } \mbox{Re} (f(z)) =0$$
then $$\mbox{Re} (f(z))$$ is bounded. But this gives a contradiction with  Little Picard Theorem.


text:
Q: bitbucket отменить изменения файла Случайно включил в коммит файл, и запушил на удаленный сервер.
Как мне отменить изменения именно этого файла на удаленном сервере?

A: Необходимо вернуться на коммит без отмены изменений:
git reset --soft HEAD~1

Потом убираем ненужный файл из коммита:
git reset HEAD путь/к/файлу

Снова коммитим
git commit -c ORIG_HEAD

И подменяем изменения на сервере
git push origin <название вашей ветки> --force


text:
Q: Regular expression to remove line breaks I am a complete newbie to Python, and I'm stuck with a regex problem. I'm trying to remove the line break character at the end of each line in a text file, but only if it follows a lowercase letter, i.e. [a-z]. If the end of the line ends in a lower case letter, I want to replace the line break/newline character with a space.
This is what I've got so far:
import re
import sys

textout = open("output.txt","w")
textblock = open(sys.argv[1]).read()
textout.write(re.sub("[a-z]\z","[a-z] ", textblock, re.MULTILINE) )
textout.close()

A: Just as an alternative answer, although it takes more lines, I think the following may be clearer since the regular expression is simpler:
import re
import sys

with open(sys.argv[1]) as ifp:
    with open("output.txt", "w") as ofp:
        for line in ifp:
            if re.search('[a-z]$',line):
                ofp.write(line.rstrip("\n\r")+" ")
            else:
                ofp.write(line)

... and that avoids loading the whole file into a string.  If you want to use fewer lines, but still avoid postive lookbehind, you could do:
import re
import sys

with open(sys.argv[1]) as ifp:
    with open("output.txt", "w") as ofp:
        for line in ifp:
            ofp.write(re.sub('(?m)([a-z])[\r\n]+$','\\1 ',line))

The parts of that regular expression are:

*

*(?m) [turn on multiline matching]

*([a-z]) [match a single lower case character as the first group]

*[\r\n]+ [match one or more of carriage returns or newlines, to cover \n, \r\n and \r]

*$ [match the end of the string]

... and if that matches line, the lowercase letter and line ending are replaced by \\1, which will the lower case letter followed by a space.

A: Try
re.sub(r"(?<=[a-z])\r?\n"," ", textblock)

\Z only matches at the end of the string, after the last linebreak, so it's definitely not what you need here. \z is not recognized by the Python regex engine.
(?<=[a-z]) is a positive lookbehind assertion that checks if the character before the current position is a lowercase ASCII character. Only then the regex engine will try to match a line break.
Also, always use raw strings with regexes. Makes backslashes easier to handle.

A: my point was that avoiding using positive lookbehind might make the code more readable
OK. Though, personally, I don't find it's less readable. It's a matter of taste.
In your EDIT:

*

*First,  (?m) is not necessary since for line in ifp: selects one line at a time and so there is only one newline at the end of each line's string

*Secondly, $ as it is placed, has no utility because it will always match the end of the string line.
Any way, adopting your point of view, I found two manners to avoid the lookbehind assertion:
with open(sys.argv[1]) as ifp:
    with open("output.txt", "w") as ofp:
        for line in ifp:
            ante_newline,lower_last = re.match('(.*?([a-z])?$)',line).groups()
            ofp.write(ante_newline+' ' if lower_last else line)

and
with open(sys.argv[1]) as ifp:
    with open("output.txt", "w") as ofp:
        for line in ifp:
            ofp.write(line.strip('\r\n')+' ' if re.search('[a-z]$',line) else line)

the second one is better: only one line , a simple matching to test, no need of groups(), naturally logic
EDIT: oh I realize that this second code is simply your first code rewritten in one line, Longair


text:
Q: Why aren't my images being displayed in the same row? So I'm using bootstrap and I'm wondering what I'm doing wrong here. I'm trying to get my images all in one row, but they are all over the place and my text isn't showing up correctly either.
matches.html

It's a match!

You and {{ match.username }} like each other!

Start messaging

Keep mingling!

A: repost from comment as requested.
u forgot the  in 2nd col-4.

A: Add this to your CSS:
    .col-4 {
    display: inline-block;
}