text:
Q: Create and populate an array of Raku objects? I chose to redesign a portion of the previous code of mine, in this case, a chessboard, in Perl 6. The first two classes went well (or at least worked, I know so little that I can't speak to their correctness), but I'm stuck with the third. Here is the code:
#!/home/hsmyers/rakudo741/bin/perl6
# board.p6 - Beginnings of a PGN toolset. And place to start learning
#            Perl 6/Raku.
use v6d;

#!___________________________________________________________

constant $size = 4;

class Piece {
    my Str @namesOfPieces[$size] = <
        white-rook white-knight white-bishop white-queen
    >;
    my Str @abrevsOfPieces[$size] = <
        R N B Q K B N R
    >;
    my Str @symbolsOfPieces[$size] = <
        ♖ ♘ ♗ ♕ ♔ ♗ ♘ ♖
    >;
    my Str @codeptsOfPieces[$size] = (
        "\x2656", "\x2658", "\x2657", "\x2655",
    );
    has Str $.name;
    has Str $.abrev;
    has Str $.symbol;
    has Uni $.codept;

    submethod BUILD( :$i ) {
        $!name   = @namesOfPieces[$i];
        $!abrev  = @abrevsOfPieces[$i];
        $!symbol = @symbolsOfPieces[$i];
        $!codept = @codeptsOfPieces[$i].NFC;
    }
}

class Square {
    my Int @colors[$size] = <
        1 0 1 0 1 0 1 0
    >;
    my Str @names[$size] = <
        a1 b1 c1 d1 e1 f1 g1 h1
    >;
    has Int   $.color;
    has Int   $.index;
    has Str   $.name;
    has Piece $.piece;

    submethod BUILD( :$i ) {
        $!color = @colors[$i];
        $!index = $i;
        $!name  = @names[$i];
        $!piece = Piece.new(:i($i));
    }
}

class Board is Array {
}

my $p = Piece.new(:i(0));
$p.say;
my $s = Square.new(:i(0));
$s.say;

#!___________________________________________________________

my @b := Board.new(
    Square.new(:i(0)),
    Square.new(:i(1)),
    Square.new(:i(2))
);
say @b;
say @b.WHAT;

When run at the cli, results in:
Piece.new(name => "white-rook", abrev => "R", symbol => "♖", codept => Uni.new(0x2656).NFC)
Square.new(color => IntStr.new(1, "1"), index => 0, name => "a1", piece => Piece.new(name => "white-
rook", abrev => "R", symbol => "♖", codept => Uni.new(0x2656).NFC))
[Square.new(color => IntStr.new(1, "1"), index => 0, name => "a1", piece => Piece.new(name =>
"white-rook", abrev => "R", symbol => "♖", codept => Uni.new(0x2656).NFC)) Square.new(color =>
IntStr.new(0, "0"), index => 1, name => "b1", piece => Piece.new(name => "white-knight", abrev =>
"N", symbol => "♘", codept => Uni.new(0x2658).NFC)) Square.new(color => IntStr.new(1, "1"), index =>
2, name => "c1", piece => Piece.new(name => "white-bishop", abrev => "B", symbol => "♗", codept =>
Uni.new(0x2657).NFC))]
(Board)

The Board class (empty as it is) is all that is left from my attempts so far. Amazingly (at least to me), it provides a degree of workability. It has variously had a "new" and a "BUILD," neither provided a working solution. The current approach doesn't work, considering that the actual count will be 64 and not 4.
My current notion is that I need to build an array of 64 Squares, which in turn will create the necessary pieces. I've tried to add to self with nothing working. Suggestions?

A: Inheriting from Array is probably not the best design choice here; it reveals and commits to the underlying representation of the Board, which will present refactoring challenges as the code evolves. Rather, I'd suggest that a Board has an Array of Square, which is initialized with Square objects.
Assuming the board is meant to have $size squared places, then you could do something like:
class Board {
    has @.squares[$size ** 2];

    method TWEAK() {
        @!squares = map { Square.new(i => $_ % $size) }, ^($size ** 2);
    }
}

That is, take the range from 0 up to but excluding $size squared, and then map each value into a Square instance. (We modulo the index to avoid an index out of bounds in one of the other classes.)
A 2D array may be preferable:
class Board {
    has @.squares[$size;$size];

    method TWEAK() {
        @!squares = (map -> $i { Square.new(:$i) }, ^$size) xx $size;
    }
}

Here, we map again, but this time since we're just doing one dimension we drop the modulo. The use of a named $i parameter means we can use the :$i convenience, which is short for :i($i) (there's an opportunity to do that in the code you posted also). We then take that expression producing one row, and use xx to run it $size times in order to get data for every column.
Ultimately, it will probably not be quite so simple as this; perhaps Square should take two constructor arguments, both a numeric and a letter, to form its name. That's probably best done as a map of map. Further, the initialization of Piece instances probably wants to happen in Board too; while it's been a quarter of a century since I last played chess, I'm quite sure not every square has a piece on it at the start of the game.


text:
Q: First chance exception when handling exceptions The way I'm handling exceptions is to set values for controls on my master page from the client page where the exception occurs:
    private void deleteUser(int userid)
    {
        try
        {
            ImajUser u = new ImajUser(userid, true);
            u.Delete();

            lblerr.Text = "User was deleted successfully.";
            lblerr.ForeColor = System.Drawing.Color.Green;
        }
        catch (Exception ex)
        {
            this.Master.ErrorTitle.Text = "Delete User";
            this.Master.ErrorMessage.Text = String.Format("Error actioning request: [ {0} ]", ex.Message);
            this.Master.pnlErrorBG.Visible = true;
            this.Master.pnlErrorModal.Visible = true;

        }
    }

When i test this (last time I shut down the database and tried a Delete), my catch block executes without fault, but I get a first chance exception and the debugger stops completely:

A first chance exception of type 'System.Data.EntityException' occurred in System.Data.Entity.dll
  The program '[2108] WebDev.WebServer40.EXE: Managed (v4.0.30319)' has exited with code -2147023895 (0x800703e9).

I've never seen this before. I don't know what causes it and I don't know how to fix it either...
Any help will be greatly appreciated!
EDIT
The properties I'm setting for access to the master page's controls are:
    public virtual Label ErrorTitle { get { return lblErrorAction; } }
    public virtual Label ErrorMessage { get { return lblErrorMessage; } }
    public virtual Panel pnlErrorBG { get { return ErrorBackground; } }
    public virtual Panel pnlErrorModal { get { return pnlErrorModal; } }

These reference the controls:
    <asp:Panel runat="server" id="ErrorBackground" visible="false"> </asp:Panel>
    <asp:Panel runat="server" id="ErrorModal" visible="false">
        <asp:Label runat="server" ID="lblErrorAction" CssClass="lblerrortitle"></asp:Label>
        <asp:Label runat="server" ID="lblErrorMessage"></asp:Label>
        <asp:Button runat="server" ID="btnErrorAction" CssClass="button" Text="Retry" OnClick="btnErrorAction_Click" />
    </asp:Panel>

EDIT 2
So I tried moving the controls to the page where the exception actually occurs and that worked 100% whereas using controls on the master page causes the error.

A: This is a Visual Studio setting in Debug / Exceptions. The [x] Thrown properties tells the debugger to stop on first chance exceptions. Uncheck the checkbox to stop only on second chance exceptions.

BTW: first chance exceptions do not terminate a process. Only second chance exceptions do. So you should be able to continue by pressing the "Play" button (Continue) again or use the F5 key.

redpajama_set_name: RedPajamaStackExchange


text:
Q: ArrayList causing NullPointerException I am getting nullpointer exception on this code from the paintcomponent method
  public A1Panel() {
            final ArrayList<MySnowFlake> myShapes = new ArrayList<MySnowFlake>();   //Stage 1: Replace this line
            popup = new JPopupMenu();               //create the popup menu
            makePopupMenu();

            addMouseListener( new MouseAdapter() {
            public void mousePressed(MouseEvent e) {
                maybeShowPopup(e);
            }

            public void mouseReleased(MouseEvent e) {
                maybeShowPopup(e);
            }

            private void maybeShowPopup(MouseEvent e) {
                if (e.isPopupTrigger()) {
                    popup.show(e.getComponent(), e.getX(), e.getY());
                }
            }
            public void mouseClicked( MouseEvent e ) {  //Stage 1: Modify the following statements
                myShapes.add(currentIndex, new MySnowFlake(e.getX(), e.getY(), currentLevel, currentLength));
                currentIndex += 1;
                repaint();
            }
            });
        }

        public void paintComponent(Graphics g) {
                //g.drawString("" + currentIndex, 50,50);
            //Stage 1: Modify the following statements
            try{
            for (int i = 0; i < currentIndex; i++) {
                myShapes.get(i).paint(g);
            }
            } catch(NullPointerException e){
                System.out.println("NullPointerException caught!!");
            }
        }

MySnowFlake
public class MySnowFlake {
    protected int level;            // the recursion level
    protected Turtle turtle;        // the turtle object
    protected double turn = Math.PI/3; // the turning angle
    public int length;              // the length of the snowflake
    public Point p;                 // the initial position

    /** Constructor to create a Snowflake and initialize all values
    */
    public MySnowFlake(int x, int y, int level, int length) {
        this.level = level;
        this.length = length;
        p = new Point(x,y);
        turtle = new Turtle();
    }

    public void translate(int dx, int dy){
        p.x += dx;
        p.y += dy;
    }

    public void LevelUp(){
        level++;
    }

    public void LevelDown(){
        level--;
    }

    /**
     * Recursive draw method
    * @param lev -  the level of the koch shape
    * @param size -  the size of the koch shape
    */
    public void draw(int lev, double size) {
        // 1) define the base case
        if(lev < 0){

        // 2) define the recursive case

    }

    /**
     * Paint a snowflake
    * @param g  the graphics control
    */

    public void paint(Graphics g) {
        double size = length;

        // replace this line with recursive calls
        g.drawRect(p.x, p.y, level*5, level*5);

        // 1) set up the turtle object first

        // 2) call the recursive draw method

    }
}

A: The loop would work more reliable, when you would use the actual length of the ArrayList:
for (int i = 0; i < myShapes.size(); i++) {

But note that the exception could also occur inside the paint method of the class MySnowFlake. When you catch an exception which can be caused by a lot of different problems (like a NullPointerException), you should always print the stack trace of it so you can see where the exception is actually thrown:
        } catch(NullPointerException e){
            System.out.println("NullPointerException caught!!");
            e.printStackTrace();
        }

In production software it is usually a good idea to save the stack-traces of all unexpected exceptions to a logfile or a database so you can do a post-mortem analysis later.

A: Could you please change the sequence of these 2 lines, i.e. instead of
myShapes.add(currentIndex, new MySnowFlake(e.getX(), e.getY(), currentLevel, currentLength));
currentIndex += 1;

try this:
currentIndex += 1;
myShapes.add(currentIndex, new MySnowFlake(e.getX(), e.getY(), currentLevel, currentLength));


text:
Q: Deserialize RGeo column as SphericalPointImpl there is a table with an RGeo column in Rails 4.2.4 and activerecord-postgis-adapter 3.1.2
class CreateAddresses < ActiveRecord::Migration
  def change
    create_table :addresses do |t|
      t.st_point :coordinates,   geographic: true, srid: 4326
    end

    add_index :addresses, :coordinates, using: :gist
  end
end

and a method that groups objects by their location
def self.group_by_coords
    includes(:address).
    joins(:address).
    group('addresses.coordinates::geometry').
    pluck(
      'array_agg(realties.id) as ids, addresses.coordinates::geometry'
    )
  end

with the corresponding test:
describe 'group_by_coords' do
  it 'correctly group realties' do
    # create samples
    expect(Realty.group_by_coords).to eq(
      [[[r1.id, r2.id], r1.address.coordinates], [[r3.id], r3.address.coordinates]]
    )
  end
end

the problem is that pluck returns  RGeo::Geos::CAPIPointImpl instead of  RGeo::Geographic::SphericalPointImpl
expected: [[[1670, 1671], #<RGeo::Geographic::SphericalPointImpl:0x3fd37e9b8a20 "POINT (106.0 10.0)">], [[1672], #<RGeo::Geographic::SphericalPointImpl:0x3fd37ab2dddc "POINT (106.5 10.5)">]]
got: [[[1671, 1670], #<RGeo::Geos::CAPIPointImpl:0x3fd37a335a44 "POINT (106.0 10.0)">], [[1672], #<RGeo::Geos::CAPIPointImpl:0x3fd37a33560c "POINT (106.5 10.5)">]]

I believe in order to fix that there must be specified a correct factory. I tried
to specify it like this
RGeo::ActiveRecord::SpatialFactoryStore.instance.tap do |config|
  config.default = RGeo::Geos.factory_generator
  config.register(RGeo::Geographic.spherical_factory(srid: 4326), geo_type: "point", sql_type: "geography")
end

but it then deserializes all points as RGeo::Geos::CAPIPointImpl which is more generic and incompatible with existing codebase.
So the question is how to make all points deserialized as RGeo::Geographic::SphericalPointImpl ?

A: What is likely here is probably simplier than what you expect let's just look at the first few characters.
expected: [[[1670, 1671],...
got: [[[1671, 1670],...

Why would those be different either way?


text:
Q: Setting selected item of ListBox in winforms throws array index out of bounds exception I'm currently working on a project in winforms and run into a little trouble with setting the selected item of a populated ListBox. Basically, I have an SQL database which holds what I guess could be called meta-data about individual clients, one of the fields being the server and name of the database all of their data is in. In addition to this, I have a form where I would like the user to be able to update the client information. There is a dropdown list of clients on this form and when the user selects a client, the form is populated with their data. One of the pieces that is populated is a ListBox of databases on the same server as their currently selected database. I would then like to select the database on that list that corresponds to the selected client, but I get an "Array index out of bounds" exception. Here's what the code basically looks like:
//getClientInfo returns all of the fields for the selected client from the database
//getDatabases returns the database names using "SELECT name FROM master.sys.databases"
Dictionary<string, object> clientData = getClientInfo(clients_ListBox.SelectedItem);
server_ComboBox.SelectedItem = clientData["Server"].ToString();
databases_ListBox.DataSource = getDatabases("Data Source=" + server_ComboBox.Text + "; Trusted_Connection=yes");
.
.
.    -----set other fields-----
.
.
 databases_ListBox.SelectedItem = clientData["Database"].ToString();

And then I get an exception on the last line. The weird thing is that this doesn't seem to occur in Debug mode, as well as when the client before I switch and the client I switch to are on the same server. If they are on different databases, I get the exception, otherwise it's fine. Could anyone help explain this to me? I can only think of some sort of timing issue, where the item is being set before the ListBox finishes being populated, but I'm not using any sort of threading, so I have no idea what's going on.
In typing this, I realized that it might be smarter to have the connection string use the retrieved client data instead of the ComboBox text, but I would still like it if someone could venture a guess as to why I'm having this problem. Thanks a lot!


text:
Q: The Maths for 2D Collision Detection between an OBB and a Circle I'm creating a 2D game and want to test for collision between an OBB (Oriented Bounding Box) and a Circle. I'm unsure of the maths and code to do this. I'm creating the game in c++ and opengl.

A: Since both your shapes are convex, you can use the Separating Axis Theorem. Here's a tutorial on how to implement an algorithm to do this.
Essentially, you try to find if it's possible to put a line somewhere that's between the two shapes and if you can't find one, then you know they're colliding.
References and general answer taken from this question.

A: Here's what I would do, in pseudocode:
function does_line_go_through_circle (original_line, circle_centerpoint, radius):
    original_slope = get_slope_of_line (original_line)
    perpendicular_slope = 1/original_slope
    perpendicular_line = create_line_with_slope_through_point (perpendicular_slope, circle_centerpoint)
    intersect_point = intersection_of_infinite_lines (perpendicular_line, original_line)
    if point_is_on_line (intersect_point, original_line):
        finite_line_along_radius = create_finite_line_between_points (circle_centerpoint, intersect_point)
        if length_of_line (finite_line_along_radius) < length_of_line (radius):
            return true
        end
    end
    return false
end

function does_box_intersect_with_circle (bounding_box, circle):
    for each side in bounding_box:
        if does_line_go_through_circle (side, circle.center, circle.radius):
            return true
        end
    end
    return false
end

Keep in mind, I'm a little rusty on this stuff, I might be wrong.
Anyway, it should be trivial to implement this in C++.

A: We will divide the rectangle into 4 finite lines.
We can construct the line equation ax + by + c = 0 connecting the points (x1, y1) and (x2, y2) as follows:
mx - y + c = 0

where m = (y2-y1)/(x2-x1)
Shortest (perpendicular) distance from a line ax + by + c = 0 to a point (xc, yc) is given by the expression:
d = (a*xc + b*yc + c) / sqrt(a*a + b*b)

or d = (m*xc - yc + c) / sqrt(m*m + 1) according the the above equation
For infinite lines, you can check if 'd' is less than the radius of the circle.
But for finite lines, you'd also have to make sure whether the point of contact is within the line.
Now m = tan(angle). You can have
cos = 1 / sqrt(m*m + 1);  sin = m / sqrt(m*m + 1)

Then you can calculate the point of contact as
xp = xc + d*cos;   yp = yc + d*sin

And to check whether (xp, yp) lies in between the points connecting line, you can do a simple check as
if(x1 < xp < x2 && y1 < yp < y2)
    return true

depending upon which is greater among x1 x2 and y1 y2.
You can repeat the same algorithm for all the four lines of a rectangle by passing the points.
Please correct me if I'm wrong somewhere.


text:
Q: CSS3 Animation should stop at position 75% Is it possible to stop CSS3 Animation at 75% and should not show again at 0% or atleast make delay at 75% for 10s ? As right now when animation completed it shows on at position 0%

div {
  width: 100px;
  height: 100px;
  background-color: red;
  position: relative;
  -webkit-animation-name: example;
  /* Chrome, Safari, Opera */
  -webkit-animation-duration: 4s;
  /* Chrome, Safari, Opera */
  animation-name: example;
  animation-duration: 4s;
}
/* Chrome, Safari, Opera */

@-webkit-keyframes example {
  0% {
    background-color: red;
    left: 0px;
    top: 0px;
  }
  25% {
    background-color: yellow;
    left: 200px;
    top: 0px;
  }
  50% {
    background-color: blue;
    left: 200px;
    top: 200px;
  }
  75% {
    background-color: green;
    left: 0px;
    top: 200px;
  }
}

A: I've made couple of changes to your animation, all you need to do is duplicate your 75% animation twice and later use animation-fill-mode property and set it to forwards to halt the animation at the last position.
Demo
div {
    width: 100px;
    height: 100px;
    background-color: red;
    position: relative;
    -webkit-animation-name: example; /* Chrome, Safari, Opera */
    -webkit-animation-duration: 4s; /* Chrome, Safari, Opera */
    animation-name: example;
    animation-duration: 4s;

    /* add these properties */
    -webkit-animation-fill-mode: forwards;
    animation-fill-mode: forwards;
}

/* Chrome, Safari, Opera */
@-webkit-keyframes example {
    0%   {background-color:red; left:0px; top:0px;}
    25%  {background-color:yellow; left:200px; top:0px;}
    50%  {background-color:blue; left:200px; top:200px;}
    75%  {background-color:green; left:0px; top:200px;}
    /* add the below one */
    100%  {background-color:green; left:0px; top:200px;}
}


text:
Q: Change string date/time to be understandable for mathematica I'm trying to convert a string of a data and time to be understandable for mathematica (I want to make time related plots).
However, I can get my head around how to do this.
For example:
temp = "Sun Jun 01 22:00:21 +0000 2014";

I have tried the following commands (and many more variations):
DateList[{temp, {"DayName", "Month", "Day", "Hour", "Minute",
   "Second", "TimeZone", "Year"}}];
DateList[{temp, {"DayName", "Month", "Day", "Hour", ":", "Minute",
   ":", "Second", "TimeZone", "Year"}}]

Both gave me this type of error:
DateString::str: "String \!\(\"Sun Jun 01 22:00:21 +0000 2014\"\) cannot be interpreted as a date in format {\!\(\"DayName\", \"Month\", \"Day\", \"Hour\", \"Minute\", \"Second\", \"TimeZone\", \"Year\"\)}."

Can anyone tell what I'm doing wrong? Thank you!!

A: The problem is with "TimeZone", that its not defined, and with using "Month" instead of "MonthName".
This works:
DateList[{"Sun Jun 01 22:00:21 2014", {"DayName", "MonthName", "Day", "Hour", "Minute", "Second", "Year"}}]

Are the strings in temp with fixed format? Then removing the characters will do
DateList[{StringDrop[temp, {21, 26}], {"DayName", "MonthName", "Day", "Hour", "Minute", "Second", "Year"}}]

Otherwise
DateList[ToString@ImportString[temp, "Table"][[1, {6, 2, 3, 4}]]]

I'm sure somebody else can work some magic to make this shorter and more efficient.

A: Some options
Your date
date = "Sun Jun 01 22:00:21 +0000 2014";

Eliminate wrong entry
rep = StringReplace[date, "+0000" -> ""]

"Sun Jun 01 22:00:21  2014"

Convert to List
list = rep // DateList

{2014, 6, 1, 22, 0, 21.}

Find day
day = DayName[list]

Sunday

Consolidate
{day}~Join~list

{Sunday, 2014, 6, 1, 22, 0, 21.}

Convert to DateObject @ GMT
obj = DateObject[list, TimeZone -> 0]

Convert to your local time
tzc = TimeZoneConvert[obj, $TimeZone]

Transform to DateList
tzc // DateList

{2014, 6, 2, 0, 0, 21.}

Convert to  another CalendarType
DateObject[list, CalendarType -> "Jewish"]

A: Manually fixing the timezone.
datecalc[t_] := Module[{},

  t2 = StringSplit[t, " " | ":"];
  tzsign = StringTake[t2[[7]], 1];
  tzhrs = ToExpression[StringTake[t2[[7]], {2, 3}]];
  tzmin = ToExpression[StringTake[t2[[7]], -2]];
  {hour, min} = ToExpression[t2[[{4, 5}]]];

  If[SameQ[tzsign, "+"],
   h2 = hour + tzhrs; m2 = min + tzmin,
   h2 = hour - tzhrs; m2 = min - tzmin];

  ymd = Take[DateList[{StringJoin[
        Riffle[Append[Take[t2, {2, 3}], Last@t2], " "]],
       {"MonthName", "Day", "Year"}}], 3];

  DateList[Join[ymd, {h2, m2}, {ToExpression[t2[[6]]]}]]]

Works for UTC-02:30
datecalc["Sun Jun 01 22:00:21 -0230 2014"]

{2014, 6, 1, 19, 30, 21.}

and UTC+13:45
datecalc["Fri Dec 31 11:00:21 +1345 1999"]

{2000, 1, 1, 0, 45, 21.}

A: At first I tried this hack:
ClearAll;
temp = "Sun Jun 01 22:00:21 +0000 2014";
td = If[StringFreeQ[temp, "-"],
   DateList[{temp, {"DayNameShort", " ", "MonthNameShort", " ",
      "Day", " ", "Hour24", ":", "Minute", ":", "Second", " +",
      "Millisecond", " ", "Year"}}],
   DateList[{temp, {"DayNameShort", " ", "MonthNameShort", " ",
      "Day", " ", "Hour24", ":", "Minute", ":", "Second", " -",
      "Millisecond", " ", "Year"}}]
   ];
tx = If[StringFreeQ[temp, "-"],
  DateList[td,
   TimeZone -> Plus[(FractionalPart[Last[td]]* 100), $TimeZone] ],
      DateList[td,
       TimeZone -> Plus[(-FractionalPart[Last[td]]* 100), $TimeZone]]]
(* {2014, 6, 1, 22, 0, 21.} *)

Since there is no "TimeZone" pattern match expression, I hacked the "Millisecond". However, millisecond is limited to 3 digits, so we get round off errors.
Next I tried this:
ClearAll;
temp = "Sun Jun 01 22:00:21 +0000 2014";
DateList[{StringDrop[
   StringRotateRight[StringInsert[temp, " ", -1], 5], -7], {"Year",
   " ", "DayNameShort", " ", "MonthNameShort", " ", "Day", " ",
   "Hour24", ":", "Minute", ":", "Second"}},
 TimeZone ->
  Plus[(ToExpression[
     StringJoin[
      StringTrim[
       StringTake[
        StringRotateRight[StringInsert[temp, " ", -1],
         5], {-7, -4}]],
      StringTrim[
       ToString[
        N[Rationalize[
          ToExpression[
            StringTrim[
             StringTake[
              StringRotateRight[StringInsert[temp, " ", -1],
               5], {-3, -1}]]]/60]]], "0"]
      ]]), $TimeZone]]
(* {2014, 6, 1, 22, 0, 21.} *)

Add space to end, rotate the string, and adjust the date pattern expression. If you put this as a Module function would have more freedom to reduce rotations. Still not certain about the TimeZone stuff.


text:
Q: PHP: Get MAC address I checked several scripts so I could display my MAC address but to no avail.
I'm asking for your help!
Here is what I tested so far but nothing works correctly:
<?php
require_once 'MacAddress.php'; //https://github.com/BlakeGardner/php-mac-address/blob/master/src/BlakeGardner/MacAddress.php
use BlakeGardner\MacAddress;
echo "Current MAC address: ";
var_dump(MacAddress::getCurrentMacAddress('eth0'));
echo "Randomly generated MAC address: ";
var_dump(MacAddress::generateMacAddress()); // Generat all refresh a new address
?>

- Current MAC address EC:A8:6B:F1:D2:B0 on all my phones/desktop on 4G or ADSL
- Randomly generated MAC address : the MAC address output varies a little bit every time the scripted is run. I suspect it's because of the time and latency information that has changed in the count. Is there a more effective way to pull just the mac address ?
<?php
class env
{
public static $IP;
public static $MAC;
public function getIP()
{
env::$IP = $_SERVER['REMOTE_ADDR'];
}
public function getMAC($ip)
{
$macCommandString = "arp $ip | awk 'BEGIN{ i=1; } { i++; if(i==3) print $3 }'";
$mac = exec($macCommandString);
env::$MAC = $mac;
}
function __construct()
{
$this->getIP();
$this->getMAC(env::$IP);
}
}
$envObj = new env();
echo "MAC : ".env::$MAC."<br>";
echo "IP : ".env::$IP;
?>

- MAC is empty
- IP is my same IP on myip.com
<?php
ob_start();
system('ipconfig /all');
$mycom=ob_get_contents();
ob_clean();
$findme = "Physical";
$pmac = strpos($mycom, $findme);
$mac = substr($mycom,($pmac+36),17);

echo $mac;  // Empty

$macLookup = 'MAC Address: ';
$pos = strpos($ping, $macLookup);

if ($pos !== false) {$mac = substr($ping, $pos+strlen($macLookup), 17 );
echo $mac; // Empty
}
?>

- $mac is empty
Can you help me please ?

A:
Current MAC address EC:A8:6B:F1:D2:B0 on all my phones/desktop on 4G or ADSL

PHP code runs on the web server.
Thus the MAC address printed out by a PHP program will be the address of the network interface on the server.
You will always get the same value because it's always checking the address of the same network interface on the server.
It doesn't matter where you are running the browser, the code will always run at the same place and will always get the same code.
If want to get the MAC address of your device that you are actually using, then you will need to run the code on that device. (this will probably mean switching to a different language).

A: to get your own mac address on linux server
$mac = shell_exec("ifconfig -a | grep -Po 'HWaddr \K.*$'");

var_dump($mac);

this will give mac address of server where PHP is running


text:
Q: How to get the set of warning checks currently enabled in the perl module? In the perllexwarn are defined all warnings what is possible to set.
But here is nothing about, how to print out what warnings i have currently enabled.
E.g.:
use strict;
use warnings;

print warnings::enabled->pretty_print(); #fictional...

How is it possible?
example:
use strict;
use 5.012;
use warnings;

my $aaa;
say "$aaa";

say warnings::enabled("uninitialized") ? "yes" : "no";

The above will output:
Use of uninitialized value $aaa in string at y line 6.

no

so, the "uninitialized" warning category is "set", because its prints a warning, but the warnings::enabled("uninitialized") not returns true.

A: Reading perllexwarn

... functions that are useful for module authors. These are used when you
  want to report a module-specific warning to a calling module has
  enabled warnings via the "warnings" pragma.

If I understand it correctly, it means the functions (enabled, warnif) only work for module-specific warnings, not for the standard categories. (There is probably a missing "that" before "has" in the documentation.)
Update: It seems standard categories work as well, but only in a module:
package MY;
use warnings::register;
sub S {
    my $x;
    print $x, "\t";
    print warnings::enabled("uninitialized"),"\n";
}

package main;
use warnings;
MY::S();
no warnings;
MY::S();


text:
Q: How to create a half scene? I am working on a project where I need to create a scene and export it only for the right or the left eye and export just a black scene for the other eye using Aframe. Is there an easy way to do so?
Thanks

A: check out the aframe stereo component.
then you can use the attribute stereo to define what should be displayed for what eye:
<a-entity geometry="primitive: box" material="color: #C03546" stereo="eye:left"></a-entity>
<a-entity geometry="primitive: box" material="color: #3546C0" position="0 5 0" stereo="eye: right"></a-entity>

example from the same link.


text:
Q: JaCoCo skipping specific package with Quarkus I have the following classes in separated files:
@Path("/products")
@Produces(MediaType.APPLICATION_JSON)
class ProductController{
    @Inject
    private ProductService productService;
}

@ApplicationScoped
public class ProductService {
    @Inject
    private ProductRepository productRepository;
}

@ApplicationScoped
public class ProductRepository implements PanacheRepositoryBase<Product, UUID> {
}

And when I run the tests coverage, all controllers and services and other packages are correctly recognized by JaCoCo, but all repositories aren't, resulting in 0% coverage in this package. And I'm sure that they are being used by services.

My guess is because JaCoCo only recognizes up to 1 level of "proxy", due to @AppicationScoped annotation, but I'm not sure.
I also tried offline intrumentation, but the result is the same.
This is my gradle config now:
plugins {
    id 'java'
    id 'io.quarkus'
    id 'jacoco'
}

repositories {
    mavenLocal()
    mavenCentral()
}

dependencies {
    // a lot of deps not related to tests
}

java {
    sourceCompatibility = JavaVersion.VERSION_11
    targetCompatibility = JavaVersion.VERSION_11
}

compileJava {
    options.encoding = 'UTF-8'
    options.compilerArgs << '-parameters'
}

compileTestJava {
    options.encoding = 'UTF-8'
}

test {
    useJUnitPlatform()
    jacoco {
        destinationFile = file("$buildDir/jacoco/test.exec")
    }
    finalizedBy jacocoTestReport
}

jacoco {
    toolVersion = '0.8.6'
    reportsDir = file("$buildDir/reports/jacoco")
}

jacocoTestCoverageVerification {
    executionData fileTree("$buildDir/jacoco/").include("*.exec")
    afterEvaluate {
        classDirectories.setFrom(files(classDirectories.files.collect {
            fileTree(dir: it)
        }))
    }
}

jacocoTestReport {
    executionData fileTree("$buildDir/jacoco/").include("*.exec")
    reports {
        xml.enabled false
        csv.enabled false
        html.destination file("${buildDir}/reports/jacoco")
    }

    afterEvaluate {
        classDirectories.setFrom(files(classDirectories.files.collect {
            fileTree(dir: it)
        }))
    }
}

And this is the other "version" of gradle config, with offline instrumentation:
configurations {
    jacocoAnt
    jacocoRuntime
}
dependencies {
    jacocoAnt group: 'org.jacoco', name: 'org.jacoco.ant', version: '0.8.5', classifier: 'nodeps'
    jacocoRuntime group: 'org.jacoco', name: 'org.jacoco.agent', version: '0.8.5', classifier: 'runtime'
}
test {
    useJUnitPlatform()
    jacoco {
        destinationFile = file("$buildDir/reports/jacoco/jacoco-sonar/jacoco-coverage.exec")
    }
}
jacoco {
    toolVersion = "0.8.5"
    reportsDir = file("$buildDir/customJacocoReportDir")
}
jacocoTestReport {
    reports {
        xml.enabled false
        csv.enabled false
        html.destination file("${buildDir}/jacocoHtml")
    }
}
jacocoTestCoverageVerification {
    executionData fileTree("$buildDir/reports/jacoco/jacoco-sonar/").include("*.exec")
    afterEvaluate {
        classDirectories.setFrom(files(classDirectories.files.collect {
            fileTree(dir: it)
        }))
    }
    violationRules {
        rule {
            limit {
                minimum = 0.74
            }
        }
    }
}
task instrument(dependsOn: ['classes']) {
    ext.outputDir = buildDir.path + '/reports/classes-instrumented'
    doLast {
        ant.taskdef(name: 'instrument',
                classname: 'org.jacoco.ant.InstrumentTask',
                classpath: configurations.jacocoAnt.asPath)
        ant.instrument(destdir: outputDir) {
            sourceSets.main.output.classesDirs.each { fileset(dir: it) }
        }
    }
}
gradle.taskGraph.whenReady { graph ->
    if (graph.hasTask(instrument)) {
        tasks.withType(Test) {
            doFirst {
                classpath = files(instrument.outputDir) + classpath + configurations.jacocoRuntime
            }
        }
    }
}
task report(dependsOn: ['instrument', 'test']) {
    doLast {
        ant.taskdef(name: 'report',
                classname: 'org.jacoco.ant.ReportTask',
                classpath: configurations.jacocoAnt.asPath)
        ant.report() {
            executiondata {
                ant.file(file: buildDir.path + '/reports/jacoco/jacoco-sonar/jacoco-coverage.exec')
            }
            structure(name: 'Example') {
                classfiles {
                    sourceSets.main.output.classesDirs.each { fileset(dir: it) }
                }
                sourcefiles {
                    fileset(dir: 'src/main/java')
                }
            }
            html(destdir: buildDir.path + '/reports/jacoco')
        }
    }
}

Why it happens?

A: I was facing the same problem as you, after include the following extension the coverage problem for @ApplicationScoped annotated classes was solved.
<dependency>
  <groupId>io.quarkus</groupId>
  <artifactId>quarkus-jacoco</artifactId>
  <scope>test</scope>
</dependency>

Obviously, since you are using Gradle, you should change it. I also needed to remove jacoco-maven-plugin plugin from maven plugins section. Probably you will need to remove everything that you included for custom instrumentation.

A: Quarkus bytecode instrumentation and JaCoCo can step on each other toes, JaCoCo default mode uses an agent the inject some bytecode and this can be incompatible with Quarkus' own bytecode injection.
You can switch JaCoCo to offline instrumentation instead, please follow this section of the Quarkus test coverage guide:
https://quarkus.io/guides/tests-with-coverage#instrumenting-the-classes-instead


text:
Q: Calculating the Entropy of a NxN matrix in python I have a NxN matrix where all the elements are having values between [-1, 1]. I can calculate Shannon's Entropy manually, but I want something like Von Neumann's Entropy. Is there any inbuilt function in Numpy/Scipy?
Manual method will also do.
Matrix is usually of size 100x100. Something like this.
[[-0.244608 -0.71395497 -0.36534627]
[-0.44626849 -0.82385746 -0.74654582]
[ 0.38240205 -0.58970239  0.67858516]]

Thank You.

A: What about just finding eigenvalues?
Untested pseudo-code
import numpy as np
from numpy import linalg as LA

M = ... # this is your matrix

e, v = LA.eig(M)

t = e * np.log(e)

return -np.sum(t)

UPDATE
Looking at companion site, this answer might be of an interest to you
https://cs.stackexchange.com/questions/56261/computing-von-neumann-entropy-efficiently
UPDATE
If you don't want to go via eigenvalues/polynomials, then you could compute log of the matrix (everything else is trivial) using Jordan decomposition to get Jordan normal form of a matrix. In python it could be done via SymPy, http://docs.sympy.org/0.7.1/modules/matrices.html#sympy.matrices.matrices.Matrix.jordan_form, check Compute Jordan normal form of matrix in Python / NumPy also for details.
Then log(M) could be computed from Jordan form using Gantmacher 1959 theorem, check this paper https://www.ams.org/journals/proc/1966-017-05/S0002-9939-1966-0202740-6/S0002-9939-1966-0202740-6.pdf for simplified explanation, especially eqns 3.4-3.8
But I bet you a donut Jordan normal form of your matrix will be complex.

A: You can define von Neumann entropy in one of two ways according to Nielsen & Chuang in "Quantum Computation and Quantum Information". It can be defined either in terms of (the negative of) the trace of the matrix times its own (matrix) logarithm...or...it can be defined in terms of the eigenvalues. The above examples all take logarithms base e, but you need base 2. In order to do this you'll need a base change in your computation. Here are two functions in Python which can be used, one for each version of the definition of von Neumann entropy (of a density operator say):
For the trace version
def von_neumann_entropy(rho):
    import numpy as np
    from scipy import linalg as la
    R = rho*(la.logm(rho)/la.logm(np.matrix([[2]])))
    S = -np.matrix.trace(R)
    return(S)

For the eigenvalue version
def vn_eig_entropy(rho):
    import numpy as np
    from scipy import linalg as la
    import math as m
    EV = la.eigvals(rho)

    # Drop zero eigenvalues so that log2 is defined
    my_list = [x for x in EV.tolist() if x]
    EV = np.array(my_list)

    log2_EV = np.matrix(np.log2(EV))
    EV = np.matrix(EV)
    S = -np.dot(EV, log2_EV.H)
    return(S)

These will return the same value, so it does not matter which you use. Just feed one of these functions a square matrix using something like
rho = np.matrix([[5/6, 1/6],
                 [1/6, 1/6]])

Obviously any square matrix will work, not just a 2x2, this is just to give you an example. If your matrix has zero eigenvalues, the convention is to set 0*log(0) terms equal to zero. This is taken care of by the second function vn_eig_entropy. All density matrices are "non-negative definite", so this is the only issue with eigenvalues you should run into. I know this response is a bit late, but maybe it will help someone else.


text:
Q: How to deal with Databases which exceed 2gb I have to work with a database which exceeds the 2gb limit. I have tried splitting the database as well but I'm not able to do it. Please suggest what I can do to solve this problem

A: When faced with the inherent 2GB limit on the size of your MS Access database, there are several steps that you can undertake, depending on how aggressively you need to reduce the size of the database:
Step 0: Compact the Database
The obvious first step, but I'll mention it here in case it has been overlooked.
Step 1: Splitting the Database
The operation of splitting the database will separate the 'front end' data (queries, reports, forms, macros etc.) from the 'back end' data (the tables).
To do this, go to Database Tools > Move Data > Access Database
This operation will export all tables in your current database to a separate .accdb database file, and will then link the tables from the new  .accdb database file back into the original database.
As a result of this operation, The size of the back end database will be marginally reduced since it no longer contains the definitions of the various front end objects, along with resources such as images which may have been used on reports/forms and which may have contributed more towards the overall size of the original database.
But since the vast majority of the data within the file will be stored in the database tables, you will only see marginal gains in database size following this operation.
If this initial step does not significantly reduce the size of the back end database below the 2GB limit, the next step might be:
Step 2: Dividing the Backend Database
The in-built operation offered by MS Access to split the database into a separate frontend and backend database will export all tables from the original database into a single backend database file, and will then relink such tables into the front end database file.
However, if the resulting backend database is still approaching the 2GB limit, you can divide the backend database further into separate smaller chunks - each with its own 2GB limit.
To do this, export the larger tables from your backend database into a separate .accdb database file, and then link this new separate database file to your frontend database in place of the original table.
Taking this process to the limit would result in each table residing within its own separate .accdb database file.
Step 3: Dividing Table Data
This is the very last resort and the feasibility of this step will depend on the type of data you are working with.
If you are operating will dated data, you might consider exporting all data dated prior to a specific cutoff date into a separate table within a separate .accdb database file, and then link the two separate tables into your frontend database (such that you have a 'live' table and an 'archive' table).
Note however that you will not be able to union the data from the two tables within a single query, as the 2GB MS Access limit applies to the amount of data that MS Access is able to manipulate within the single .accdb file, not just the data which may be stored in the tables.
Step 4: Migrate to another RDBMS
If you're frequently hitting the 2GB limit imposed by an MS Access database and find yourself sabotaging the functionality of your database as a result of having to dice up the data into ever smaller chunks, consider opting for a more heavyweight database management system, such as SQL Server, for example.

A: You can split your database into several files. The feature exists in the menu Database Tools > Move data.
You can read the Microsoft documentation about it
But prepare yourself to migrate to a new RDBMS in a near future because you are reaching the system limits ...


text:
Q: Snort running with pfSense First of all, I am sorry about my English skill.
I have a topology and I want to integrate the Snort with pfSense.
Can pfSense auto add firewall rules when Snort alert?
Does pfSense have function to do this action?

A: Snort will automatically block the ip address of the offender, for the time period that you select, thus adding the firewall rule that blocked the offender is not really necessary as they get blocked automatically. The Snort rules define what traffic is blocked and you determine what rule set(s) you would like it to filter traffic with.
See screen shots for a little more information.


text:
Q: How to create imageView click event in iOS?
Note:
      ImageView Click event is available in Android, I Want to know  whether it's available or not in iOS

I am new to iOS, please consider, I have camera image, OnClick of it I have to open my device camera, but I am getting function of Action for image. Attaching screenshot

My code:
import UIKit

class AttendanceViewController: UIViewController {

    @IBOutlet weak var loginimagebtn: UIImageView!
    @IBOutlet weak var loginstatus: UITextView!
    @IBOutlet weak var displayloginimg: UIImageView!

    override func viewDidLoad() {
        super.viewDidLoad()
    }

    func openCamer() {

    if UIImagePickerController.isSourceTypeAvailable(
        UIImagePickerControllerSourceType.camera) {

        let imagePicker = UIImagePickerController()
        imagePicker.delegate = self
        imagePicker.sourceType = UIImagePickerControllerSourceType.camera
        imagePicker.allowsEditing = false
        self.present(imagePicker,animated: true,completion : nil)
    }

}

    // For Toast message below code
    func showToast(message : String) {
        let toastLabel = UILabel(frame: CGRect(x: self.view.frame.size.width/2 - 75, y: self.view.frame.size.height-100, width: 150, height: 35))
        toastLabel.backgroundColor = UIColor.black.withAlphaComponent(0.6)
        toastLabel.textColor = UIColor.white
        toastLabel.textAlignment = .center;
        toastLabel.font = UIFont(name: "Montserrat-Light", size: 12.0)
        toastLabel.text = message
        toastLabel.alpha = 1.0
        toastLabel.layer.cornerRadius = 10;
        toastLabel.clipsToBounds  =  true
        self.view.addSubview(toastLabel)
        UIView.animate(withDuration: 4.0, delay: 0.1, options: .curveEaseOut, animations: {
            toastLabel.alpha = 0.0
        }, completion: {(isCompleted) in
            toastLabel.removeFromSuperview()
        })
    }
}

A: okay do the following step
Step -1
drag and drop UIbutton to the current viewcontroller
Step -2
delete the default title for your button

step-3
UIbutton has property Image --> go to image add your camera Image like follow and finally change the button frame based on your need

Step - 4
go to connection Inspector --> select your camera button event of Touch Up Inside and create the event for your button , for e.g

option - 2
if you want to proceed with your imageview I mean you dont  want to proceed with UIButton then follow this code
 let cameraTap = UITapGestureRecognizer(target: self, action: #selector(cameraTapped))
    displayloginimg.isUserInteractionEnabled = true
    displayloginimg.addGestureRecognizer(cameraTap)

and handle the event for your imageview
 @objc func cameraTapped() {
   // open your camera controller here
 }

A: You can achieve this functionality on UIImageView using UITapGestureRecognizer.
Use below code in your viewDidLoad() method.
   override func viewDidLoad() {
            super.viewDidLoad()
            let tapGetsure = UITapGestureRecognizer(target: self,
                                                    action: #selector(self.openCamer))
            tapGetsure.numberOfTapsRequired = 1
            loginimagebtn.gestureRecognizers = tapGetsure
            loginimagebtn.isUserInteractionEnabled = true
    }


text:
Q: Writing Assembler Code System Programming I am working on writing an assembler code. For PASS # 1 I am following all instructions but stuck at the following point
Rule when opcode = 'BYTE'
if OPCODE='BYTE' then
            begin
                  find length of constant in bytes
                  add length to LOCCTR
            end {if BYTE}

It says if OPCODE = 'BYTE'  then find length of constant and add to Location counter (LOCCTR). I didn't got this step. Can some one clarify it to me please.
I also have this sample input program and its output.
Input Program Below
PROG START 0
FIRST STL RETADDR
SECOND LDA =CꞌABCDꞌ
THIRD LDA =XꞌFFꞌ
J @RETADR
DEF BYTE CꞌDEFꞌ
SYM1 EQU 512

Output of the above program
LINE# LOCCTR  LABEL     OPERATION    OPERAND
01    00000   PROG      START        0
02    00000   FIRST     STL          RETADDR
03    00003   SECOND    LDA          =C'ABCD'
04    00006   THIRD     LDA          =X'FF'
05    00009             J            @RETADR
06    0000C   DEF       BYTE         C'DEF'
07    00200   SYM1      EQU           512
08    0000F   SYM2      EQU           *
09    00003   SYM3      EQU          SECOND-FIRST
10    0000F   RETADDR   RESW         1
11    00012             END          FIRST
12    00012   *         =C'ABCD'
13    00016   *         =X'FF'

Program Length = (12 – 0) + 5 = 17
You can see above when we Reach to Line 6   which contains Byte in the next line the LOCCTR movies to 00200. I am not sure how it happened. Please explain it. Thanks

A: The EQU instruction is a compile-time instruction that doesn't put anything in memory. It just sets the symbol on the left to the value on the right. If that value is an asterisk (*), then the value is the current value of LOCCTR. Instead of putting the current location in the LOCCTR column, these instructions display the value assigned to them (in hex). So the 00200 is just hex for 512. Similarly, the 0000F for SYM2 is the current location that was assigned to SYM2. And the 00003 beside SYM3 is the value of SECOND-FIRST, which are the addresses of the first and second instructions.
The BYTE instruction is a compile-time instruction that loads data into memory starting at the current location. The rule simply says to add the length of the data to LOCCTR in order to determine where the next part of the program will go.
Notice that line 6, a BYTE instruction, starts at location 0000C and contains the string 'DEF'. That's 3 characters. 0000C + 3 is 0000F, which is the next LOCCTR value after the EQU instructions (which don't put anything in memory).


text:
Q: Applying correct colours to elevation raster I have a problem to display elevation data with pseudocolours. The channel 1 is from -3.40282e+38 to 149.717 . A colleague used 1.7. and it looks like it should (from blue to Red)
when I use QGis 1.8 the complete raster is red with an unreasonable classified legend with four colours (three with minus values, one with maximum value red)
How do I do this?

A: My first guess is that -3.40282e+38 is the Null value and that your colleague's system correctly recognized and handled that but it doesn't work on your system.
Try specifying the null value or just create a colormap that makes sense.


text:
Q: Ignore commas between quotations when reading CSV Oracle stored procedure UTL_FILE Example data:
1, test, "xy, yz", dog, cat
2, test2, xy, fish, bear

As you can see above, the second column may or may not be enclosed in quotes with a comma as part of the string.
I am simply trying to find a way to ignore the comma within the quotes, if either is there.
I am using UTL_FILE and can't use external tables, I know I know, but I am not the one who gets to make decisions.
I haven't really "tried" anything yet, because I haven't been able to find anything to try in this particular scenario.  I have code that extracts substrings between each comma, but obviously, will split "xy, yz" into 2 separate strings. I have been able to get it to work on ONE row, by using " as the delimiter for that specific column, but that goes to hell, when the next row has no quotes for the second column.

A: If you can get the input file delivered with all fields enclosed in double-quotes (or can translate it after reading; my regex isn't good enough) you can use dbms_utility.comma_to_table; the fields need to be enclosed because (as noted here) the tokens have to be valid object names, so 1 causes an error. For example:
declare
    file utl_file.file_type;
    list varchar2(120);
    tablen binary_integer;
    tab dbms_utility.lname_array;
begin
    file := utl_file.fopen('MY_DIR', 'test1.csv', 'R');
    loop
        begin
            utl_file.get_line(file => file, buffer => list);
        exception
            when no_data_found then
                exit;
        end;
        dbms_output.put_line('Raw list: ' || list);

        dbms_utility.comma_to_table(list => list,
            tablen => tablen, tab => tab);

        for i in 1..tablen
        loop
            dbms_output.put_line('Column ' || i || ': '
                || replace(tab(i), '"'));
        end loop;
    end loop;
    utl_file.fclose(file);
end;
/

gives:
Raw list: "1","test","xy, yz","dog","cat"
Column 1: 1
Column 2: test
Column 3: xy, yz
Column 4: dog
Column 5: cat
Raw list: "2","test2","xy","fish","bear"
Column 1: 2
Column 2: test2
Column 3: xy
Column 4: fish
Column 5: bear
Raw list: "3","test3","ab, cd","rabbit, rabbit","duck"
Column 1: 3
Column 2: test3
Column 3: ab, cd
Column 4: rabbit, rabbit
Column 5: duck

If they aren't quoted then you can use a regex (pattern from here):
declare
    file utl_file.file_type;
    list varchar2(120);
    pattern varchar2(15) := '("[^"]*"|[^,]+)';
    c sys_refcursor;
    i number;
    f varchar2(20);
begin
    file := utl_file.fopen('MY_DIR', 'test2.csv', 'R');
    loop
        begin
            utl_file.get_line(file => file, buffer => list);
        exception
            when no_data_found then
                exit;
        end;

        dbms_output.put_line('Raw list: ' || list);

        open c for
             select level as col,
                 regexp_substr(list, pattern, 1, rownum) split
             from dual
             connect by level <= length(regexp_replace(list, pattern))  + 1;

        loop
            fetch c into i, f;
            exit when c%notfound;
            dbms_output.put_line('Column ' || i || ': ' || replace(f, '"'));
        end loop;
        close c;

    end loop;
    utl_file.fclose(file);
end;
/

which gives:
Raw list: 1,test,"xy, yz",dog,cat
Column 1: 1
Column 2: test
Column 3: xy, yz
Column 4: dog
Column 5: cat
Raw list: 2,test2,xy,fish,bear
Column 1: 2
Column 2: test2
Column 3: xy
Column 4: fish
Column 5: bear
Raw list: 3,test3,"ab, cd","rabbit, rabbit",duck
Column 1: 3
Column 2: test3
Column 3: ab, cd
Column 4: rabbit, rabbit
Column 5: duck

I'm not sure if you really have spaces between the fields as shown in the question. If so, the first method still works and you can add a trim() around tab(i). The second method
breaks down so would need a bit of adjustment...

A: Oracle SQL Developer tool came with a data import wizard that supports CSV. Have a look at § 5.34 of the manual. It is probably easier than processing your csv manually. If any processing need to be done you can do it via excel / perl.


text:
Q: Content in div blocks disapear in mobile? In my site http://www.xn--ntcasinon-v2a.eu/ I used @media codes below to remove some of the content in mobile and it works fine but I am trying to do the exact same thing with the same code in http://www.nya-casino.com/ and the content disappears in mobile. Anyone know what code in the theme causes this?
@media only screen and (min-width: 100px) and (max-width: 780px)  {.info{display:none;}}
@media only screen and (min-width: 100px) and (max-width: 780px)  {.benefits{display:none;}}
@media only screen and (min-width: 100px) and (max-width: 780px)  {.site-title{width:70%;}}
@media only screen and (min-width: 100px) and (max-width: 780px)  {.logo img{max-height:65px;}}

A: You have assigned class="hidden-xs" to all those divs inside the .item divs. That class has this rule which makes the content invisible:
.hidden-xs {
    display: none !important;
}

Since this is a general bootstrap rule (which you probably shouldn't change), you should erase that class from the divs.

A: The only sometimes are ignored by some web browsers, so the code would be like this->
@media screen and (min-width: 100px) and (max-width: 780px)  {.info{display:none;}}
As you see there isn't the word "only".


text:
Q: How can I split a list of strings by chunks when they have some light markdown attributes, in F#? I have a tool that is using a Telegram chatbot to interact with its users.
Telegram limits the call rate, so I use a queue system that gets flushed at regular intervals.
So, the current code is very basic:
// flush the message queue
let flushMessageQueue() =
    if not messageQueue.IsEmpty then       <- messageQueue is a ConcurrentQueue

        // get all the messages
        let messages =
            messageQueue
            |> Seq.unfold(fun q ->
                match q.TryDequeue () with
                | true, m -> Some (m, q)
                | _ -> None)

        // put all the messages in a single string
        let messagesString = String.Join("\n", messages)

        // send the data
        client.SendTextMessageAsync(chatId, messagesString, ParseMode.Markdown)
        |> Async.AwaitTask
        |> Async.RunSynchronously
        |> ignore

this is called at regular interval, while the write is:
// broadcast message
let broadcastMessage message =
    messageQueue.Enqueue(message)
    printfn "%s" (message.Replace ("```", String.Empty))

But as messages became more complex, two problems came at once:
Part of the output is formatted text with simple markdown:

*

*Some blocks of lines are wrapped between ``` sections

*There are some ``` sections as well inside some lines

*The text is UTF-8 and uses a bunch of symbols

Some example of text may be:
```
this is a group of lines
with one, or many many lines
```
and sometimes there are things ```like this``` as well

And... I found out that Telegram limits message size to 4kb as well
So, I thought of two things:

*

*I can maintain a state with the open / close ``` and pull from a queue, wrap each line in triple back ticks based on the state and push into another queue that will be used to make the 4kb block.

*I can keep taking messages from the re-formatted queue and aggregate them until I reach 4kb, or the end of the queue and loop around.

Is there an elegant way to do this in F#?
I remember seeing a snippet where a collection function was used to aggregate data until a certain size but it looked very inefficient as it was making a collection of line1, line1+line2, line1+line2+line3... and then picking the one with the right size.


text:
Q: How to initialize a PostgreSQL database without running the PostgreSQL server In an initialization script, I want to initialize a PostgreSQL directory, but don't need (and don't want) a running PostgreSQL server at this stage.
This would be a no-brainer if I just create the cluster (as user postgres):
initdb -D ...

However, I also need to create the PostgreSQL role, create the database and add some extensions  (also as user postgres):
createuser someuser
createdb -O someuser somedb
echo 'CREATE EXTENSION xyz;' | psql somedb

The latter commands require a running PostgreSQL server. So this whole thing becomes quite messy:
initdb -D ...

# Start PostgreSQL server in background
... &

# Wait in a loop until PostgreSQL server is up and running
while ! psql -f /dev/null template1; do
    sleep 0.5
done

createuser someuser
createdb -O someuser somedb
echo 'CREATE EXTENSION xyz;' | psql somedb

# Kill PostgreSQL server
kill ...

# Wait until the process is really killed
sleep 2

Especially the part that is waiting for the PostgreSQL server is never 100% reliable. I tried lots of variants and each of them failed in roughly 1 of 20 runs. Also, killing that process may not be 100% reliable in a simple shell script, let alone ensuring that it has stopped correctly.
I believe this is a standard problem that occurs in all use cases involving bootstrapping a server or preparing a VM image. So one would expect that in the year 2016, there should be some existing, realiable tooling for that. So my questions are:

*

*Is there a simpler and more reliable way to achieve this?

*For example, is there a way to run a PostgreSQL server in some special mode, where just starts up, executes certain SQL commands, and quits immediately after the last SQL command finished?

*As a rough idea, is there something from the internal PostgreSQL test suite can be reused for this purpose?

A: You are looking for single-user mode.
If you start PostgreSQL like that, you are is a session connected as superuser that waits for SQL statements on standard input.  As soon as you disconnect (with end-of-file), the server process is stopped.
So you could do it like this (with bash):
postgres --single -D /usr/local/pgsql/data postgres <<-"EOF"
CREATE USER ...;
CREATE DATABASE somedb ...;
EOF

postgres --single -D /usr/local/pgsql/data somedb <<-"EOF"
CREATE EXTENSION ...;
EOF


text:
Q: Getting text from Edit Text inside Text Input Layout that has a prefix I am having a Text Input Edit Layout with a TextInputEditText that has a prefix of +254
Below is the code of the Text Input Layout

<com.google.android.material.textfield.TextInputLayout
            android:id="@+id/til_phone_number"
            android:layout_below="@+id/rl_text_view_login_description"
            style="@style/Widget.MaterialComponents.TextInputLayout.OutlinedBox"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginStart="10dp"
            android:layout_marginLeft="10dp"
            android:layout_marginTop="10dp"
            android:layout_marginEnd="10dp"
            android:layout_marginRight="10dp"
            android:layout_marginBottom="10dp"
            android:padding="5dp"
            app:prefixText="+254">

            <com.google.android.material.textfield.TextInputEditText
                android:id="@+id/et_phone_number"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:hint="Enter Phone Number"
                android:inputType="text"
                android:textSize="15sp"/>

        </com.google.android.material.textfield.TextInputLayout>

The problem am having is that when am getting Text from the text input edit text its not getting the prefix its only getting the text entered. How can i get the whole text with the prefix
Below is how i am getting the text

etPhoneNumber.getText().toString().trim()

I have tried removing the trim() but its not getting the prefixText

A: You can get the Prefix text using getPrefixText() method on your 'TextInputLayout' object (til_phone_number) ..
link:- https://developer.android.com/reference/com/google/android/material/textfield/TextInputLayout#getPrefixText()


text:
Q: There is no result type defined for type 'dynamic-jasper' mapped with name 'success' I am trying to use DynamicJasper 5.0.0 with Struts 2.3.4. I am using following code to show data in PDF format
In action class
try {
    FastReportBuilder drb = new FastReportBuilder();
    DynamicReport dr = drb.addColumn("Size", "size", String.class.getName(), 30).setTitle("Size List Report").setSubtitle("This report was generateed at" + new Date()).setUseFullPageWidth(true) //make colums to fill the page width
            .setPrintBackgroundOnOddRows(true).build();

    JRDataSource ds = new JRBeanCollectionDataSource(getSizeList());
    JasperPrint jp = DynamicJasperHelper.generateJasperPrint(dr, new ClassicLayoutManager(), ds);
    JasperViewer.viewReport(jp);    //finally display the report report   [/CODE]
} catch (Exception e) {
    System.out.println("Exception");
}
return SUCCESS;

struts.xml:
<package name="expotpkg" extends="struts-default, json-default,jasperreports-default">
   <result-types>
        <result-type name="dynamic-jasper" class="ar.com.fdvs.dj.webwork.DJResult"/>
    </result-types>

<action name="DownloadSizePdf" class="iland.work.SizesAction" method="fetchDJ">
            <result name="success" type="dynamic-jasper">
                <param name="dynamicReport">dr</param>
                <param name="dataSource">sizeList</param>
                <param name="documentName">Dynamic Report generated with struts 2</param>
                <param name="parameters">params</param>
                <param name="format">PDF</param>
                <param name="layoutManager">classic</param>
            </result>
        </action>
   </package>

While running this I am getting following error
There is no result type defined for type 'dynamic-jasper' mapped with name 'success'.  Did you mean 'dynamicJasper'? - result - file:/E:/Project/cxn/cnx/build/web/WEB-INF/classes/struts.xml:571:58
    at com.opensymphony.xwork2.config.providers.XmlConfigurationProvider.buildResults(XmlConfigurationProvider.java:653)
    at com.opensymphony.xwork2.config.providers.XmlConfigurationProvider.addAction(XmlConfigurationProvider.java:387)
    ... 20 more

I have included following jar files

A: Add this configuration to your package
<result-types>
    <result-type name="dynamicJasper" class="ar.com.fdvs.dj.webwork.DJResult"/>
</result-types>

<action name="DownloadSizePdf" class="iland.work.SizesAction" method="fetchDJ">
    <result name="success" type="dynamicJasper">
        <param name="dynamicReport">dr</param>
        <param name="dataSource">sizeList</param>
        <param name="documentName">Dynamic Report generated with struts 2</param>
        <param name="parameters">params</param>
        <param name="format">PDF</param>
        <param name="layoutManager">classic</param>
    </result>
</action>

The ActionSupport class is under the package name com.opensymphony.xwork2. The error is occurred from the configuration of the plugin you use with Struts2 which is incompatible to the version of Struts you use.


text:
Q: Latest snapshot from gradle We are using gradle to publish locally and remote (nexus) to a snapshot repository (using the 'maven-publish' plugin). When I make a local build, I would like to use the latest snapshot version either from my local repository or the remote one. Now when gradle finds one locally the remote one is not considered anymore.
Is there a way to configure this or should I use other plugins?

A: Unfortunately, Gradle doesn't (as of 1.10) support getting the latest snapshot across multiple repositories. In Maven, this works (only) because the local Maven repo is treated specially, and a snapshot found there won't terminate the search.


text:
Q: Render Rails query as JSON for jQuery I have a javascript function that takes data from Rails and presents it.
The format it needs:
[
  {
    title: 'All Day Event',
    start: new Date(y, m, 1)
  },
  {
    title: 'Long Event',
    start: new Date(y, m, d-5),
    end: new Date(y, m, d-2)
  }
]

I'm trying to present this data directly from Rails:
<%= raw @bookings.as_json( only: [:title, :start, :end] ).collect{|o| o["booking"]} %>

This is pretty close, producing:
[{"end"=>nil, "start"=>nil, "title"=>...}, {...}, {...}]

All I have left to do now is change each => into :.

*

*Am I going about this problem the best way?

*If so, how can I make this final substitution in hash format?

A: Try using to_json instead of as_json. as_json is old syntax and hence may not work.


text:
Q: column-wise merging of multiple files in specific order I want to perform column-wise merging of multiple files considering the increasing order of file names. To be specific, I have renamed 163 files as 1.lrr, 2.lrr,3.lrr...163.lrr and I used following command to merge multiple files:
    Paste -d "\t" *.lrr > all_samples.lrr

However, It combined column in some strange order of filenames. It started file merging with the file 100.lrr instead of file 1.lrr. Later on, it combined column from files 101.lrr until 109.lrr. Is it possible to modify this command so that it also considers numerically sorting of file names while merging the column?

A: Try this:
paste $(ls | grep -E "*.lrr" | sort -n) > all_samples.lrr


text:
Q: How to disable row header in devexpress xtragrid Hai all,
I want to know how to disable row header in Devexpress xtragrid (grid control ) . In normal we are disabling the property of DataGrid by row header visbile into false.But how to disable in Devexpress.
Please Help
EDIT

A: At last i found the answer !!!
set the GridView.OptionsView.ShowIndicator  property to False.

A: I am not sure that this is what you want to achieve, but to hide a column, you should set its Visible property to false.  I.e.
GridView1.Columns["SomeFieldName"].Visible = false;
If this does not help, please explain the needed functionality in greater details and I will update my answer....


text:
Q: Использование кнопки "Назад" телефона в мобильной версии сайта На некоторых телефонах под Android'ом присутствует физическая кнопка "назад". В случае нажатия данной кнопки при просмотре веб-страницы на телефоне, обычно мы возвращаемся на предыдущую страницу.
Возможно ли привязать данную кнопку к функции закрытия pop-up окна на сайте. Так как неудобно, когда вместо закрытия окна, страница полностью перезагружается.
Спасибо!

A: При окрытии модально окна с помощью window.history.pushState добавить к URL хеш, например #popup (это сэмулирует переход на другую страницу, но при этом не перезагрузит страницу) и создать слушетеля события смены URL:
window.addEventListener('popstate', function(e){
  ...
}, false);

И в этом обработчеке закрыть popup и удалить сам обработчик.


text:
Q: rails inverse of a scope Is there a method to negate the result of a scope?
I have 3 models, associated by has_many :through association
user.rb
class User < ActiveRecord::Base
    has_many :user_training_maps
    has_many :trainings, through: :user_training_maps
end

training.rb
class Training < ActiveRecord::Base
    has_many :user_training_maps
    has_many :users, through: :user_training_maps
end

user_training_map.rb
class UserTrainingMap < ActiveRecord::Base
    belongs_to :user
    belongs_to :training
end

Before, I want to find all users belonging (enrolled) to a training. In user.rb, this works:
scope :all_enrolled, -> { joins(:trainings) }
Now, I need help to find all users NOT belonging (unenrolled) to a training. I can't get this to work:
scope :all_unenrolled, -> { !joins(:trainings) }
instead, it simply returns all the users. Something like unenrolled users = (all users) - (enrolled users)

A: Try this
scope : all_enrolled, -> { joins(:trainings) }
scope :not_enrolled, -> { where.not(id: all_enrolled) }

A: ActiveRecord has left_joins for a while now, so you should be able to do it directly in the same way you'd do it if you were to write plain SQL:
  scope :not_enrolled, { left_joins(:trainings).where(trainings: {id: nil}) }


text:
Q: How to accelerate the identification of a single tap over a double tap? I have a UITableView with row where I added single tap and double tap gestures:
let doubleTap = UITapGestureRecognizer(target: self, action: "doubleTap:")
doubleTap.numberOfTapsRequired = 2
doubleTap.numberOfTouchesRequired = 1

let singleTap = UITapGestureRecognizer(target: self, action: "singleTap:")
singleTap.numberOfTapsRequired = 1
singleTap.numberOfTouchesRequired = 1
singleTap.requireGestureRecognizerToFail(doubleTap)

tableView.addGestureRecognizer(doubleTap)
tableView.addGestureRecognizer(singleTap)

Is there a way to reduce the time between when the first tap is made and when the gesture recognizer realize that it is a single tap and not a double tap?
I'm asking this because when I do a single tap, the new viewController appear quite late, giving a feeling that the app lags.

A: Full Implementation of Markus's Swift 3 version of eladleb's original solution.

Create subclass file UIShortTapGestureRecogninzer
import UIKit
import UIKit.UIGestureRecognizerSubclass

class UIShortTapGestureRecognizer: UITapGestureRecognizer {
    let tapMaxDelay: Double = 0.3 //anything below 0.3 may cause doubleTap to be inaccessible by many users

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent) {
        super.touchesBegan(touches, with: event)

        DispatchQueue.main.asyncAfter(deadline: .now() + tapMaxDelay) { [weak self] in
            if self?.state != UIGestureRecognizerState.recognized {
                self?.state = UIGestureRecognizerState.failed
            }
        }
    }
}

Note: When adding UIGestureRecognizer only doubleTap needs to be of type UIShortTapGestureRecognizer & singleTap.require(toFail: doubleTap) is required.
func addBoth (views: UIView, selectorSingle: Selector, selectorDouble: Selector) {
    let doubleTap:UIShortTapGestureRecognizer = UIShortTapGestureRecognizer(target: self, action: selectorDouble)
    doubleTap.numberOfTapsRequired = 2
    views.addGestureRecognizer(doubleTap)

    let singleTap:UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: selectorSingle)
    singleTap.numberOfTapsRequired = 1
    singleTap.require(toFail: doubleTap)
    views.addGestureRecognizer(singleTap)
}

A: Swift 5 implementation of Nico's accepted answer.
class UIShortTapGestureRecognizer: UITapGestureRecognizer {
    var maximumTapLength: Double = 0.3

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent) {
        super.touchesBegan(touches, with: event)
        delay(delay: maximumTapLength) {
            // Enough time has passed and the gesture was not recognized -> It has failed.
            if  self.state != .ended {
                self.state = .failed
            }
        }
    }

    func delay(delay:Double, closure:@escaping ()->()) {
        DispatchQueue.main.asyncAfter(deadline: .now() + delay, execute: closure)
    }
}

A: I found the answer on this link
The swift version:
class UIShortTapGestureRecognizer: UITapGestureRecognizer {
    let tapMaxDelay: Double = 0.3

    override func touchesBegan(touches: NSSet!, withEvent event: UIEvent!) {
        super.touchesBegan(touches, withEvent: event)
        delay(tapMaxDelay) {
            // Enough time has passed and the gesture was not recognized -> It has failed.
            if  self.state != UIGestureRecognizerState.Ended {
                self.state = UIGestureRecognizerState.Failed
            }
        }
    }
}

With delay(delay: Double, closure:()->()):
class func delay(delay:Double, closure:()->()) {
        dispatch_after(dispatch_time( DISPATCH_TIME_NOW, Int64(delay * Double(NSEC_PER_SEC))), dispatch_get_main_queue(), closure)
    }

A: for future, full implementation by Howard Yang, here's links:
https://github.com/oney/SingleDoubleTapGestureRecognizer
 let tap = SingleDoubleTapGestureRecognizer(target: self, singleAction: Selector("singleTap"), doubleAction: Selector("doubleTap"))
        tap.duration = 0.8
        view.addGestureRecognizer(tap)

https://github.com/oney/SingleDoubleTapGestureRecognizer/blob/master/Pod/Classes/SingleDoubleTapGestureRecognizer.swift
//
//  SingleDoubleTapGestureRecognizer.swift
//  SingleDoubleTapGestureRecognizer
//
//  Created by Howard Yang on 08/22/2015.
//  Copyright (c) 2015 Howard Yang. All rights reserved.
//

import UIKit

public class SingleDoubleTapGestureRecognizer: UITapGestureRecognizer {
    var targetDelegate: SingleDoubleTapGestureRecognizerDelegate
    public var duration: CFTimeInterval = 0.3 {
        didSet {
            self.targetDelegate.duration = duration
        }
    }
    public init(target: AnyObject, singleAction: Selector, doubleAction: Selector) {
        targetDelegate = SingleDoubleTapGestureRecognizerDelegate(target: target, singleAction: singleAction, doubleAction: doubleAction)
        super.init(target: targetDelegate, action: Selector("fakeAction:"))
        numberOfTapsRequired = 1
    }
}
class SingleDoubleTapGestureRecognizerDelegate: NSObject {
    var target: AnyObject
    var singleAction: Selector
    var doubleAction: Selector
    var duration: CFTimeInterval = 0.3
    var tapCount = 0

    init(target: AnyObject, singleAction: Selector, doubleAction: Selector) {
        self.target = target
        self.singleAction = singleAction
        self.doubleAction = doubleAction
    }

    func fakeAction(g: UITapGestureRecognizer) {
        tapCount = tapCount + 1
        if tapCount == 1 {
            delayHelper(duration, task: {
                if self.tapCount == 1 {
                    NSThread.detachNewThreadSelector(self.singleAction, toTarget:self.target, withObject: g)
                }
                else if self.tapCount == 2 {
                    NSThread.detachNewThreadSelector(self.doubleAction, toTarget:self.target, withObject: g)
                }
                self.tapCount = 0
            })
        }
    }
    typealias DelayTask = (cancel : Bool) -> ()

    func delayHelper(time:NSTimeInterval, task:()->()) ->  DelayTask? {

        func dispatch_later(block:()->()) {
            dispatch_after(
                dispatch_time(
                    DISPATCH_TIME_NOW,
                    Int64(time * Double(NSEC_PER_SEC))),
                dispatch_get_main_queue(),
                block)
        }

        var closure: dispatch_block_t? = task
        var result: DelayTask?

        let delayedClosure: DelayTask = {
            cancel in
            if let internalClosure = closure {
                if (cancel == false) {
                    dispatch_async(dispatch_get_main_queue(), internalClosure);
                }
            }
            closure = nil
            result = nil
        }

        result = delayedClosure

        dispatch_later {
            if let delayedClosure = result {
                delayedClosure(cancel: false)
            }
        }

        return result;
    }

    func cancel(task:DelayTask?) {
        task?(cancel: true)
    }
}

A: I'd rather recommend to use canBePrevented(by:) function, it takes in account amount of taps to perform and won't run you double-tap gesture recognizer unless first one is recognized/failed.
canBePrevented(by:)

A: Inspired by Howard Yang's implementation, Swift 5.1 using DispatchWorkItem:
public class SingleDoubleTapGestureRecognizer: UITapGestureRecognizer {
    var targetDelegate: SingleDoubleTapGestureRecognizerDelegate
    public var timeout: TimeInterval = 0.3 {
        didSet {
            self.targetDelegate.timeout = timeout
        }
    }

    public init(target: AnyObject, singleAction: Selector, doubleAction: Selector) {
        targetDelegate = SingleDoubleTapGestureRecognizerDelegate(target: target, singleAction: singleAction, doubleAction: doubleAction)
        super.init(target: targetDelegate, action: #selector(targetDelegate.recognizerAction(recognizer:)))
    }
}

class SingleDoubleTapGestureRecognizerDelegate: NSObject {
    weak var target: AnyObject?
    var singleAction: Selector
    var doubleAction: Selector
    var timeout: TimeInterval = 0.3
    var tapCount = 0
    var workItem: DispatchWorkItem?

    init(target: AnyObject, singleAction: Selector, doubleAction: Selector) {
        self.target = target
        self.singleAction = singleAction
        self.doubleAction = doubleAction
    }

    @objc func recognizerAction(recognizer: UITapGestureRecognizer) {
        tapCount += 1
        if tapCount == 1 {
            workItem = DispatchWorkItem { [weak self] in
                guard let weakSelf = self else { return }
                weakSelf.target?.performSelector(onMainThread: weakSelf.singleAction, with: recognizer, waitUntilDone: false)
                weakSelf.tapCount = 0
            }
            DispatchQueue.main.asyncAfter(
                deadline: .now() + timeout,
                execute: workItem!
            )
        } else {
            workItem?.cancel()
            DispatchQueue.main.async { [weak self] in
                guard let weakSelf = self else { return }
                weakSelf.target?.performSelector(onMainThread: weakSelf.doubleAction, with: recognizer, waitUntilDone: false)
                weakSelf.tapCount = 0
            }
        }
    }
}

Usage:
let singleDoubleTapRecognizer = SingleDoubleTapGestureRecognizer(
    target: self,
    singleAction: #selector(handleTapGesture),
    doubleAction: #selector(handleDoubleTapGesture)
)


text:
Q: CloudKit CKModifyRecordsOperation gives me a "Protection data didn't match" I'm trying to upload some record changes with CloudKit. I'm truing to use a CKModifyRecordsOperation to do a batch upload of records that have changed on the device. The records are all in a custom zone
For some reason the operation keeps coming back with an error telling me ""Protection data didn't match"
Here's the code:
- (void)updloadLocalChangesWithCompletionBlock:(void (^)(NSError *error))completionBlock
{
   // Initialize the data
   NSArray *localChanges = self.localChanges;
   NSArray *localDeletions = self.localDeletions;

   // Initialize the database and modify records operation
   CKDatabase *database = [CKContainer defaultContainer].privateCloudDatabase;
   CKModifyRecordsOperation *modifyRecordsOperation = [[CKModifyRecordsOperation alloc] initWithRecordsToSave:localChanges recordIDsToDelete:localDeletions];
   modifyRecordsOperation.savePolicy = CKRecordSaveAllKeys;

   NSLog(@"CLOUDKIT Changes Uploading: %d", localChanges.count);

   // Add the completion block
   modifyRecordsOperation.modifyRecordsCompletionBlock = ^(NSArray *savedRecords, NSArray *deletedRecordIDs, NSError *error) {
       if (error) {
           NSLog(@"[%@] Error pushing local data: %@", self.class, error);
       }

       [self.localChanges removeObjectsInArray:savedRecords];
       [self.localDeletions removeObjectsInArray:deletedRecordIDs];

       completionBlock(error);
   };

   // Start the operation
   [database addOperation:modifyRecordsOperation];
}

Here is the error it's giving me:
[CloudKitSyncManager] Error Uploading Changes: <CKError 0x156654a0: "Partial Failure" (2/1011); "Failed to modify some records"; partial errors: {
    default-00001:(ZoneName:UserRecordID) = <CKError 0x1550b5a0: "Server Record Changed" (14/2037); "Error saving record <CKRecordID: 0x18080430; default-00001:(ZoneName:UserRecordID)> to server: Protection data didn't match">
}>

A: If you use the savePolicy of CKRecordSaveIfServerRecordUnchanged, it is necessary to pre-fetch a remote CKRecord (and update that particular instance) before CKModifyRecordsOperation. If you allocate a "local" CKRecord and up-reference it through CKRecordID with a matching initWithRecordName:, CloudKit cannot compare a remote change-tag to a (missing) local change-tag, so it fails with CKErrorServerRecordChanged and the somewhat vague error message: "protection data didn't match".
However, if a remote CKRecord does not exist at all, surely the server record has not changed and the save operation can proceed. This behavior is the basis for the "Save If Not Exists" use case (SQL: INSERT over a PRIMARY KEY). If you allocate a "local" CKRecord and use the savePolicy of CKRecordSaveIfServerRecordUnchanged, it will INSERT, but never UPDATE.
If you use the savePolicy of CKRecordSaveAllKeys and the CKRecordZoneID ownerName of CKOwnerDefaultName, you should be able to save (SQL: UPDATE, with INSERT if necessary) through a "locally" allocated CKRecord, saving a (pre-fetch) trip over the network.
The "Save If Exists" use case (SQL: UPDATE over a PRIMARY KEY) probably cannot be done without a (verification) trip over the network.
A catch: it is not possible to roll both a CKRecordSaveIfServerRecordUnchanged INSERT and a CKRecordSaveAllKeys UPDATE into one atomic transaction, since CloudKit transactions span only a single CKModifyRecordsOperation, across multiple CKRecord/CKRecordID instances. Philosophically speaking, a "transaction" should be able to span multiple "operations" (SQL: queries), not just multiple "records" (SQL: rows).

A: What exactly is in your self.localChanges array? CKRecord I assume, but are the modified records you're uploading based on the same CKRecord objects you downloaded from CloudKit?
I had a similar (albeit not exact) error message when I tried uploading a freshly allocated CKRecord with my local changes and expected it to overwrite the server's copy. I fixed it by downloading the remote copy of my item, applying updates to the CKRecord instance given to me by CloudKit, and then uploading it.

A: You should set write permission for the the corresponding record types in dashboard, I guess.

A: It is worth noting that the solution to this was two-fold. I was also trying to use a custom zone. Wherever I was initializing a CKRecordZoneID the code looked like this:
[[CKRecordZoneID alloc] initWithZoneName:@"CustomZoneName" ownerName:self.userRecordId.recordName];

This should have looked like this
 [[CKRecordZoneID alloc] initWithZoneName:@"CustomZoneName" ownerName:CKOwnerDefaultName];

I believe that this is part of what was causing the "Protection Data Didn't Match Bug", but answer by Dave Teare was also necessary to remedy it.


text:
Q: Proving that in an infinite cyclic group order of every element is infinite
Prove that in an infinite cyclic group order of every element ($\ne e$) is infinite.

I have tried proving this way : If there exists an element of finite order, then it must generate a finite subgroup of $G.$ But this is not possible as by Lagrange's theorem, order of a subgroup must divide order of a group, which is not true here as order of $G$ is infinity.
Is this correct and complete ?

A: It doesn't quite work, as there are infinite groups with elements of (any possible) finite order.
Instead, think that every element of your infinite cyclic group $\langle g \rangle$ is of the form $x = g^k$ for some $k$. What happens if $1 = x^ n = (g^k)^n$ for some $n > 0$?

A: This proof is invalid, since some infinite groups have finite subgroups.  E.g. $\mathbb{Z}_2 \times \mathbb{Z}$ has the subgroup $\mathbb{Z}_2 \times \{0\}$.
In an infinite cyclic group the elements are $$\{\ldots,g^{-3},g^{-2},g^{-1},1,g,g^2,g^3,\ldots,\}$$ for some generator $g$.
If $h \neq 1$ is in this group, then $h=g^k$ for some $k \in \mathbb{Z} \setminus \{0\}$.  So, the subgroup generated by $h$ has the underlying set $$\{\ldots,g^{-3k},g^{-2k},g^{-k},1,g,g^{2k},g^{3k},\ldots,\}.$$

A: That is not correct because Lagrange's theorem presumes the group to be finite, and you can't use it that way, specifically because you're not using the fact that is cyclic.
For example $$G=\mathbb{R}-\lbrace 0 \rbrace$$
$G$ is a group under multiplication and $H=\lbrace 1,-1\rbrace$ is a finite subgroup.
You're correct trying to use negation: if a element generates a finite subgroup, the it means that $g^k=1$ for some $k$. Is that possible if the group is cyclic?

A: If you mean the infinite cyclic group $G := \{x^n | n\in \mathbb{Z}\}$. Then the proof would be by contradiction. Suppose there exists an element $y(\neq 1)\in G$ such that $y^n = 1$. But $y = x^m$ for some $m\in \mathbb{Z}$. Hence $1= y^n = (x^m)^n = x^{mn}$. But this implies G is finite, as then $G = \{x^{-mn+1},\ldots, x^{mn-1}\}$. Contradiction!


text:
Q: SSO (Single sign on ) in MVC has anyone implemented signgle sign on in MVC? Can anyone give me any example for single sign on in MVC.

A: I've implemented a SSO solution between multiple ASP.NET MVC applications hosted on the same parent domain (app1.domain.com, app2.domain.com, ...) by using Forms Authentication and setting the domain property of the cookie in web.config of all applications:
<forms
   name="ssoauth"
   loginUrl="/login"
   protection="All"
   timeout="120"
   requireSSL="true"
   slidingExpiration="false">
   domain="domain.com"
/>

When you set the domain property of the cookie, this cookie will automatically be sent by the client browser to all applications hosted on this domain and will be able to authenticated the user automatically.
If you want to implement a cross domain SSO using Forms Authentication here's what you could do:

*

*The user navigates to foo.com and signs in. The application hosted on foo.com uses standard Forms Authentication, nothing fancy.

*The user decides to go to bar.com and clicks on a link that you created. This link could contain a token parameter which will contain the encrypted username. This encryption could be done using the machine keys and look something like this: https://bar.com?token=ABC.

*The application hosted on bar.com receives the request and because it uses the same machine keys as the other application it is capable of decrypting the token and fetching the username. Then it simply signs in the user by emitting an authentication cookie locally and the user is automatically signed in bar.com.

A: Below is an example for SSO for websites sharing same domain
http://www.codeproject.com/Articles/27576/Single-Sign-on-in-ASP-NET-and-Other-Platforms

A: Please see my answer here. Basically you need to set Authentication mode to windows on web.config and use HttpContext class to retrieve user identity which takes data from Active directory
https://stackoverflow.com/a/40938106/950944


text:
Q: jsplumb state machine on multiple tabs I am designing a web page for state machine and I am using jsplumb state machine. I want to draw this state machine on multiple tabs. Tabs are created dynamically using 'New' button

            Untitled-1

In the div area of class 'fsm', state machine is drawn dynamically by dragging state machine(SM) blocks and dropping it in 'fsm' div. If there are multiple tabs, after dropping SM block in fsm div, it is draggable in fsm div only on 1st tab and not in another tabs. For example, if there are 2 tabs, I can re-position SM blocks only in 1st tab, on 2nd tab when I start dragging SM block, it disappears from fsm div and its left-top coordinates become negative.
This is the code for fsm div -
$("div.fsm").droppable({
    accept: ".cTemp, .rTemp",
    hoverClass: "ui-state-hover",
    drop: function (event, ui) {
        var draggable = $(ui.draggable[0]);
        if (draggable.attr("class").indexOf("rTemp") > -1) {
            $("

").text("rect" + rectI).appendTo(this);
            $("#rect" + rectI).append("

").appendTo(this);
            $("#rect" + rectI).addClass("draggable");

            jsPlumb.draggable($(".rBase"),{containment: ".fsm", zIndex: 30});
        } else if (draggable.attr("class").indexOf("cTemp") > -1) {
            $("

").text("circle" + circleI).appendTo(this);
            $("#circle" + circleI).append("

").appendTo(this);
            $("#circle" + circleI).addClass("draggable");

        jsPlumb.draggable($(".cBase"),{containment: ".fsm", zIndex: 30});

       }

       jsPlumbDemo.init();
}

});
This might be because fsm div is created dynamically or there are more than 1 fsm divs. What would be the best option to handle this multitab situation ?
I tried to remove fsm div from all tabs except the active tab then it works. I can drag SM blocks from tab content even if there are more than 1 tabs since there is only 1 fsm div. But then I have to add fsm div back again to the tab when I switch to that tab.
Then which is the best way to save the tab's content before switching to any other tab and load it back when that tab is opened ?
To give my background, this is my first time to work on jquery/jsplumb so detailed explanation is very much appreciated.

A: Here is a couple of comments

*

*You can use the Jquery command hasClass() instead of attr("class")indexOf

*To handle tabs I guess you are using the Jquery command tabs() ? in that case you don't need to save anything.

*As far as your dropping issue is concerned you should use the appendTo: property in the draggable() parameters specifying which div they are supposed to be dropped to. You can change the target tab by reacting to the jquery tab select event this way
$("#tabs").tabs({
    select: function(event, ui) {
        // Your code
    }
 });
You can play with this fiddle I made for you
http://jsfiddle.net/webaba/sy9PJ/
$(document).ready(function () {

    // Calls custom select tab function, scroll down for implementation
    selectTab(1);

    // Block models are made draggable
    function selectTab(tabIndex) {
        var tabName = '#tab'+tabIndex;
        $(".model").draggable({
            appendTo: tabName,
            helper: 'clone'
        });
    }

    // Tabs div is formatted as tabs by jquery
    $("#tabs").tabs({
        select: function (event, ui) {
            selectTab(ui.index + 1);
        }
    });

    //Sets canvas as droppable
    $(".tab").droppable({

        accept: ".model",
        drop: function (event, ui) {
            var newBlock = ui.helper.clone();
            $(newBlock).removeClass("model").addClass("block");
            $(this).append($(newBlock));
            $(newBlock).draggable({containment:$(this)});
            return true;
        }
    });
});

and the html

Block1

Block2

Tab1

Tab2

Tab3

Tab1

Tab2

Tab3

and the CSS
#container {
    width:100%;
    height:300px;
}
#tabs {
    height:300px;
    width:70%;
    float:right;
    border:1px solid black;
}
.tab{
    height:100%;
    border:1px dotted blue;
}
#library {
    border:1px solid black;
    width:20%;
    height:300px;
    float:left;
}
.type1 {
    width:50px;
    height:50px;
    border:1px solid green;
}
.type2 {
    width:50px;
    height:20px;
    border:1px solid red;
}


text:
Q: Showing that the difference of two random varialbes is symmetric Let $X$ and $Y$ be two iid random variables on $(\Omega, \mathcal F, \mathbb P)$. I want to show that $X - Y$ has a symmetric distribution. I know that $\mathbb P_X(A) = \mathbb P_Y(A)$ for every $A \in \mathcal B(\mathbb R)$. How can I show that $\mathbb P_{X-Y} (A) = \mathbb P_{Y-X}(A)$ for every $A \in \mathcal B(\mathbb R)$? I know that it should be enough to analyze the family of intervals $(\infty, x]$, but I don't see how I can relate $\mathbb P(Y\leq x) = \mathbb P(X \leq x)$ to $\mathbb P(X - Y \leq x) = P(Y - X \leq x)$.

A: Let $P_X$ and $P_Y$ denote the distribution of $X$ and $Y$. Then,
$$
P_{X-Y}(A)= \mathbb{E}{[\mathbb{1}\{X-Y\in A\}]}=\\\int_{-\infty}^{+\infty} \int_{-\infty}^{+\infty} \mathbb1\{x-y \in A\} dP_X(x)dP_Y(y)
$$
Since $P_X$ and $P_Y$ are equal, we can write
$$P_{X-Y}(A)=\int_{-\infty}^{+\infty} \int_{-\infty}^{+\infty} \mathbb1\{x-y \in A\} dP_Y(x)dP_X(y)$$.
Then, by the change of variable $x \leftarrow y$ and $y \leftarrow x$, we have
$$P_{X-Y}(A)=\int_{-\infty}^{+\infty} \int_{-\infty}^{+\infty} \mathbb1\{y-x \in A\} dP_Y(y)dP_X(x)\\
=P_{Y-X}(A)$$.


text:
Q: Have OpenCL and OpenGL SL got any "undefined behaviour"? I was told that C and C++ have "undefined behavior", that is, the same code might behave differently on different platforms, or using different compilers, if I use "certain constructs".
Does the same apply to OpenCL and/or OpenGL SL?

A: Yes.

A: Yes, according to the OpenCL specification 1.1 which defines undefined behaviour in the front matter as:

The behavior of an OpenCL API call, built-in function used
  inside a kernel or execution of a kernel that is explicitly not
  defined by OpenCL. A conforming implementation is not required to
  specify what occurs when an undefined construct is encountered in
  OpenCL

For example:

*

*Section 5.2.1 defines several:

*

*"Reading from a buffer or image object created with CL_MEM_WRITE_ONLY inside a kernel"

*"Writing to a buffer or image object created with CL_MEM_READ_ONLY inside a kernel"

*"OpenCL commands that operate on multiple
buffer objects created with the same host_ptr or
overlapping host regions"

*"Concurrent reading from, writing to and copying between overlapping
sub-buffer objects created with the same buffer object"

*Section 5.2.2 also defines a few:

*

*clEnqueueReadBuffer with other commands using the buffer

*clEnqueueReadBuffer whilst the buffer is mapped

There's plenty more ways of invoking undefined behaviour from OpenCL though.
For OpenGL SL (specification) there are quite a few easy to find examples:

*

*"Undefined behavior results from indexing an array with a non-constant expression that's greater than or equal to the array's size or less than 0" (Interestingly if it's a const then it's a compile time error)

*Likewise for accessing vector elements with array subscript notation

*"Reading a varying variable in a
vertex shader returns undefined values if it is read before being written"

*"If this pragma [#pragma STDGL invariant(all)] is used after the declaration of any variables or
functions, then the set of outputs that behave as invariant is undefined"

*"Reading [gl_PointSize or gl_ClipVertex] before writing them results in undefined behavior"

*etc.

A:
I was told that C and C++ have "undefined behavior", that is, the same code might behave differently on different platforms, or using different compilers, if I use "certain constructs".

That's not what undefined behavior actually means. That is the result of undefined behavior, but that's not what it's for.
Specifications are all about defining what happens when you do something. It says what parameter values are good and which are bad. If you pass bad ones, it tells you what errors you get and what the state of the system will be. If the current state is invalid for an operation you attempt to perform, the specification explains what other kinds of errors you get and what that means for the state of the system afterwards.
When you use defined behavior, you are relying on a contract between yourself and the implementation; that contract is called the OpenGL specification. You rely on the implementation to provide the validity checks that the specification requires. And you rely on the implementation doing what the specification says. If the implementation doesn't implement something correctly, then it is breaking the contract.
When the specification says that a certain set of things will result in "undefined behavior", what that means is doing those things is you are breaking the contract. You are off the edge of the map. You are doing something for which the specification does not provide defined behavior; you broke your part of the deal.
To put it another way, your code will be perfectly portable as long as you don't rely on undefined behavior. That's what it means.
Generally, the spec marks something undefined if testing for it would be an onerous burden for implementations. OpenGL does need to be reasonably fast, after all. So burdening the driver by forcing it to test for things that would be nearly impossible to check for is something they try to avoid.
Then, there are tests which are flat-out impossible to test for. In OpenGL, it is illegal to read from and write to the same image, by binding an image as a texture and sampling from it, while simultaneously attaching that image to an FBO and rendering to it. There is no way to guaranteeably test for this scenario.
Oh, you can test for most of it. You could fail on draw calls when the same texture is bound to the FBO and to a sampler. But then, you wouldn't be able to render to different mipmaps of the same texture; remember: each mipmap is a separate image. So you could check to see if the base/max level range allows for the possibility to sample from the mipmap that is bound to the FBO. But that puts a hefty burden on the user, as they would have to be constantly adjusting the base/max level when rendering to different mipmaps. It's much easier for them to just sample from the correct mipmap with textureLOD or similar functions. And you can't determine until runtime whether they are sampling from outside that mipmap level.
OpenCL and OpenGL SL have undefined behavior, just like many specifications. And generally, it's undefined for the same reasons: testing for it would make the implementation unacceptably slower, or testing is flat-out impossible.

A: Yes, there are undefined behaviours (you can grep the spec to find some); but be careful, because those are not the only way for a program to behave differently on different systems: not all OpenGL implementations are completely compilant (in fact, it is likely that most aren't). For instance, Nvidia's drivers allow texture2D to be called in a core profile here, while this causes an error on other platforms (and the latter is the expected behaviour). The best way to know if it will work is to test on several platforms (OSs, GPU, and drivers).