text:
Q: C# and SIMD: High and low speedups. What is happening? Introduction of the problem
I am trying to speed up the intersection code of a (2d) ray tracer that I am writing. I am using C# and the System.Numerics library to bring the speed of SIMD instructions.
The problem is that I am getting strange results, with over-the-roof speedups and rather low speedups. My question is, why is one over-the-roof whereas the other is rather low?
Context:

*

*The RayPack struct is a series of (different) rays, packed in Vectors of System.Numerics.

*The BoundingBoxPack and CirclePack struct is a single bb / circle, packed in vectors of System.Numerics.

*The CPU used is an i7-4710HQ (Haswell), with SSE 4.2, AVX(2), and FMA(3) instructions.

*Running in release mode (64 bit). The project runs in .Net Framework 472. No additional options set.

Attempts
I've already tried looking up whether some operations may or may not be properly supported (Take note: these are for c++. https://fgiesen.wordpress.com/2016/04/03/sse-mind-the-gap/ or http://sci.tuomastonteri.fi/programming/sse), but it seems that is not the case because the laptop I work on supports SSE 4.2.
In the current code, the following changes are applied:

*

*Using more proper instructions (packed min, for example).

*Not using the float * vector instruction (causes a lot of additional operations, see the assembly of the original).

Code ... snippets?
Apologies for the large amount of code, but I am not sure how we can discuss this concretely without this amount of code.
Code of Ray -> BoundingBox
public bool CollidesWith(Ray ray, out float t)
{
    // https://gamedev.stackexchange.com/questions/18436/most-efficient-aabb-vs-ray-collision-algorithms
    // r.dir is unit direction vector of ray
    float dirfracx = 1.0f / ray.direction.X;
    float dirfracy = 1.0f / ray.direction.Y;
    // lb is the corner of AABB with minimal coordinates - left bottom, rt is maximal corner
    // r.org is origin of ray
    float t1 = (this.rx.min - ray.origin.X) * dirfracx;
    float t2 = (this.rx.max - ray.origin.X) * dirfracx;
    float t3 = (this.ry.min - ray.origin.Y) * dirfracy;
    float t4 = (this.ry.max - ray.origin.Y) * dirfracy;

    float tmin = Math.Max(Math.Min(t1, t2), Math.Min(t3, t4));
    float tmax = Math.Min(Math.Max(t1, t2), Math.Max(t3, t4));

    // if tmax < 0, ray (line) is intersecting AABB, but the whole AABB is behind us
    if (tmax < 0)
    {
        t = tmax;
        return false;
    }

    // if tmin > tmax, ray doesn't intersect AABB
    if (tmin > tmax)
    {
        t = tmax;
        return false;
    }

    t = tmin;
    return true;
}

Code of RayPack -> BoundingBoxPack
public Vector<int> CollidesWith(ref RayPack ray, out Vector<float> t)
{
    // ------------------------------------------------------- \\
    // compute the collision.                                  \\

    Vector<float> dirfracx = Constants.ones / ray.direction.x;
    Vector<float> dirfracy = Constants.ones / ray.direction.y;

    Vector<float> t1 = (this.rx.min - ray.origin.x) * dirfracx;
    Vector<float> t2 = (this.rx.max - ray.origin.x) * dirfracx;
    Vector<float> t3 = (this.ry.min - ray.origin.y) * dirfracy;
    Vector<float> t4 = (this.ry.max - ray.origin.y) * dirfracy;

    Vector<float> tmin = Vector.Max(Vector.Min(t1, t2), Vector.Min(t3, t4));
    Vector<float> tmax = Vector.Min(Vector.Max(t1, t2), Vector.Max(t3, t4));

    Vector<int> lessThanZeroMask = Vector.GreaterThan(tmax, Constants.zeros);
    Vector<int> greaterMask = Vector.LessThan(tmin, tmax);
    Vector<int> combinedMask = Vector.BitwiseOr(lessThanZeroMask, greaterMask);

    // ------------------------------------------------------- \\
    // Keep track of the t's that collided.                    \\

    t = Vector.ConditionalSelect(combinedMask, tmin, Constants.floatMax);

    return combinedMask;
}

Code of Ray -> Circle
public bool Intersect(Circle other)
{
    // Step 0: Work everything out on paper!

    // Step 1: Gather all the relevant data.
    float ox = this.origin.X;
    float dx = this.direction.X;

    float oy = this.origin.Y;
    float dy = this.direction.Y;

    float x0 = other.origin.X;
    float y0 = other.origin.Y;
    float cr = other.radius;

    // Step 2: compute the substitutions.
    float p = ox - x0;
    float q = oy - y0;

    float r = 2 * p * dx;
    float s = 2 * q * dy;

    // Step 3: compute the substitutions, check if there is a collision.
    float a = dx * dx + dy * dy;
    float b = r + s;
    float c = p * p + q * q - cr * cr;

    float DSqrt = b * b - 4 * a * c;

    // no collision possible! Commented out to make the benchmark more fair
    //if (DSqrt < 0)
    //{ return false; }

    // Step 4: compute the substitutions.
    float D = (float)Math.Sqrt(DSqrt);

    float t0 = (-b + D) / (2 * a);
    float t1 = (-b - D) / (2 * a);

    float ti = Math.Min(t0, t1);
    if(ti > 0 && ti < t)
    {
        t = ti;
        return true;
    }

    return false;
}

Code of RayPack -> CirclePack
Original, unedited, code can be found at: https://pastebin.com/87nYgZrv
public Vector<int> Intersect(CirclePack other)
{
    // ------------------------------------------------------- \\
    // Put all the data on the stack.                          \\

    Vector<float> zeros = Constants.zeros;
    Vector<float> twos = Constants.twos;
    Vector<float> fours = Constants.fours;

    // ------------------------------------------------------- \\
    // Compute whether the ray collides with the circle. This  \\
    // is stored in the 'mask' vector.                         \\

    Vector<float> p = this.origin.x - other.origin.x; ;
    Vector<float> q = this.origin.y - other.origin.y;

    Vector<float> r = twos * p * this.direction.x;
    Vector<float> s = twos * q * this.direction.y; ;

    Vector<float> a = this.direction.x * this.direction.x + this.direction.y * this.direction.y;
    Vector<float> b = r + s;
    Vector<float> c = p * p + q * q - other.radius * other.radius;

    Vector<float> DSqrt = b * b - fours * a * c;

    Vector<int> maskCollision = Vector.GreaterThan(DSqrt, zeros);

    // Commented out to make the benchmark more fair.
    //if (Vector.Dot(maskCollision, maskCollision) == 0)
    //{ return maskCollision; }

    // ------------------------------------------------------- \\
    // Update t if and only if there is a collision. Take      \\
    // note of the conditional where we compute t.             \\

    Vector<float> D = Vector.SquareRoot(DSqrt);

    Vector<float> bMinus = Vector.Negate(b);
    Vector<float> twoA = twos * a;
    Vector<float> t0 = (bMinus + D) / twoA;
    Vector<float> t1 = (bMinus - D) / twoA;
    Vector<float> tm = Vector.ConditionalSelect(Vector.LessThan(t1, t0), t1, t0);

    Vector<int> maskBiggerThanZero = Vector.GreaterThan(tm, zeros);
    Vector<int> maskSmallerThanT = Vector.LessThan(tm, this.t);

    Vector<int> mask = Vector.BitwiseAnd(
        maskCollision,
        Vector.BitwiseAnd(
            maskBiggerThanZero,
            maskSmallerThanT)
            );

    this.t = Vector.ConditionalSelect(
        mask,                                                           // the bit mask that allows us to choose.
        tm,                                                             // the smallest of the t's.
        t);                                                             // if the bit mask is false (0), then we get our original t.

    return mask;
}

Assembly code
These can be found on pastebin. Take note that there is some boilerplate assembly from the benchmark tool. You need to look at the function calls.

*

*BoundingBox(Pack): https://pastebin.com/RYMQdZMh

*Circle(Pack) Tweaked: https://pastebin.com/YZHjc1vY

*Circle(Pack) Original: https://pastebin.com/87nYgZrv
Benchmarking
I've been benchmarking the situation with BenchmarkDotNet.
Results for Circle / CirclePack (updated):

Method
Mean
Error
StdDev

Intersection
9.710 ms
0.0540 ms
0.0505 ms

IntersectionPacked
3.296 ms
0.0055 ms
0.0051 ms

Results for BoundingBox / BoundingBoxPacked:

Method
Mean
Error
StdDev

Intersection
24.269 ms
0.2663 ms
0.2491 ms

IntersectionPacked
1.152 ms
0.0229 ms
0.0264 ms

Due to AVX, a speedup of roughly 6x-8x is expected. The speedup of the boundingbox is significant, whereas the speedup of the circle is rather low.
Revisiting the question at the top: Why is one speedup over-the-roof and the other rather low? And how can the lower of the two (CirclePack) become faster?
Edit(s) with regard to Peter Cordes (comments)

*

*Made the benchmark more fair: the single ray version does not early-branch-out as soon as the ray can no longer collide. Now the speedup is roughly 2.5x.

*Added the assembly code as a separate header.

*With regard to the square root: This does have impact, but not as much as it seems. Removing the vector square root reduces the total time with about 0.3ms. The single ray code now always performs the square root too.

*Question about FMA (Fused Multiply Addition) in C#. I think it does for scalars (see Can C# make use of fused multiply-add?), but I haven't found a similar operation within the System.Numerics.Vector struct.

*About a C# instruction for packed min: Yes it does. Silly me. I even used it already.

A: I am not going to try to answer the question about SIMD speedup, but provide some detailed comments on poor coding in the scalar version that carried over to the vector version, in a way that doesn't fit in an SO comment.
This code in Intersect(Circle) is just absurd:
// Step 3: compute the substitutions, check if there is a collision.
float a = dx * dx + dy * dy;

sum of squares -> a is guaranteed non-negative
float b = r + s;
float c = p * p + q * q - cr * cr;

float DSqrt = b * b - 4 * a * c;

This isn't the square root of D, it's the square of D.
// no collision possible! Commented out to make the benchmark more fair
//if (DSqrt < 0)
//{ return false; }

// Step 4: compute the substitutions.
float D = (float)Math.Sqrt(DSqrt);

sqrt has a limited domain.  Avoiding the call for negative input doesn't just save the average cost of the square root, it prevents you from having to handle NaNs which are very, very slow.
Also, D is non-negative, since Math.Sqrt returns either the positive branch or NaN.
float t0 = (-b + D) / (2 * a);
float t1 = (-b - D) / (2 * a);

The difference between these two is t0 - t1 = D / a.  The ratio of two non-negative variables is also non-negative.  Therefore t1 is never larger.
float ti = Math.Min(t0, t1);

This call always selects t1.  Computing t0 and testing which is larger is a waste.
if(ti > 0 && ti < t)
{
    t = ti;
    return true;
}

Recalling that ti is always t1, and a is non-negative, the first test is equivalent to -b - D > 0 or b < -D.

In the SIMD version, Vector.SquareRoot documentation does not describe the behavior when inputs are negative.  And Vector.LessThan does not describe the behavior when inputs are NaN.


text:
Q: Serializing objects in C# to XML can not change anyType to "Move" I am trying to get the array objects from movelist to be shown as <Move> when serializing the movelist.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Collections;
using System.Xml.Serialization;

namespace Arbitrary.Parties.Moves
{
    [XmlType("MoveList")]
    [XmlInclude(typeof(Move))]
    public class MoveList : IEnumerable
    {
        [XmlArrayItem(typeof(Move))]
        public List<Move> oMoveList = new List<Move>();

        public MoveList()
        {
        }

        public void Add(object o)
        {
            this.oMoveList.Add(o as Move);
        }

        public int Count()
        {
             return oMoveList.Count;
        }

        public IEnumerator GetEnumerator()
        {
            return oMoveList.GetEnumerator();
        }
    }
}

The output when attempting to serialize it shows my move objects as <anyType psi:type="Move"> I would like them to show up as <Move>.
<?xml version="1.0" encoding="utf-16"?>
  <MoveList xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <anyType xsi:type="Move">
    <MoveName element="normal" order="1" rating="green" threshold="0">Wild Swing</MoveName>
    <MoveLevel element="normal" order="1" rating="green" threshold="0">1</MoveLevel>
    <MoveAOEDamage element="normal" link="1" order="1" rating="green" stat="strength" target="relative(1,1|1,0|1,-1)" threshold="0">2</MoveAOEDamage>
    <MoveDescription element="normal" link="1" order="1" rating="green" threshold="0">VARACTINGCHARACTER takes a VARMOVENAME at VARTARGET1, VARTARGET2, VARTARGET3!         </MoveDescription>
    <MoveDescription element="normal" link="1" order="2" rating="green" threshold="0">VARTARGET1 takes VARDAMAGE1 damage!</MoveDescription>
 </anyType>
 <anyType xsi:type="Move">
    <MoveName element="normal" order="1" rating="green" threshold="0">Overpower</MoveName>
    <MoveLevel element="normal" order="1" rating="green" threshold="0">1</MoveLevel>
    <MoveAmplify duration="1" element="normal" link="1" order="1" rating="green" target="enemy primary" threshold="0">25</MoveAmplify>
    <MoveDescription element="normal" link="1" order="1" rating="green" threshold="0">VARACTINGCHARACTER VARMOVENAMEs VARTARGET1's defenses!</MoveDescription>
    <MoveDescription element="normal" link="1" order="2" rating="green" threshold="0">VARTARGET1 takes VARMOVEAMPLIFY1% more damage!</MoveDescription>
 </anyType>
 <anyType xsi:type="Move">
   <MoveName element="normal" order="1" rating="green" threshold="0">Patch Up</MoveName>
   <MoveLevel element="normal" order="1" rating="green" threshold="0">1</MoveLevel>
   <MoveHeal element="normal" link="1" order="1" rating="green" stat="agility" target="self" threshold="0">1</MoveHeal>
   <MoveDescription element="normal" link="1" order="1" rating="green" threshold="0">VARACTINGCHARACTER tries to patch up VARTARGET1's wounds!</MoveDescription>
   <MoveDescription element="normal" link="1" order="2" rating="green" threshold="0">VARTARGET1 is healed for VARHEAL1!</MoveDescription>
 </anyType>
 </MoveList>

A: So I dont really understand why this fixed my issue but here is what my new class looks like. If some one would like to elaborate on why this worked I would be more than happy to mark them with the answer.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Collections;
using System.Xml.Serialization;

namespace Arbitrary.Parties.Moves
{
    [XmlType("MoveList")]
    [XmlInclude(typeof(Move))]
public class MoveList : IEnumerable<Move>
{
    [XmlArrayItem(typeof(Move))]
    public List<Move> oMoveList = new List<Move>();

    public MoveList()
    {
    }

    public void Add(Move move)
    {
        this.oMoveList.Add(move);
    }

    public int Count()
    {
        return oMoveList.Count;
    }

    public IEnumerator<Move> GetEnumerator()
    {
        return oMoveList.GetEnumerator();
    }

    IEnumerator IEnumerable.GetEnumerator()
    {
        return GetEnumerator();
    }
}
}

After adding the IEnumerator IEnumerable.GetEnumerator() I am now seeing the desired results.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Can only log in as "guest" after editing /etc/passwd to change UID to 0 To get superuser access my friend edited his /etc/passwd file, changing the UID and GID to 0, because he read somewhere it should be same as root.
Then when he tried using commands with sudo he started getting a message unknown user 1000 who are you.
I myself haven't used much Linux. I tried editing GRUB parameters to enter as root but I couldn't edit the passwd file. I couldn't even add a new user because the passwd file couldn't be written into.
Now when he chooses Ubuntu in the GRUB menu he only gets the option of a guest login. How can this be resolved?

A: Start the computer and press Left Shift to enter the grub menu and choose Advanced Options for Ubuntu:

In the following menu choose Ubuntu, with Linux xx.xx.x-xx-generic (recovery mode):

Note: I placed here small x for the kernel version numbers so don't get confused, on my system, since it is 17.10 it is 4.13.0-16 but on your system this may differ.

The system will then boot up into the following screen where you should choose enable networking to begin with. It prompts you that it needs to remount the file-system in read-and-write mode, you need to allow this.

Note: This step is easier as remounting the drive into read-write from command line

You will be returned to this selection after that. Now you can choose to go into a root shell. Press Return once to be finally in as root on a writable file-system.
Now enter the following:
cd /etc
nano passwd

Inside the editor navigate to the last line and revert the change. The line should look something like this:
username:x:1000:1000:username,,,:/home/username:/bin/bash

Where username is your username.
After you have made your changes press ctrl+x to exit the program, you are then asked to confirm that you want to write, which you should do by pressing y and finally you are asked for a name to save to. There you don't need to change anything, just press Return.
As final command enter:
reboot

And this should solve your problem. Have fun!
Note: Ah and before I forget, tell your friend to keep his fingers out of the system unless he really knows what he is doing. :)


text:
Q: Unity - Mirror Networking : Player client disconnect after scene changed I'm currently using Mirror Networking to make a multiplayer game. I have a scene when players are all connected, they can choose their characters and set the ready. If all players are ready, I change current scene to arena scene using MyNetworkManager.ServerChangeScene(arenaSceneName). This method sets all player clients as not ready. But After the scene was loaded, my player client is no longer connected to my host and I don't know why.
Can you help me please ?
Thanks a lot for answers.

A: Clients that connect to this server will automatically switch to this scene. This is called automatically if onlineScene or offlineScene are set, but it can be called from user code to switch scenes again while the game is in progress. This automatically sets clients to be not-ready. The clients must call NetworkClient.Ready again to participate in the new scene."
if its not solve problem  can you  give more information about your project
Are you using MatchInterestManager ? This can be lead some problems like yours
Edit 1 -
Maybe the problem was host
can you run your code on server not host
Edit 2 -
i belive your command function runs on client not server because you miss "Cmd" prefix on your command function change it CmdOnAllPlayersReady()

A: public class ReadyPlayerChecker : NetworkBehaviour
{
  public List<PlayerBehaviour> activePlayers;

  public List<PlayerBehaviour> GetActivePlayers()
  {
    return activePlayers;
  }

  // Start is called before the first frame update
  void Start()
  {
    activePlayers = new List<PlayerBehaviour>();
  }

  // Update is called once per frame
  void Update()
  {
    foreach (PlayerBehaviour player in FindObjectsOfType<PlayerBehaviour>
    (true))
    {
       if(!activePlayers.Contains(player))
       {
          activePlayers.Add(player);
       }
    }

    bool allPlayersReady = true;
    foreach (PlayerBehaviour player in activePlayers)
    {
       if (!player.IsReady())
       {
          allPlayersReady = false;
       }
    }
    if (allPlayersReady && activePlayers.Count > 0)
    {
       OnAllPLayersReady();
    }
 }

 [Command]
 public void OnAllPLayersReady()
 {
    GameObject.Find("SceneManager").GetComponent<SceneChanger>
    ().LoadScene("SimpleArena");
 }

}

A: This is my Network Manager settings :

A: I succeed to make the playerclient connected when the scene change. Now, the player prefab for my client is in host view but not in the corresponding client view. Do someone can tell me why ?


text:
Q: nginx lua make an external http call without blocking the request We need to log an event to our event server from nginx when some condition happens. I understand that I could use access_by_lua to make the http call.  Since the event logging can fail or take longer, We don't want to request processing to wait for the http operation to finish.
If I use access by lua, the amount of time takes for logging would be added to the request time.
Is there a way to kick off the event logging process in async process so that request can move on while event logging can take it's time.

A: You can do your usual processing within content_by_lua_* and explicitly specify the end of the response output stream by ngx.eof()
So HTTP request will be processed without any delay.
After that you may do anything you want, use cosocket API or ngx.location.capture() for example
https://github.com/openresty/lua-nginx-module#ngxeof
Here is example from the documentation:
 location = /async {
     keepalive_timeout 0;
     content_by_lua_block {
         ngx.say("got the task!")
         ngx.eof()  -- well written HTTP clients will close the connection at this point
         -- access MySQL, PostgreSQL, Redis, Memcached, and etc here...
     }
 }

A: I do not try it on nginx. But in my app I use separate thread to do all IO and communicate with it using ZeroMQ library.
According doc you can create/run work thread with communication socket in init_by_lua_block and then use it in other parts. But to do this you should remember if request/sec is constantly greater than write/sec then in the end you can get out of memory. Also with ZeromMQ is quite easy make several work threads. Of course in this scenario work thread have no acces to nginx module.
But you can use e.g. LuaSocket or Lua-cURL (last one can be used to perform multiple requests in async mode).
Basic sceleton with single thread.
local thread = function(actor)
  local msg, err while true do
    msg, err = actor:recvx()
    if not msg then break end
    print(msg)
  end
  print('Close thread: ', tostring(err))
end

local zthreads = require "lzmq.threads"
local ztimer   = require "lzmq.timer"
local actor    = zthreads.xactor(thread):start()

for i = 1, 10 do
  actor:send(string.format('message #%d', i))
  ztimer.sleep(1000)
end


text:
Q: "Access denied for user 'username'@'localhost' (using password: YES)" when deploying Rails with Capistrano I am standing up a new Ubuntu server running MySQL. I have Capistrano set up on my development server and am trying to deploy:cold after running deploy:setup. After the deploy script tries to run
executing "cd /home/adm1n/www/knowit/releases/20121112152400 && bundle exec rake RAILS_ENV=production RAILS_GROUPS=assets assets:precompile"

I keep getting this message:
Rake Aborted!
Access denied for user 'specialusername'@'localhost' (using password: YES)
Tasks: TOP => environment

I have 'specialusername' created in my database on the mysql server for both localhost and %.
I removed the empty user ' ' @ localhost row in the user database.
I have added the IP address of the server to my my.cnf file and commented out the 127.0.0.1 line.
Here is my deploy.rb file for production:
production:
adapter: mysql2
encoding: utf8
reconnect: false
database: mydatabasename
username: specialusername
password: crazypassword
socket: /tmp/mysql.sock
pool: 5
timeout: 5000

I think that I may not be understanding how this works. On my Site5 server I have never had to specify which host I was accessing mysql from. But in all my reading it seems that I must specify a specific user@hostname. This makes it a little difficult if I am deploying from many different locations around the country as I travel. OR do I merely need to use the hostname of my laptop regardless of my current IP address? Thanks for any insight and solutions you can provide. I have not found any articles that have provided me precisely what I need to fix this issue.

A: There are two ways to connect to a MySQL server.
First, using a UNIX socket, such as /tmp/mysql.sock, in which case there is no "host", so authentication uses username@localhost. This will work only with connection from the same machine.
Second, using a TCP/IP connection. In this case, the server listen to a specific port on the box running the database, and the way to connect to it is to provide a host + port number. The port number can be optional (the default will be used), and host can be given by hostname or by ip address. This allows to connect locally or remotely.
Note: I have no way to actually verify this (no access to your server), so below is just a possible explanation ...
In mysql -u knowitdbadmin -p -h192.168.0.50, a host (-h) is given, so TCP/IP is used, causing authentication to use username@hostname or username@% rules, but this will not use username@localhost.
In mysql -u knowitdbadmin -p, no host (-h) is given, so the default UNIX socket is used, causing authentication to use username@localhost (and therefore fails).
If you want to disable access using a UNIX socket (/tmp/mysql.sock) and username@localhost, and always use a TCP/IP connection, do it all the way:
* remove grants to username@localhost (done)
* always specify a host/IP (+ port) in configuration files from your application.
I think the problem is with:
socket: /tmp/mysql.sock

try using a hostname + port number instead.
As a side note, if you somehow have SQL access to the database itself, starting with 5.5, a new table performance_schema.host_cache will show you all the reasons a connection is failing, which saves a lot of time when troubleshooting things like this.


text:
Q: Ruby constructor self vs @ I have created folowing simple class:
class Test
  def initialize(a, b)
    @a = a
    @b = b
  end

  def test
    puts @a
  end
end

IS there a way to replace @a with self? Everytime I tried to do this I received an error:
undefined method `a'

The reason I am doing this is because I would like to create a new object with two parameters, and later operate on these parameters like:
d = MyObject('title', 'Author')
d.showAuthor

A: class Test
  attr_accessor :a,:b   #creates methods a,b,a=,b= and @a and @b variables

  def initialize(a, b)
    self.a = a  #calls a=
    self.b = b  #calls b=
  end

  def test
    puts a  #calls method a; self.a would do the same.
  end

  def self.[](a,b)
    new(a,b)
  end
end

This will let you drop the new (but you have to change the parens to square brackets)  So you can call:
d=Test['dog','cat']
d.a  #'dog'

A: It can be done and actually is done for these classes: Array, String, Integer, Float, Rational, Complex and Hash. If you consider the Test class (bad name by the way) of equal importance then consider:
class Test
  def initialize(a, b)
    @a = a
    @b = b
  end

  def test
    puts @a
  end
end

module Kernel
  def Test(*args)
    Test.new(*args)  #that's right, just call new anyway!
  end
end

book = Test('title', 'Author')
book.test # => title

Since the Kernel module is inherited by Object, the global namespace now has a Test method. Don't do this unless you absolutely need it.

A: You need to define accesors, you can do it using attr_*:
class Foo
  attr_accessor :a,:b

  def initialize(a, b)
    self.a = a
    self.b = b
  end
end

Also do not use camelCase in Ruby, there is convention to name:

*

*variables - snake_case

*methods - snake_case

*classes - CapitalCamelCase

*constants - CAPITAL_SNAKE_CASE

A: When you use self.a, Ruby is looking for a method a for the class represented by self, so you get an undefined method error (since you did not define a method called a). You probably are looking for:
class Test
  attr_accessor :a, :b

  def initialize(a, b)
    self.a = a
    self.b = b
  end

  def test
    puts self.a   # "puts a" would be adequate here since it's not ambiguous
  end
end

A: So you need to access your instance variables from outside the instance? You can use attr_accessor to do that:
class Test
  attr_accessor :a
  attr_accessor :b

  def initialize(a, b)
    @a = a
    @b = b
  end
end

t = Test.new(:foo, :bar)
t.a
t.b

attr_accessor let's you both read and write the instance variable. If you only need to read it, you can use attr_reader, and if you only need to change it you can use attr_writer.
More on attribute accessors: https://stackoverflow.com/a/4371458/289219

A: class MyClass

  def initialize(title,author)
    @title = title
    @author = author
  end

  def showAuthor
    @author
  end

end

That will produce...
d = MyClass.new("Grapes of Wrath", "Steinbeck")
d.showAuthor
=> "Steinbeck"


text:
Q: Script is not Finding End of File from Data Input File I hope this makes sense. I have a Python script that reads an input (created from csv with commmas stripped out) file of geographic coordinates and I get this error:
forrtl: severe (24): end of file during read. unit 23 file /home/filename

This seems to relate that the code was expecting an EOF in the input file but this was perhaps absent. Would someone be able to tell how I check for this in the input file and what keystroke(s) are required for an EOF and exactly where this is placed.
this is an extract of the script that creates the file:
f = open(file_ls, "w")
#first line contains 3 integers: the grid dimension, nx and ny, and the total number of snapshots nt
print("%d %d %d" % (np.shape(kxx)[1], np.shape(kxx)[0],     collapse_steps), file(f))
# then it follows by the X coordinates of gridded data (from lines 2 to nx+1), Y coordinates of gridded data (from lines nx+1 to nx+ny+1), and the times at which the snapshots are created (from lines nx+ny+2 to nx+ny+nt+1)
for ii in np.arange(np.shape(kxx)[1]):
        print("%.8f" % (kxx[0, ii]), file(f))
# for ii in arrange(shape(kyy)[0]):
for ii in range(np.shape(kyy)[0] - 1, -1, -1):
print("%.8f" % (kyy[ii, 0]), file(f))
for ii in np.arange(collapse_steps):
mytime = collapse_times[ii] + collapse_starttime
print("%.8f" % mytime, file(f))

# all the nt snapshots of seafloor variation are written into a single column one by one from t=t1 to t=tn; for each snapshot, deltah, the data should be written row by row from the left (i=1) to the right (i=nx) from the bottom (j=1) to the top (j=nx)
# deltaH > 0 corresponds to UPLIFT
# deltaH < 0 corresponds to SUBSIDE

deltaH = elev_t0 - elev_t1
###### time - start of collapse => initial bath => zero difference ??? bit stupid ??? check w/comcot sources
for ii in np.arange(np.shape(elev_t1)[0]):
for jj in np.arange(np.shape(elev_t1)[1]):
    print("%.8f" % 0.0, file(f))

for ii in np.arange(np.shape(elev_t1)[0]):
for jj in np.arange(np.shape(elev_t1)[1]):
    print("%.8f" % (deltaH[ii, jj]), file(f))

f.close()

This is an extract of the input file from 1st line:
1488 903 2    3560181.70300000    3560191.70300000    3560201.70300000    3560211.70300000    3560221.70300000    3560231.70300000    3560241.70300000    3560251.70300000    3560261.70300000    3560271.70300000    3560281.70300000    3560291.70300000    3560301.70300000    3560311.70300000    3560321.70300000    3560331.70300000    3560341.70300000    3560351.70300000    3560361.70300000    3560371.70300000    3560381.70300000    3560391.70300000    3560401.70300000    3560411.70300000    3560421.70300000    3560431.70300000    3560441.70300000    3560451.70300000    3560461.70300000    3560471.70300000    3560481.70300000


text:
Q: rm all files under a directory using python subprocess.call I'm writing a script that will move files into a .trash directory in a user's home folder. I want to add the ability to empty the trash directory by calling rm -rf /home/user/.trash/* using python's subprocess.call()
~$ touch file1
~$ trash file1
['mv', 'file1', '/home/rodney/.trash/']
~$ ls .trash
file1
~$ trash --empty
['rm', '-rf', '/home/rodney/.trash/*']
~$ ls .trash
file1

As you can see the rm command did not remove the contents of the trash. However if I execute the command directly on the command line it works.
~$ rm -rf /home/rodney/.trash/*
~$ ls .trash
~$

The output is from the following code
print(cmd)
subprocess.call(cmd)

What is weird about this is if I exclude the * from the last argument in the cmd list then the subprocess call works but also removes the entire .trash directory. I do not want to delete the .trash directory; only everything under it.
To sum up the question
This works
import subprocess
subprocess.call(['rm', '-rf', '/home/rodney/.trash/'])

This does not
import subprocess
subprocess.call(['rm', '-rf', '/home/rodney/.trash/*'])

Why?

A: Don't shell out.
This uses glob.glob() to identify the files to be removed, and shutil.rmtree() to remove subdirectories.
#!/usr/bin/env python
import os, os.path
import glob
import shutil

def remove_thing(path):
    if os.path.isdir(path):
        shutil.rmtree(path)
    else:
        os.remove(path)

def empty_directory(path):
    for i in glob.glob(os.path.join(path, '*')):
        remove_thing(i)

empty_directory('trash')

Example:
$ tree trash/
trash/
├── aaa
├── bbb
├── ccc
├── ddd
└── sub
    ├── iii
    └── jjj

1 directory, 6 files

$ ./go.py

$ tree trash/
trash/

0 directories, 0 files

A: Shell expand * into file names. You need to pass shell=True keyword argument so that shell will interpret *.
import subprocess
subprocess.call('rm -rf /home/rodney/.trash/*', shell=True)

According to subprocess - Frequently Used Arguments:

If shell is True, the specified command will be executed through the
  shell. This can be useful if you are using Python primarily for the
  enhanced control flow it offers over most system shells and still want
  convenient access to other shell features such as shell pipes,
  filename wildcards, environment variable expansion, and expansion of ~
  to a user's home directory. However, note that Python itself offers
  implementations of many shell-like features (in particular, glob,
  fnmatch, os.walk(), os.path.expandvars(), os.path.expanduser(), and
  shutil).


text:
Q: Expression syntax with if command using curly braces in csh I'm trying to check if a volume is mounted using a csh script.
This code works
#!/bin/csh
set MOUNT_FOLDER = "/Volumes/AAA"
if ( `mount | grep -c "on $MOUNT_FOLDER"` == 0 ) then
    echo Not mounted
else
    echo Mounted
endif

but I would like to try using the syntax with { } and the exit code of grep. I've tried with
if ( { mount | grep -q "on $MOUNT_FOLDER" } ) then
...

but it prints the mount output and it regardless the value of $MOUNT_FOLDER the expression is always true.

A: Unlike in bash, if You have piped commands in csh and want get command exit status You need to encapsulate in sub-shell ( ... | ... )
So following should work for You:
if ( { ( mount | grep -q "on $MOUNT_FOLDER" ) } ) then
...


text:
Q: Join a win7 computer to a domain where domain is in remote location I am in GA and need to have several notebooks join a domain where the Domain Controller is in Texas.  Notebooks are Win7 and Domain Controller is 2008 R2.  I have VPN access to the Domain Controller from the Win7 notebook.

A: VPN in, then add it to the domain. As long as there's no firewall rule blocking you, you should be able to do this. Unless you have a VPN that can connect when Windows starts (as opposed to login), you'll be in a tight spot with logging in to it with anything other than local accounts. You will also have some issues with group policy.
Are you sure this is what you want to do?

A: Consider an appliance that has an always on VPN link that way you are natively "on" the company's network.
That seems like a pretty reasonable price/compromise.  It is only listed as an example, you'll want to do some research first to make sure it would be compliant with the VPN appliance on the other end of the tube.
Like has been mentioned, you don't need to always been on the network to use your AD credentials, but firing up a software VPN client every time you want to work using internal network resources can be a pain.


text:
Q: Avoiding text/characters being chopped off vertically I've constrained the height of an area of text within a thumbnail box in Bootstrap, but in cases where the title is two or more lines, it cuts the last line of the text vertically in half. See here:
http://www.bootply.com/zBXG6in5R5
Since the text box has two font sizes (larger for the title and smaller for the description, which will be dynamic and vary in length), setting the line height will not help. Overflow:hidden does not hide full lines of text, just the part that overflows. Adding text-overflow: ellipsis or like does not stop the half-line from showing up, either.
I have reviewed both of these previous posts, but they don't seem to provide an answer that works for my case:

*

*Can I completely hide lines of text that are half cut off?

*Sentence showing half at end of the div, overflow: hidden is cutting the sentence
I have mentioned Bootstrap in case there is a solution anyone has found in using their thumbnail class, but it's really a more general question. Is there any way to stop chopped line-heights from happening, preferably in CSS?
Thanks!
EDIT: for those who don't want the bootply link, this is my CSS:
.container {
  margin-top: 20px;
}

.thumbnail .caption h3 {
  margin-top: 8px;
  margin-bottom: 8px;
}

.thumbnail-text {
  overflow: hidden;
  height: 160px;
  margin-bottom: 10px;
}

And HTML:

This Title is Two Lines Long

Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore

A: I have written you some very nice jQuery to calculate the number of lines that could be visible and then restrict it to that amount
$(".thumbnail-text").each(function() {
  //start with 0 height
  h=0;
  //calculate height consumed by title
  $(this).find("h3").each(function() {
    h+=$(this).outerHeight();
  });
  //calculate height left over for text
  h=160-h;
  //determine the line height of the text
  lineHeight=parseFloat($(this).find("p").first().css("line-height"));
  //determine the amount of lines that can fit in the height left for the text
  lines=Math.floor(h/lineHeight);
  //set the height of the 'p' to be the lines * lineHeight
  $(this).find("p").first().css("height",(lines*lineHeight)+"px");
});

I also changed your css a bit so now the p element is set to overflow:hidden and has the margin-bottom
.thumbnail-text p {
  overflow: hidden;
  margin-bottom: 10px;
}

Link -> http://www.bootply.com/1pZoRkUHOj
I know it is a very case specific solution but the concept behind the solution will work for anything

A: Similar approach as @MarshallOfSound
$(function(){
  var captionHeight=150; //160px - 10px bottom margin.
  $(".thumbnail-text").each(function(){

      var h3=$(this).find("h3");
      var p=$(this).find("p");

      var titleHeight=h3.outerHeight();
      var lineHeight=p.css("line-height").replace('px','');
      var pHeight=captionHeight-titleHeight;
      var newHeight=Math.floor(pHeight/lineHeight)*lineHeight;

      p.height(newHeight);
  });
});

DEMO
CSS:
.thumbnail-text p {
  overflow:hidden;
}

A: You notice the area that holds the information that has been cut is defined with maximum height of 160px like this;
.thumbnail-text {
    overflow: hidden;
    height: 160px;
    margin-bottom: 10px;
}

change to this;
.thumbnail-text {
    overflow: hidden;
    height: auto;
    margin-bottom: 10px;
}

To make sure all captions are the same size, you could adjust caption to this;
.thumbnail .caption {
    padding: 9px;
    color: rgb(51, 51, 51);
    height: 450px;
}

This will let the area height be defined by the text instead of being cut to fit the area height.

A: just add column-width attribute and give width of that div, it will work.


text:
Q: PlotMarkers problem in ErrorListPlot, Mathematica 10 Bug introduced in 10.0.0, fixed in 10.1

I recently upgraded to Mathematica 10, very excited about the multiple undo function of course.
However I very quickly noticed that if I specify a setting for PlotMarkers in the ErrorListPlot function, the error bars disappear. Even just setting PlotMarkers->Automatic makes the error bars disappear. This was not a problem in Mathematica 9, but appears to be a new 'feature'. Has anyone else noticed this since upgrading, and are there any possible fixes?

A:
Even just setting PlotMarkers->Automatic makes the error bars
  disappear

Fixed in 10.0.2. windows 7, 64 bit

Needs["ErrorBarPlots`"]
ErrorListPlot[{{{1, 1}, ErrorBar[0.2]}, {{2, 2}, ErrorBar[0.1]}, {{3, 4},
   ErrorBar[0.3]}, {{4, 6}, ErrorBar[0.4]}, {{5, 7},
   ErrorBar[0.8]}, {{6, 10}, ErrorBar[0.5]}}, Joined -> True]

ErrorListPlot[{{{1, 1}, ErrorBar[0.2]}, {{2, 2}, ErrorBar[0.1]}, {{3, 4},
   ErrorBar[0.3]}, {{4, 6}, ErrorBar[0.4]}, {{5, 7},
   ErrorBar[0.8]}, {{6, 10}, ErrorBar[0.5]}}, Joined -> True,
   PlotMarkers -> Automatic]

Update
To answer comment below

With Joined -> False the error bars disappear again.

This last part has now been fixed in 10.1 (windows). The bars remain when Joined->False is added

A: I heard from technical support. The problem should be fixed in an upcoming release, but for now there is a temporary fix by inserting Method -> {"OptimizePlotMarkers" -> False} into the ErrorListPlot options.


text:
Q: Viking GPS editor/viewer: how to scroll the map while entering points in a track? I just discovered the (great) Viking application for editing and viewing GPS tracks.
I am struggling to find a way to scroll the map while I am editing?adding points to a track or a route, like in the following case:

I know I can click on the "four arrow" symbol and then move the map, but this will exit the track editing mode --- I have to select "extend track" to continue each time.
I am sure there should be a better method, but I am unable to find it.
Is there a way to scroll the map while in track editing mode?

A: As soon as I posted the question, I found the answer in the here.
Mid-click will center the map again and allow you to continue inputting the track; scrolling with the mouse wheel will change the zoom level.


text:
Q: How does the assignment operator overload resolution work in this example? The result is unexpected for me Here is the code that I do not understand:
class Base
{
public:
    Base(){}

    Base operator=(Base ob2)
    {
        std::cout << "Using Base operator=() " << '\n';
        return *this;
    }
};

class Derived : public Base
{
public:
    Derived(){}
    Derived operator=(Base ob2)
    {
        std::cout << "Using Derived operator=() " << '\n';
        return *this;
    }
};

int main()
{
    Derived derived1, derived2;
    Base base1;

    derived1 = derived2;  // Uses base operator=()

    derived1 = base1;  // Uses derived operator=()

    return 0;
}

What are the language rules that determine, that the first assignment uses the operator of the Base class and the second the operator of the Derived class?
Yes and I know that one normally does not declare an assignment operator like this. That is why I called it accademical.

A: When you create a class, compiler implicitly generates following functions (unless you specify some of them explicitly see http://en.wikipedia.org/wiki/Special_member_functions ):

*

*default constructor

*copy constructor

*move constructor (since c++11)

*copy assignment operator

*move assignment operator (since c++11)

*destructor

In your case copy assignment operator signature is:
struct Foo {
   Foo &operator=( const Foo &f ); // either this
   Foo &operator=( Foo f ); // does not make much sense but will work too
};

When you create assignment operator for class Derived, you do not explicitly replace implicit copy assignment operator but create a new one. To understand the issue easier modify your code to this:
class Derived : public Base
{
public:
    Derived(){}
    Derived &operator=(const Base &ob2)
    {
        std::cout << "Using Derived operator=(Base) " << '\n';
        return *this;
    }
    Derived &operator=(const Derived &ob2)
    {
        std::cout << "Using Derived operator=(Derived) " << '\n';
        return *this;
    }
};

Issue should become obvious.

A: Short version: Overload resolution didn't select Base::operator=(Base). It selected the implicitly declared Derived::operator=(const Derived &), which calls Base::operator=(Base) to copy-assign the base-class subobject.
Long version with standard quotes:
First, copy assignment operator is defined in the standard in §12.8 [class.copy]/p17:

A user-declared copy assignment operator X::operator= is a non-static non-template member function of class X with exactly one parameter of type X, X&, const X&, volatile X& or const volatile X&.

Second, if you don't provide a copy assignment operator, one will always be implicitly declared for you. From §12.8 [class.copy]/p18:

If the class definition does not explicitly declare a copy assignment
  operator, one is declared implicitly. If the class definition declares
  a move constructor or move assignment operator, the implicitly
  declared copy assignment operator is defined as deleted; otherwise, it
  is defined as defaulted (8.4). The latter case is deprecated if the
  class has a user-declared copy constructor or a user-declared
  destructor. The implicitly-declared copy assignment operator for a
  class X will have the form
X& X::operator=(const X&)

if

*

*each direct base class B of X has a copy assignment operator whose parameter is of type const B&, const volatile B& or B, and

*for all the non-static data members of X that are of a class type M (or array thereof), each such class type has a copy assignment
  operator whose parameter is of type const M&, const volatile M& or M.

  Otherwise, the implicitly-declared copy assignment operator will have
  the form
X& X::operator=(X&)

Note that one of the results of these rules is that (§12.8 [class.copy]/p24):

Because a copy/move assignment operator is implicitly declared for a
  class if not declared by the user, a base class copy/move assignment
  operator is always hidden by the corresponding assignment operator of
  a derived class.

In other words, overload resolution can never select the copy assignment operator of Base for an assignment from one Derived to another. It is always hidden and isn't even in the set of candidate functions.
Finally, §12.8 [class.copy]/p28 provides that

The implicitly-defined copy/move assignment operator for a non-union class X performs memberwise copy-/move assignment of its subobjects.

In the case in the question, no copy assignment operator is provided for Derived, so one will be implicitly declared as defaulted (since Derived has no user-declared move constructor or move assignment operator). This implicit copy assignment operator will be selected by overload resolution, and performs copy assignment of, among other things, the base class subobject, which calls the copy assignment operator you defined for Base.


text:
Q: Building an array of deferred functions (promises)? I'm learning promises and I'm trying, in this example, to create an array of promises which I can execute (under native ES6) with Promise.all(...).
The promises should "launch" a function which doubles the number passed to it.
I expected the execution of the promises would be deferred until I had called Promises.all(), but the results are printed immediately. What am I missing??
I want the promises to start when I call them and not as soon as possible (if it wasn't clear)
 var buildPromises = function(numbers) {
    var res = [];
     numbers.forEach(function(num) {
         var p = new Promise(function(resolve, reject) {
             console.log(num * 2);
         });
         res.push(p);
     });
     return res;
 }

 var numbers = [1, 2, 3];
 var p = buildPromises(numbers);

A: The promise executor function (the callback you pass to new Promise()) is designed to be executed immediately, thus you will see all your console.log() statements immediately.
What usually happens in the executor is that you start some async operation such as an ajax request or an async file I/O request and then some time later, that request will call resolve(xxx) to resolve that promise with a value.  What you have now has no async operations, never calls resolve() and really should not be using promises at all since there is no asynchronous activity here.
A promise is not a function.  It is not "executed".  So, you don't really create an array of deferred functions with promises like your question implies.  You could use promises to keep track of some asynchronous operations and you could execute some functions when those promises resolved by attaching listeners to the promise, but you don't really execute promises.
To make a promise that you're creating work, you supply the function that executes as the promise executor callback passed to new Promise(fn).  That's where the executing happens.  The promise itself is just an object that serves as a placeholder for a future value of some asynchronous operation.  The promise value is set when code in the executor calls resolve(someValue).  Or, an error can be indicated by calling reject(someError).  Meanwhile code outside the executor function can then register listeners with .then() or .catch() to listen for a state change in the promise (some future time when the promise fulfills to a value or ends with an error).
So, right after either resolve() or reject() is called, the appropriate event listeners (that were registered with .then() or with .catch()) will trigger, informing the listening code that there is finally a resolution to this promise (either a value or an error).  That listening code can then process that value or error.
Promise.all() accepts an array of promises and returns a new master promise that is rejected when any of the array of promises rejects or is resolved with an array of values when all the array of promises are resolved.  It watches all those other promises and essentially gives you a summary of them all.
To simulate an async operation, we could put all your operations inside a setTimeout() and then call resolve() like this runnable snippet:

 var buildPromises = function (numbers) {
     var res = [];
     numbers.forEach(function (num) {
         var p = new Promise(function (resolve, reject) {
             // this is called immediately and it starts
             // an asynchronous operation that will finish later
             setTimeout(function () {
                 var result = num * 2;
                 console.log("individual:", result);
                 // resolve the promise with our result
                 resolve(result);
             }, Math.floor(Math.random() * 500) + 500);
         });
         res.push(p);
     });
     return Promise.all(res);
 }

 var numbers = [1, 2, 3, 4, 5];
 buildPromises(numbers).then(function (results) {
     console.log("group: ", JSON.stringify(results));
 });

In the results here after running this snippet, notice that the individual console.log() statements may be in any order (since async operations are usually unpredictable in timing), but the Promise.all() group results are always kept in the original order of the promises in the array.  That is another service that Promise.all() provides.

Also, it saves code to use .map() to build your array of promises since you're traversing an array and building a new array with one promise per element which is exactly what .map() was designed for.  You can do that like this:

var buildPromises = function (numbers) {
    return Promise.all(numbers.map(function (num) {
        return new Promise(function (resolve, reject) {
            setTimeout(function () {
                var result = num * 2;
                console.log("individual:", result);
                resolve(result);
            }, Math.floor(Math.random() * 500) + 500);
        });
    }));
}

var numbers = [1, 2, 3, 4, 5];
buildPromises(numbers).then(function (results) {
     console.log("group: ", JSON.stringify(results));
});

A: What you're missing is that Promise is the result of an action and not an action itself. A Promise is merely an object you can hold on to now, while you wait for the value in the future.
The action will be performed as soon as you call the function which returns the Promise. If you want to delay that, delay calling the function.


text:
Q: How does USB take care of retransmissions? I'm trying to understand the USB protocol at the packet level. In particular, I'm interested in how USB handles retransmission of bulk transfers in case of an error. For reference:
https://www.beyondlogic.org/usbnutshell/usb3.shtml
https://www.beyondlogic.org/usbnutshell/usb4.shtml#Bulk
Let's discuss normal transmission from peripheral to host first: The host sends an IN token to the peripheral. The peripheral responds with a data packet. Then the host sends an ACK. Due to the ACK, the peripheral knows that the data was received correctly by the host and the next IN token will be answered with a new data packet by the peripheral.
Now consider that something goes wrong. Assume, that the data packet is corrupted. So the host discards the data packet and does not send an ACK. When the peripheral receives the next IN token, it simply sends the previous data packet again. Is that correct?
Now consider the more tricky case that the data packet arrives correctly at the host, however the ACK sent by the host is corrupted. So the host received the data correctly, but the peripheral doesn't know about it because the ACK was not received correctly. To the best of my knowledge, the ACK is never retransmitted by the host.
I believe that the next IN token sent by the host is answered with a retransmission of the data packet. However, how does the host tell that it is the same data package? I don't find an explanation anywhere.
Is it related to the fact that there are two PID values for data packets (DATA0 and DATA1)?

A: The answer to your first question is yes; the device only considers the bulk IN packet to be successfully sent if it gets an ACK packet.
And for your second question, you guessed it correctly: the data toggle bit switches between 0 and 1, so if the host gets the same data packet two times in a row, it can tell that the second one should be ignored since it will have the same data toggle value as the one before it.
For more information, see section 8.6, "Data Toggle Synchronization and Retry" in the USB 2.0 specification.


text:
Q: The CLR has been unable to transition from COM context X to COM context Y for 60 seconds I got this frequently error on my application that takes the sound as byte from microphone  to stored in the soundfile (.wav).
""The CLR has been unable to transition from COM context 0x686670 to COM context 0x686898 for 60 seconds. The thread that owns the destination context/apartment is most likely either doing a non pumping wait or processing a very long running operation without pumping Windows messages. This situation generally has a negative performance impact and may even lead to the application becoming non responsive or memory usage accumulating continually over time. To avoid this problem, all single threaded apartment (STA) threads should use pumping wait primitives (such as CoWaitForMultipleHandles) and routinely pump messages during long running operations.""
What is the mainly cause of this error?
Why is this error mainly occurs?
What is the solution for this type of error??
Does this error leads to "An unhandled exception of type 'System.StackOverflowException' occurred in mscorlib.dll"??
And how is this "An unhandled exception of type 'System.StackOverflowException' occurred in mscorlib.dll" error occured too??
Thanx in advance.


text:
Q: Returning results from a loop in another excel sheet in the same workbook What am I defining wrong?
I constructed a For Each ..Next loop. I had a function applied to it, and I tried to return the results in a table on a next sheet in my Excel Workbook.
However, I keep on getting the Error 1004, Object or Application Run-Time error whenever I apply this: Note that table 1 is a ReDim table1(Nb_Rows - 1, 6)
    Worksheets("Sheet2").Range("A2", Range("A2").Offset(Nb_Rows - 1, 6)).Value = Table1

However, if I apply THIS code, I get no error. Yet, I cannot use this one because it requires a manual selection. How can I deal with this?
   Worksheets("Sheet2").Range(Selection, Selection.Offset(Nb_Rows -1, 6)).Value = Table1

I also tried this way:
    Worksheets("Sheet2").Activate
    Range("A2").Select
    Range(Selection, Selection.Offset(Nb_Rows - 1, 6)).Value = Table1

And it didn't work.. :(

A: And what about:
    Worksheets("Sheet2").Range(Range("A2"), Range("A2").Offset(Nb_Rows - 1, 6)).Value = Table1


text:
Q: Align the form in visual studio editor I cant find where to align the form in the visual studio editor and its very annoying to watch in a 28'' monitor.
I've searched for tutorials but couldn't find nothing but to align the form when executed as a program but that's not what I want.


text:
Q: Is PS4 Manual Eject Screw supposed to tighten My PS4 works fine 9/10 of the time, but at some point, usually ingame or at night, it will eject the disc in it (if any) and then the ejection engine will start spinning like crazy and the console will triple beep repeatedly.
It seems to go away for a while (a day, usually) if I unplug the PS4 and try to turn it on several times, but sometimes it doesn't work and I have to resort to other methods. On the web I found "remove rubber foot", tried, didn't change a thing.
Eventually, on Sony's site, I found "tighten manual eject screw" I did that and it seemed to work, for a while, after which the PS4 had the issue again. I did it again and it only worked for a shorter time before "screwing up" again.
One thing I noticed is that the screw does not actually tighten. Instead, it spins infinitely. I have never overtightened the screw, damaged or modified my PS4 or even done anything weird with my PS4.
Online, other users too seem to have had this problem.
Sony refuses to repair the PS4 out of warranty and, for the same price as a new slim, wants to give me an old refurbished PS4 with only 6 months warranty. I am totally not going to do this nor buy another PS4: I only play on PS4 for the few exclusives as I have switched to PC. What I'd like to know is if it is normal for the "screw" to be like this (which means my problem cannot be solved) or if maybe I could have the screw replaced by a third party and maybe my issue could be solved

A: I ran into this issue about a month after I bought my console. I tried everything, same as you; adjusted that rubber foot, twisted that internal screw, but nothing helped. If memory serves, that screw will not actually tighten, or at least I did not have the patience to see if it would. The solutions you have found online do work for some people, but in my case (and I'm guessing yours), a replacement was needed.
Unfortunately, you're out on a warranty, and a refurb isn't quite worth it in my opinion. The only recommendation I can make is to maybe get a base for the PS4 so that it can sit on its side, taking pressure off the rubber foot and disc-eject sensor. I used this for a long time until my setup needed the PS4 in a different spot for WiFi connectivity.
Otherwise, it may be best to wait for a sale to get a new PS4 for cheaper than a refurbished device.

A: I bought a PS4 with the same issue. Their solution was to actually disengage the button itself. And just use the menu eject.


text:
Q: Merge two TFS branches with git tfs I'm using git-tfs, and I was wondering if it is possible to merge two TFS branches using git-tfs. I have two branches $/MyCompany/Dev & $/MyCompany/Release-3.3. Release-3.3 originates from the Dev branch. Both are checked out as different git repositories using git tfs.
I'd like to re-incorporate the changes back into the Dev branch. Can this be achieved with git-tfs or will I have to resort to trying to do it using TFS tools?

A: I found an awesome, if hacky way of doing this. Git tfs manages it's awareness of areas of TFS using git config. Specifically 3 attributes per remote; url, repository and fetch, for example:
tfs-remote.default.url=http://tfsserver:8080/tfs/collection
tfs-remote.default.repository=$/Product/Branch/Component
tfs-remote.default.fetch=refs/remotes/default/master

You can add another remote by setting these 3 properties again with a different name to default. Eg:
tfs-remote.feature_branch.url=http://tfsserver:8080/tfs/collection
tfs-remote.feature_branch.repository=$/Product/FeatureBranch/Component
tfs-remote.feature_branch.fetch=refs/remotes/default/feature_branch

You may need to issue git tfs bootstrap now.
You can then issue:
git tfs fetch -i feature_branch

Then merge the commits using:
git merge tfs/feature_branch

A: Since git-tfs 0.16, you can manage TFS branches (with branch command) so you can now easily init existing branch, create one and merge TFS branches!
https://github.com/git-tfs/git-tfs/blob/master/doc/commands/branch.md#initialize-an-existing-tfs-branch
And since the release 0.19, you can do a git merge of 2 TFS branches and checkin it in TFS (with rcheckin) and it will be checked in as a merge changeset : https://github.com/git-tfs/git-tfs/blob/master/doc/commands/rcheckin.md#checkin-a-merge-changeset
The only limitation (due to TFS) is that all the commits should have been already checked in TFS before doing your merge with git and check it in TFS.
So you can now merge more easily than with 2TFS  branches and check them in...

A: I'm not a git-tfs user, but I have done this with git-svn in the past (which I believe has a similar approach).  I think your main issue is that you have two repos.  If you add both remote branches to the same git repo, you should then be able to do a local merge, do a local commit and then push that commit to TFS.
HTH


text:
Q: Let G be a finite graph. Can G have a subgraph H (H is supposed to be different from G) so that G and H are isomorphic?
Let G be a finite graph. Can G have a subgraph H (H is supposed to be different from G) so that G and H are isomorphic?

Stuck on this question. Don't know how to approach this question. Any answer would be much appreciated!

A: The subgraph $H$ must have strictly fewer edges than $G$, otherwise $H=G$. But two graphs that are isomorphic must have the same number of edges. Hence $H$ cannot be isomorphic to $G$.
The finiteness restriction is needed here, otherwise $G$ could be an infinite path $0-1-2-3\cdots$ and $H$ could be $1-2-3\cdots$, providing an example.


text:
Q: Parsing a filename and adding it to a text file I have a directory full of files with the date they were created in the filename (ie "mvr-20160420.csv").  The files contain comma delimited data that I'm combining into a single text file.  I'm trying to figure out how to add the date portion of each file to the data.  I'm able to read the files, but not the filenames.
Sample file for mvr-20160420.csv:
client employee id,first name,last name,points
14204,Bob,Smith,5

I have a Korn script and just trying to add the filename to the data:
for file in $Folder/path/burnsmcd-mvr*.csv
do
FN=file

if [ $FIRSTTIME = $STATUS_OK ]
then
  FIRSTTIME=$STATUS_NOT_OK
  cat $file | strings | sort -n | awk 'BEGIN{FS=","}{OFS="|"}{if ( $1 ~ /^[0-9]+$/) print "ADMVR", $1, $2, $3, $4, $FN}' > $Folder/path/ext_test.txt
else
  cat $file | strings | sort -n | awk 'BEGIN{FS=","}{OFS="|"}{if ( $1 ~ /^[0-9]+$/) print "ADMVR", $1, $2, $3, $4, $FN}' >> $Folder/path/ext_test.txt
fi
done

So my output ext_test.txt looks like this:
14204|Bob|Smith|5|14204,Bob,Smith,5

I can't seem to add the filename.  I  also need to extract the date portion.

A: $ awk 'BEGIN {OFS=","}
      { split (FILENAME, parts, "[-.]"); print FILENAME, parts[2], $0 }' \
      mrv-20161225.csv
mrv-20161225.csv,20161225,client employee id,first name,last name,points
mrv-20161225.csv,20161225,14204,Bob,Smith,5

A morning without awk is like a long day at work.  ;-)


text:
Q: What is this UI Element? Is this a built in UI Element? I see it used in the address book, mail app, and other 3rd party apps but I can't find the object in Xcode anywhere...

A: That is a UIActionSheet. Basically, it's intended to replace what would be commonly accomplished with a Combo Box in a traditional setting.

A: This is called a UIActionSheet you usually use it to present a user with a set of options for an action. You can use it to warn a user about a potentially dangerous task such as deleting something like a photo. you can read more about it here:
http://developer.apple.com/library/ios/#documentation/uikit/reference/UIActionSheet_Class/Reference/Reference.html


text:
Q: Mock Generic Repository with Moq I'm using Moq and trying to mock a IDummyRepository which implements IGenericRepository interface, and need to verify a call for the Add method of IGenericRepository. But with the example code below I'm getting a MockException.
If I replace the IGenericRepository in the ServiceDummy for the IDummyRepository the test works, but not in the way I need.
How this can work?
[TestClass]
public class DummyServiceSpec
{
    protected DummyService service;
    protected DummyModel model;

    [TestClass]
    public class Work : DummyServiceSpec
    {
        [TestMethod]
        public void ExpectToWork()
        {
            var repositoryMock = new Mock<IDummyRepository>();
            var serviceDummy = new ServiceDummy(repositoryMock.Object);
            var entity = new Dummy { DummyString = "DummyString" };

            serviceDummy.Add(entity);

            repositoryMock.Verify(r => r.Add(It.IsAny<Dummy>()), Times.AtLeastOnce());
        }
    }
}

public class ServiceDummy
{
    protected IGenericRepository<Guid, Dummy> dummyRepository;

    public ServiceDummy(IDummyRepository dummyRepository)
    {
        this.dummyRepository = dummyRepository;
    }

    public virtual void Add(Dummy entity)
    {
        this.dummyRepository.Add(entity);
    }
}

A: Try moving your code of repository expectations to your Moq setup of the repository. Since the Add() method is a void, there is no result to check but you can make it verifiable to test that it is actually called.
[TestMethod]
public void ExpectToWork()
{
    var repositoryMock = new Mock<IDummyRepository>();
    var serviceDummy = new ServiceDummy(repositoryMock.Object);
    var entity = new Dummy { DummyString = "DummyString" };

    repositoryMock.Setup(i => i.Add(It.IsAny<Dummy>())).Verifiable();

    serviceDummy.Add(entity);
    repositoryMock.Verify();
 }

A: Sorry, I just found the problem, it was a bug in my GenericRepository code.


text:
Q: C++ error C 2664 Cannot convert parameter from "IID *" to "const IID&" My code:
IID              xIID_ICMLuaUtil;

if (IIDFromString(T_IID_ICMLuaUtil, &xIID_ICMLuaUtil) != S_OK) {
        break;
}

r = ucmMasqueradedCoGetObjectElevate(
        T_CLSID_CMSTPLUA,
        CLSCTX_LOCAL_SERVER,
        &xIID_ICMLuaUtil,
        NULL);

ucmMasqueradedCoGetObjectElevate function :
HRESULT ucmMasqueradedCoGetObjectElevate(
_In_ LPWSTR clsid,
_In_ DWORD dwClassContext,
_In_ REFIID riid,
_Outptr_ void **ppv);

REFIID :
#define REFIID const IID * __MIDL_CONST
IN c:\Program Files (x86)\Windows Kits\8.1\Include\shared\guiddef.h line 119

Error:
Error C2664 "HRESULT ucmMasqueradedCoGetObjectElevate(LPWSTR, DWORD, const IID &, void **)": Cannot convert parameter 3 from "IID *" to "const IID &" test2 c:\users\son\desktop\60\test2\ Api.c 62
I use stackoverflow for the first time, I am sorry for my incompleteness!

A: Remove the & operator from &xIID_ICMLuaUtil in the call to ucmMasqueradedCoGetObjectElevate.
As shown by the error message, that parameter is a reference to IID (not a REFIID).


text:
Q: system test - how to test database without saving data actually I currently use   using (TransactionScope scope = new TransactionScope()) for
 c# testing database insertion so that it doesn't actually save into database for unit testing. But for system testing which I am currently testing on different server to test the status code for different scenarios. Each time I run the test, it is actually saving data into database and next time I ran the test it is failing as it is duplicate record. I tried to use transaction scope , but doesn't seem to work. Please help.


text:
Q: Firefox: Bookmarks on my own server? I don't trust other servers (even Firefox's ;-)) and would like to store my bookmarks on my own server in order to synchronize them on different devices/PCs. So, similar to the "Sync" function within Firefox.
In the best case, there would also be a web interface to browse/manage bookmarks on my own server.
I think there is no add-on or extension for this, only different providers who store bookmarks on their servers.
How would be the best way to get this done?

A: This sounds the best case for wallabag. You can even have it in a docker container.

wallabag is a self hostable application for saving web pages: Save and classify articles. Read them later. Freely.

There is also an addon, wallabagger which you can link it to your own server.
References:
https://github.com/wallabag
https://wallabag.org/en/news/wallabagger-howto

A: This post is your answer:
https://mozilla-services.readthedocs.io/en/latest/howtos/run-sync-1.5.html
I wrote a post some time ago, about this theme (in Spanish), when the Addon "Xmarks", still permit configure a custom server. It was very easy, you only need a webdav server, and you can sync Bookmars between this, and your devices with Firefox. All right. But "Xmarks", removed the option. Thank you guys!, and now, I think we don't have any addon with this feature.
I'll try to do it with the tutorial of top answer, but its more complicated than older option.


text:
Q: Changing The MahApps Metro Theme I know that the MahApps metro theme comes with "themes" (colour sets), but I don't know how to change them from the default settings in my WPF application.
I have followed the beginners tutorial at MahApps.Metro Documentation (including adding the resource libraries at the top of the page), but it makes no mention about changing the theme.
The component/Styles/Colours.xaml file has the comment "from the cosmopolitan theme pack", which may be a helpful clue to someone better versed in WPF design than me.
I'm talking about an app-wide theme change, not an individual control.

A: If you want to change the default colour scheme, just change which colour resource file is loaded.
from Blue:
    <ResourceDictionary Source="pack://application:,,,/MahApps.Metro;component/Styles/Accents/Blue.xaml" />

to Red:
    <ResourceDictionary Source="pack://application:,,,/MahApps.Metro;component/Styles/Accents/Red.xaml" />

You can also change programatically (once you've loaded every colour resource file) using ThemeManager.ChangeTheme().


text:
Q: How can I share a TFS task board outside of TFS? It's pretty straight forward. We have a local TFS installation and lots of people (including stakeholders) are outside our local office. As it stands, for me to be able to allow stakeholders to see the task board I have to add them to our local AD (AAD is not sufficient) and then add permissions to TFS. While this is understandably a secure way of doing it, I would hope there would have to be a way to just simply "share" a task board. Maybe a Link or iframe on a local website. Anything ideas are welcome.
I have tried to extend TFS by using Aha, Jira and solutions like that, but even those cannot simply take said task board and display it over here.

A: You can't. There are no public projects and no anonymous access.
VSTS has public projects in preview, but you'd have to migrate from TFS to VSTS in order to make use of that.


text:
Q: WIX Create folder from values present in file during installation I am a Wix novice, first of all. I am trying to create an installer using Wix. I am using Visual Studio 2012 and I have Wix toolkit installed.
In my installer I have a version.ini file which contains the version information. During each build, the version.ini file will be updated. I need to create a folder using the version specified in version.ini and copy some files to that folder created during installation. I prefer the version.ini should not be deployed during installation.
I went through some threads here. What I got is since the version.ini file is present during build time, we need to use it rather than creating custom actions. But I don't know how.
Can someone help? I really appreciate if you could provide sample code.
Thanks,
ssn


text:
Q: ASP.NET core not encoding input value on post back I have ASP.NET Core with NET 5 and Razor View. from doc prevent XSS

The Razor engine used in MVC automatically encodes all output sourced
from variables,You must ensure that you only use @ in an HTML context,
not when attempting to insert untrusted input directly into
JavaScript. Tag helpers will also encode input you use in tag
parameters.

I have the following code
Model
public class HomeModel
{
    public int Id { get; set; }
}

Controller
    [HttpPost]
    [Route("items/{id}/edit")]
    public ActionResult Edit([FromRoute(Name = "id")] int id, HomeModel model)
    {
        if (!ModelState.IsValid)
        {
            return View("Index", model);
        }

        //do something

        return RedirectToAction("Index");
    }

Razor
@model XSSTest.Models.HomeModel
@{
    ViewData["Title"] = "Home Page";
}

 <form method="post" id="myform">
        <input type="hidden" asp-for="Id" />
        @DateTime.Now;
    </form>
<button type="submit" form="myform" asp-action="Edit" asp-controller="Home" asp-route-id="@Model.Id">Save</button>

After the page is rendered, using dev tools in Chrome browser I changed the value of ID to some malicious script and click submit.
<input type="hidden" data-val="true" data-val-required="The Id field is required." id="Id" name="Id" value="">
On server, the model binding fails as expected and now ModelState is not valid. ID value  set to default 0 by the modelbinder. Without any further processing the edit action method returns the View with Model.
On client side the browser shows error The value '' is not valid for Id. (This is all expected behavior)
However the value attribute of the input field still shows the malicious script I entered (without encoding)
<input type="hidden" class="input-validation-error" data-val="true" data-val-required="The Id field is required." id="Id" name="Id" value="">
(I understand why ID value is not refreshed to 0, because I am not clearing the ModelState so it shows the original value.)
Questions
1>Since the value is not encoded on post back, Is this a valid XSS attack? (Note that the alert is not displayed on post back)
2>When .NET Core encodes output HTML, will it use Model.ID or ID value from the ModelState?
The point of doing this exercise, the DAST scanner (Acunetix) reporting this behavior as XSS attack. But this is a normal flow for any ASP.NET application. It does not make sense to clear ModelState on POST requests because that will clear errors as well.
**UPDATE 1 **
I was wrong, the value is indeed encoded in the output. In chrome dev tools I was looking under the elements tab which shows the rendered html.
But When I verified the Response under Network tab, the value is encoded.
So I am not sure why Acunetix shows this as XSS


text:
Q: Github Repository Languages used not showing correct In my GitHub repository tech stack used is not showing correctly, as you can see it just shows CSS wherein its a React app so it should show JavaScript as well
https://i.stack.imgur.com/CzPrK.png


text:
Q: A greedy algorithm about assigning time to tasks to Maximize the total time I'm given a number of tasks, each of them has a start time and an end time. I should arrange my day to do them.
Requirements are:

*

*Can't do more than one tasks at any time.

*Can't divide tasks

*Maximize the total working time

My solution to this is:

*

*Rank all tasks by their number of overlaps with all others from the least to most.

*Select the tasks from the left to right in the above ranked list to do. Make sure that any tasks to choose don't have overlaps with tasks that have been chosen.

*Calculate the time.

Is this correct? I can't prove it. Does anyone have better idea?

A: The Activity Selection problem maximises the total number of tasks using a greedy algorithm.
However, your problem is slightly different as you wish to maximise the total time.
You can solve this by solving the shortest path problem in a graph where you have a node for each task.
Make edges from task A to task B if A finishes before B, and set the weight on the edge to the amount of time between the end of A and the start of B.
Make an extra start node that connects to all tasks (with weight equal to the start time of the task), and an extra end node that all tasks connect to (with weight equal to the time between the end of the task and the end of the day).
Note that the weight on each edge corresponds to the amount of time you waste not working if you use that edge.
Computing the shortest path on this graph (e.g. with Dijkstra's algorithm) will tell you the tasks to do with minimum wasted time - which is the same as maximising the work time.
Example

In this graph the shortest path is Start->A->C->End with weight 3, corresponding to doing job A followed by job C, and only wasting 3 hours not working.

A: edit: My mistake, my greedy algorithm solves for maximizing the number of jobs completed which is different than the maximum job time.  I'll leave my answer here in case people are curious though.
There are some decent slides for Greedy Scheduling here: Greedy Scheduling
Basically rather than ranking by the number of overlaps, it's best to rank by the order of finish times.  By finish time, I don't mean how long it will take to complete, but when it will complete.  With the jobs ranked this way, you iterate through until you find a job with start time >= to the current time and then perform that job.  Then you repeat until you have no time left.
edit: So this algorithm is labeled greedy because you are always selecting as your next job the one which has the earliest completion time and valid start time.


text:
Q: Git : not ignored file in two branch needs to be different I want to ask about what your approach looks like handling a situation like this: I have this setting file mongoid.yml, and I have two branches of the same project : master and dev. I haven't put mongoid.yml into gitignore because I need it to be in the commit when I push both branches. But whenever I edit it in either branch, for example, if I edited it in the dev branch, it shows up in git status, when I commit then merge dev to master, the master branch's mongoid is now looking like the one in dev. I need them to be different. How would you approach this? thanks!

A: You want to make a dev branch and then check it out. Change the config file to what you need it to be. Switch back to the other branch.
git merge -s ours dev

This will ignore what you did in the dev branch, but still mark in the history as if those changes were already merged. From now on, when you merge to and from the dev branch, your config will stay as what you need it to be. This is the proper way to set up a development branch.
Hope this helps.

A: You could keep your changes to the file in a separate commit always on top of master, and merge its parent.
For example:

*

*you work on dev,

*if you ever have to change mongoid.yml, you make commits with only this file changed,

*before you switch to master, you git rebase -i master and move your mongoid.yml commits to the bottom (and squash them all with the first one if there's more than one),

*then you switch to master and merge the parent of dev: git merge dev^
It's a little work on each merge and you loose the history of you changes on mongoid.yml in the dev branch, but it should work.

A: You can use a different merge strategy on your file to prevent the merge.
Create a .gitattributes file with:
mongoid.yml merge=ours

Then when this file conflicts during a merge, the old one will be kept.
More infos here and here.


text:
Q: PHP MySQL Search with string & location distance I have table user with with columns latitude and longitude.
Another table products with  columns title description
I am trying to create a PHP search form where the results are filtered by the keywords/string input and location input.
So essentially, I'm trying to query the products table to find matches, while querying the users table for proximity. You search for a product, and the result shows the stores that has the products nearest to you.
This is the query I have for matching keywords/strings
SELECT * FROM products WHERE MATCH(item_name,item_desc) AGAINST(:searchstr IN BOOLEAN MODE) AND public = 1
I was trying to using foreign keys/referencing the lat/lng column in user table in products table but I had no luck.
"SELECT *,
        truncate((degrees(acos(
        sin(radians(lat))
        * sin( radians(:lat))
        + cos(radians(lat))
        * cos( radians(:lat))
        * cos( radians(lng - :lng) )
        ) ) * 69.09),1) as distance FROM users, product
WHERE MATCH(product.item_name,product.item_desc) AGAINST(:searchstr IN BOOLEAN MODE)
AND public = 1";

Any idea how I can do this?
Thanks
Edit: I'm already using a foreign key to connect each product with specific users (user.id = products.user_id)

A: If I'm understanding correctly, you need to JOIN the two tables together.  Try this:
"SELECT *,
    truncate((degrees(acos(
    sin(radians(lat))
    * sin( radians(:lat))
    + cos(radians(lat))
    * cos( radians(:lat))
    * cos( radians(lng - :lng) )
    ) ) * 69.09),1) as distance FROM users
JOIN product ON product.user_id = users.id
WHERE MATCH(product.item_name,product.item_desc) AGAINST(:searchstr IN BOOLEAN MODE)
AND public = 1
ORDER BY distance";

Also, make sure you have the correct table names.  In your question you say "user" and "products", but in your query you have "users" and "product".


text:
Q: Basic svn merge/switch I'm cautiously playing with svn merge on a large codebase, and I'm not too familiar with this command. Is the following the right way to proceed:

*

*I had a trunk

*I did svn cp trunk branch and then did many modifications in the branch

*then I did a merge by first copying my branch and then merging the trunk (which had recent modifications) into it: svn cp branch both; svn merge http://.../trunk both

*I fixed the conflicts and tested the merged version

Now I want to replace the trunk with the merged version. Is svn mv trunk oldtrunk; svn mv both trunk the proper way to proceed ? I don't understand what 'switch' really does.


text:
Q: SQL Server Null Logical XOR I'm creating a constraint on a (Microsoft) Sql Server 2008 table.  I have two columns that are different datatypes.  One column must be null at all times, but not both (A logical exclusive OR/XOR).  I have a working expression currently.
(@a is null or @b is null) and not (@a is null and @b is null)

My question is Is there a cleaner or shorter way to write this code?
To test it you can use this code...
declare @a int
declare @b varchar(5)

set @a=1
set @b='XXXXX'

if (@a is null or @b is null) and not (@a is null and @b is null)
  select 'pass'
else
  select 'fail'

A: I would prefer
if (@a is null and @b is not null) or (@a is not null and @b is null)

It is a little clearer in my opinion

A: OK, here is a (albeit stupid) suggestion if you are working with all strings. And it scales to multiples greater than 2 where you want a particular number of non-nulls. Again, its stupid and not really shorter but it was too fun to pass up mentioning...
where LEN(ISNULL(right(@a+'x',1),'')+ISNULL(right(@b+'x',1),'')) = 1

To make it work with your stuff, You'd have to CAST the [int], I suppose.  Doing string "surgery" in the where clause before matching is evil and liable to be real slow. But if you had 6 columns and needed exactly 1 to be not-null this trick would scale up.
Basically, we're using LEN to count the not-nulls. The +'x' ensures that you don't count a '' as null. You could leave that off when testing [char] columns.


text:
Q: why is the result of "windowed" different? Code with List:
println(listOf(1, 2, 3).windowed(1))
println(listOf(1, 2, 3).windowed(1) { it })
println(listOf(1, 2, 3).windowed(1) { it.toList() })

Result:
[[1], [2], [3]]
[[3], [3], [3]]  //why is there 3 everywhere?
[[1], [2], [3]]

Code with Sequence:
println(sequenceOf(1, 2, 3).windowed(1).toList())
println(sequenceOf(1, 2, 3).windowed(1) { it }.toList())
println(sequenceOf(1, 2, 3).windowed(1) { it.toList() }.toList())

Result:
[[1], [2], [3]]
[[], [], []]     //why?!
[[1], [2], [3]]

Please explain

A: It is in the documentation for the function:

Note that the list passed to the transform function is ephemeral and is valid only inside that function. You should not store it or allow it to escape in some way, unless you made a snapshot of it.

As an implementation detail, this higher order function is reusing the same list instance for each element of the window and clearing/refilling it in between. This avoids having to allocate many lists.
By passing it as the return value of the transform function, you are allowing the list instance to escape, as they warn you not to do.
In your third example, you are returning a copy of the list using toList(), so it works correctly.
When you do this with sequences, the results are different because the function internally handles lists and other iterable types differently. Perhaps the algorithm empties the reused list at the end.


text:
Q: Stored Procedure parameters are different in SSMS Object Explorer to when the SP is modified I have hit an issue that I am not quite sure what has caused it, or how to cure it.
When I view the parameters of a stored procedure in the object explorer of management studio, they show more parameters than when I right click on the same stored procedure and select modify.
So if I expand the parameters I get:
dbo.ReportSummary
      Parameters
          @Types (nvarchar(max), input, No Default)
          @month (int, Input, No Default)
          @year (int, Input, No Default)
          @groupID (int, Input, No Default)
          @subGroupID (int, Input, No Default)
          @dateRange (nvarchar(100), input, default)
          Returns integer

If i then right click on the stored procedure and select modify from the popup menu, I get:
ALTER procedure [dbo].[ReportSampleSummaryDetailsByAsset]
@Types nvarchar(max),
@month int, @year int,
@groupID int, @SubUnitID int,
@dateRange nvarchar(100) = ''
as
.....

The subGroup is now missing.
The intelisense shows the parameters the same in the object explorer.
If I check INFORMATION_SCHEMA.Parameters and sys.parameters, they both show the same as the object explorer.
The schemas are both dbo.
The compatability level for the database and management studio are both Microsoft Sql Server 2014.
If it helps any, this is a backup of the publisher database.
What I need to know is:
Why are they different?
and
how do I make the parameters the same in the SP that I modify?

A: Refresh your object explorer.  It needs to be explicitly refreshed when changes have been made to the underlying objects.
Right click on the procedure, and click "Refresh", then re-expand it.


text:
Q: How to send and receive an ajax request with jQuery? I am new to jQuery and am having trouble following the documentation. I have a variable in JavaScript (that I already obtained from an html form) that I would like to send using AJAX to the server.  I want to the server to do whatever it needs to do with that value and then reply with either "success" or "failure" (I know how to do the backend part).  How do I send the request and then receive the reply with jQuery?

A: To send the request you use the $.post or $.get function (or the $.ajax function if you want loads of control)
$.post('example.com/script', {
    'param1':somaVar
 }, function(data){
    alert(data); //data is whatever the server returned
 });

For both $.get and $.post the argument order is like this: (url, [data], [callback], [type]). Url is the url to which the request is done, data is the data with which the request is send, callback is a function that is executed when the request is complete. Type is the type of data the server will return (jQuery usually finds this out on itself) possibles are "xml", "html", "script", "json", "jsonp", or "text"


text:
Q: Driver's symbolic link disappearing In my UMDF windows driver I create a symbolic link of my device in \DosDevices\Global\ directory in order to track device instances. So if a device gets connected to the host a symbolic link \DosDevices\Global\MyDevice0 gets created. If another device gets connected a symbolic link \DosDevices\Global\MyDevice1 gets created. I achieve this by following code:
int symbolicLinkIndex = 0;
for (symbolicLinkIndex = 0; symbolicLinkIndex < 127; symbolicLinkIndex++) // 127 max usb devices
{
    swprintf(m_SymbolicLinkName,
             L"\\DosDevices\\Global\\MyDevice%d",
             symbolicLinkIndex);

    hr = m_FxDevice->CreateSymbolicLinkA(m_SymbolicLinkName);
    if (FAILED(hr))
    {
        // Symbolic link already exists try next index
        if (HRESULT_CODE(hr) == ERROR_ALREADY_EXISTS || HRESULT_CODE(hr) == ERROR_FILE_EXISTS)
            continue;
        else
        {
            TraceEvents(TRACE_LEVEL_ERROR, TRACE_DEVICE, "%!FUNC! Failed to create symbolic link: %lu", hr);
            goto Exit;
        }
    }
    else
    {
        TraceEvents(TRACE_LEVEL_INFORMATION, TRACE_DEVICE, "%!FUNC! Created symbolic link: %S", m_SymbolicLinkName);
        break;
    }
}

Method documentation: IWDFDevice::CreateSymbolicLink
This works if I quickly connect two devices behind each other. However it seems if I wait for about 10 seconds and connect a third device it gets the symbolic link \DosDevices\Global\MyDevice0 which shall not happen, because the first device already got index 0 and is still connected.
So why does it seem that the symbolic link gets deleted after some while? Also I am wondering if my approach is a good one to count device instances?


text:
Q: Zend Framework unknown module is interpreted as default module i wanted to support multilingual structure for my work i used the following lines
$controller=Zend_Controller_Front::getInstance();
$router=$controller->getRouter();
$languageRouter=new Zend_Controller_Router_Route(":lang/:module/:controller/:action", array("lang"=>"en","module"=>"default","controller"=>"index","action"=>"index"),
                                                array("lang"=>"[a-zA-Z]{2}"));
$router->addRoute("default",$languageRouter);

it works fine http://localhost/zend/public/en set the lang param to en and call default module
but the problem is that when i use url like this http://localhost/zend/public/en/anything
where anything isn't module it still show the default module how to prevent that???

after the answer of takeshin i added this function to the bootstarp file and now it works as i want it
protected function _initRoutes()
{
    $routeLang=new Zend_Controller_Router_Route(':lang',array('lang'=>'en'),array('lang'=>'[a-z]{2}'));
    $front  = Zend_Controller_Front::getInstance() /*$this->getResource('frontcontroller')*/;
    $router = $front->getRouter();
    $routeDefault=new Zend_Controller_Router_Route_Module(array(),$front->getDispatcher(),$front->getRequest());
    $routeLangDefault=$routeLang->chain($routeDefault);
    $router->addRoute('default',$routeLangDefault);
    $router->addRoute('lang',$routeLang);
}

A: It looks like you have overwritten default module defined in Zend Application by your custom one.
You should chain the routes instead.

A: The settings you are using means module will 'default' to default , if you didn't it would throw a route not found error - which should throw to appropriate error controller

A: I'm not sure if I unterstood this correctly, but it looks like it works fine, as it should. If you try to call non existing module, Zend Framework automatically "redirects" to the default module.


text: Q: QGIS - Determine percentage of coverage of buffer for census tracts I have a census tract shapefile for the state of South Dakota. I have providers plotted with a 40 mile radius buffer. I am trying to determine what percent of each census tract is covered by any part of the buffer. How can I do this?


text:
Q: How to express one-to-many in Django and use append and remove? class Player(models.Model):
    owner =  models.ForeignKey('self',blank=True, null=True,related_name = "player_owner")
    slaves = models.ManyToManyField('self',blank=True, null=True)

I want to define a Player model, whose instance can have its slaves composing by other players;at the same time it could be a slave of other player.
How to define the slaves field and manipulate it in terms of an instance?

A: Best to refer to the docs
here