Q:

regex validating single occurences of characters

I want to check an input string to validate a proper text. The validation will be done with javascript and right now I'm using this code:
keychar = String.fromCharCode(keynum);
var text = txtBox.value + keychar;
textcheck = /(?!.*(.)\1{1})^[fenFN,]*$/;
return textcheck.test(text);

The strings that are allowed are for example:
f
e
f,e
n,f,e,F,N
Examples of not allowed:
ff
fe
f,f
f,ee
f,e,n,f
n,,(although this could be ok)
Is this possible to solve with regex in Javascript?

A:

Although it is possible using regex, it produces a rather big regex that might be hard to comprehend (and therefor maintain). I'd go for a "manual" option as Benjam suggested.
Using regex however, you could do it like this:
var tests = [
  'f',
  'e',
  'f,e',
  'n,f,e,F,N',
  'ff',
  'fe',
  'f,f',
  'f,ee',
  'f,e,n,f',
  'n,,',
  'f,e,e'
];

for(var i = 0; i < tests.length; i++) {
  var t = tests[i];
  print(t + ' -> ' + (t.match(/^([a-zA-Z])(?!.*\1)(,([a-zA-Z])(?!.*\3))*$/) ? 'pass' : 'fail'));
}

which will print:
f -> pass
e -> pass
f,e -> pass
n,f,e,F,N -> pass
ff -> fail
fe -> fail
f,f -> fail
f,ee -> fail
f,e,n,f -> fail
n,, -> fail
f,e,e -> fail

as you can see on Ideone.
A small explanation:
^                     # match the start of the input
([a-zA-Z])            # match a single ascii letter and store it in group 1
(?!.*\1)              # make sure there's no character ahead of it that matches what is inside group 1
(                     # open group 2
  ,([a-zA-Z])(?!.*\3) #   match a comma followed by a single ascii letter (in group 3) that is not repeated
)*                    # close group 2 and repeat it zero or more times
$                     # match the endof the input

A:

I don't think you can do it with regexps alone, as they are not very good at looking around in the text for duplicates.  I'm sure it can be done, but it won't be pretty at all.
What you might want to do is parse the string character by character and store the current character in an array, and while you're parsing the string, check to see if that character has already been used, as follows:
function test_text(string) {
    // split the string into individual pieces
    var arr = string.split(',');
    var used = [];

    // look through the string for duplicates
    var idx;
    for (idx in arr) {
        // check for duplicate letters
        if (used.indexOf(arr[idx])) {
            return false;
        }

        // check for letters that did not have a comma between
        if (1 < arr[idx].length) {
            return false;
        }

        used.push(arr[idx]);
    }

    return true;
}

You might also want to make sure that the browser you are running this on supports Array.indexOf by including this script somewhere: Mozilla indexOf


Q:

Can I pass image form data to a PHP function for upload?

I'm trying to use jquery and PHP to upload an image like so:
HTML
<form id="form-photo" enctype="multipart/form-data"><

    Add Photo
    <input type="file" name="photo-img" id="photo-img">

</form>

Current jquery framework looks like this:
$('#photo-img').change(function(){
    var file = this.files[0];

    //console.log(file);
    name = file.name;
    size = file.size;
    type = file.type;

    // I'll do some validation here before proceeding

    var formData = new FormData($('#form-photo'));

    console.log(formData);

   // How do I pass the image form data to a PHP function via jquery?

});

Can I just pass the formData to a PHP function via jquery post?

A:

Tested and working on Goolge Chrome, Opera, Firefox, Safari.
doesn't work with IE8 or lower
Javascript
Create a FormData object and append the file with index photo-img and POST it to your server with the help of XMLHttpRequest
$(function() {
  $('#photo-img').change(function(){
    var file  = this.files[0];

    // do your validation here

    var formData  = new FormData();
    formData.append( 'photo-img', file ); // append the file to form data

    var xhr = false;
    if ( typeof XMLHttpRequest !== 'undefined' ) {
      xhr = new XMLHttpRequest();
    }
    else {
      var versions  = [ "MSXML2.XmlHttp.5.0", "MSXML2.XmlHttp.4.0", "MSXML2.XmlHttp.3.0", "MSXML2.XmlHttp.2.0", "Microsoft.XmlHttp" ];
      for( var i = 0, len = versions.length; i < len; i++ ) {
        try {
          xhr = new ActiveXObject( versions[i] );
          break;
        }
        catch(e) {}
      }
    }
    if ( xhr ) {
      // replace test.php with your own upload script url
      xhr.open( "POST", "test.php", true );
      xhr.onreadystatechange  = function() {
        if ( this.readyState === 4 && this.status == 200 ) {
          var response  = this.response || this.responseText;

          /** Do Something with the reponse **/
          response  = $.parseJSON( response );
          if ( response && response.message ) {
            window.alert( response.message );
          }

        }
      }
      // now send the formData to server
      xhr.send( formData );
    }
  });
});

PHP
A better image upload handling on server side and return a JSON object as response
<?php
  if ( isset( $_FILES["photo-img"] ) ) {
    $error  = false;
    $image  = $_FILES["photo-img"];
    $code   = (int)$image["error"];
    $valid  = array( IMAGETYPE_PNG, IMAGETYPE_JPEG, IMAGETYPE_GIF );
    $folder = dirname( __FILE__ )."/upload/"; // path to folder to where you want to move uploaded file
    $target = $folder.$image["name"];

    if ( !file_exists( $folder ) ) {
      @mkdir( $folder, 0755, true ) ;
    }

    if ( $code !== UPLOAD_ERR_OK ) {
      switch( $code ) {
        case UPLOAD_ERR_INI_SIZE:
          $error  = 'Error '.$code.': The uploaded file exceeds the upload_max_filesize directive in php.ini';
        break;
        case UPLOAD_ERR_FORM_SIZE:
          $error  = 'Error '.$code.': The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form';
        break;
        case UPLOAD_ERR_PARTIAL:
          $error  = 'Error '.$code.': The uploaded file was only partially uploaded';
        break;
        case UPLOAD_ERR_NO_FILE:
          $error  = 'Error '.$code.': No file was uploaded';
        break;
        case UPLOAD_ERR_NO_TMP_DIR:
          $error  = 'Error '.$code.': Missing a temporary folder';
        break;
        case UPLOAD_ERR_CANT_WRITE:
          $error  = 'Error '.$code.': Failed to write file to disk';
        break;
        case UPLOAD_ERR_EXTENSION:
          $error  = 'Error '.$code.': A PHP extension stopped the file upload';
        break;
        default:
          $error  = 'Error '.$code.': Unknown upload error';
        break;
      }
    }
    else {
      $iminfo = @getimagesize( $image["tmp_name"] );
      if ( $iminfo && is_array( $iminfo ) ) {
        if ( isset( $iminfo[2] ) && in_array( $iminfo[2], $valid ) && is_readable( $image["tmp_name"] ) ) {
          if ( !move_uploaded_file( $image["tmp_name"], $target ) ) {
            $error  = "Error while moving uploaded file";
          }
        }
        else {
          $error  = "Invalid format or image is not readable";
        }
      }
      else {
        $error  = "Only image files are allowed (jpg, gif, png)";
      }
    }
    if ( empty( $error ) ) {
      echo json_encode( array( "error" => 0, "message" => "Upload success!" ) );
    }
    else {
      echo json_encode( array( "error" => 1, "message" => $error ) );
    }
    exit();
  }
?>


Q:

concatenate values across columns in data.table, row by row

I have data.table like this:
x <- data.table(
       a = c( 1,     2),
       b = c('foo', 'bar'))

I want to add a new column 'key_' that contains the row-by-row concatenated values of a and b separated by '_':
   a   b  key_
1: 1 foo 1_foo
2: 2 bar 2_bar

For the hard-coded case, there is a simple solution:
x[, key_ := paste0(a, '_', b)]

How could I achieve this in the more generic case when the columns to be concatenated are given as an arbitrarily long character vector?
Thanks for your help!

A:

You can use do.call(), using .SDcols to supply the columns.
x[, key_ := do.call(paste, c(.SD, sep = "_")), .SDcols = names(x)]

.SDcols = names(x) supplies all the columns of x.  You can supply any vector of names or column numbers there.


Q:

AngularJs Data Manipulation before display

I have a simple table in which there are 2 columns: a) Name b) Country. Currently it works fine and displays name of the user and country.
Now I want to add a condition so that if the country is Germany then instead of Germany it should print Europe and if country is Argentina or Brazil it should print South America, for other countries it will remain same, for example UK, Sweden or any other country will be printed as it is.
My angular code is this ::
<!DOCTYPE html>

    {{ x.Name }}
    {{ x.Country }}

And json data in my user-data.php file is this::
{
    "records":[
    {"Name":"Alfreds Futterkiste","City":"Berlin","Country":"Germany"},
    {"Name":"Ana Trujillo Emparedados","City":"México D.F.","Country":"Mexico"},
    {"Name":"Antonio Moreno Taquería","City":"México D.F.","Country":"Mexico"},
    {"Name":"Around the Horn","City":"London","Country":"UK"},
    {"Name":"B's Beverages","City":"London","Country":"UK"},
    {"Name":"Berglunds snabbköp","City":"Luleå","Country":"Sweden"},
    {"Name":"Blauer See Delikatessen","City":"Mannheim","Country":"Germany"},
    {"Name":"Blondel père et fils","City":"Strasbourg","Country":"France"},
    {"Name":"Bólido Comidas preparadas","City":"Madrid","Country":"Spain"},
    {"Name":"Bon app'","City":"Marseille","Country":"France"},
    {"Name":"Bottom-Dollar Marketse","City":"Tsawassen","Country":"Canada"},
    {"Name":"Cactus Comidas para llevar","City":"Buenos Aires","Country":"Argentina"},
    {"Name":"Centro comercial Moctezuma","City":"México D.F.","Country":"Mexico"},
    {"Name":"Chop-suey Chinese","City":"Bern","Country":"Switzerland"},
    {"Name":"Comércio Mineiro","City":"São Paulo","Country":"Brazil"}
    ]
}

A:

There are numerous ways to achieve this in angular. (directives, functions, services, ng-if...etc.)
The cleanest in your case would be a custom filter:
.filter('countryFormat', function() {
    return function(input) {
        if (input != undefined) {
           //Your switch case here
           return 'South America'; // for example
        }
    }
});

And in the html:
{{ x.Country | countryFormat }}


Q:

Disable show response document in hierarchy for browser

I have a view of lotus notes and web browser. I have enabled show response documents and both notes and web browser showing response documents. Notes are for Admin view while web browser for employee view. So I want to create Admin can view all response document on notes but the employee cannot view response document on a web browser.
Below here my view for notes.

Below here my view for a web browser.

My question is, can I disable show response document just for a web browser?
It means, my notes still showing response document but my browser will not showing response document. Thanks for any help!

A:

You can create two views: one for Notes users  (hidden for web users ) and response hierarchy disabled and vice versa one for the web users which is hidden for notes Users with response hierarchy enabled.


Q:

Using Enum values as integers

I have the following enumerated type:
        /// <summary>
        /// TTE Node types.
        /// </summary>
        public enum E_TTE_NODES
        {
            /// <summary>
            /// Represents FCM 0
            /// </summary>
            E_FCM0 = 0,

            /// <summary>
            /// Represents FCM 1
            /// </summary>
            E_FCM1,

            /// <summary>
            /// Represents FCM 2
            /// </summary>
            E_FCM2,

            /// <summary>
            /// Represents DCM 0
            /// </summary>
            E_DCM0,

            /// <summary>
            /// Represents DCM 1
            /// </summary>
            E_DCM1,

            /// <summary>
            /// Represents DCM 2
            /// </summary>
            E_DCM2,

            /// <summary>
            /// Represents CCM 0
            /// </summary>
            E_CCM0,

            /// <summary>
            /// Represents CCM 1
            /// </summary>
            E_CCM1,

            /// <summary>
            /// Represents CCM 2
            /// </summary>
            E_CCM2,

            /// <summary>
            /// Represents PDU C1
            /// </summary>
            E_PDU_C1,

            /// <summary>
            /// Represents the last node.
            /// Must remain last.
            /// </summary>
            E_LAST,
        }

I would like to initialize a generic list like this:
// Should initialize to a capacity of 10
private List<Int32> transmitIndex = new List<Int32>((Int32)E_TTE_NODES.E_LAST);

Yes, I know I can just pass the number 10 as a parameter.  The enum may add more nodes in the future, but E_LAST will always be the last node. My question is my does the compiler say I cannot cast my enum to an int on the above line of code.  Isn't the default value of a enum value an integer?

A:

You can cast an enum type as you have to an int, the problem is probably somewhere else.
This would produce the compiling error you said:
 private List<Int32> transmitIndex = new List<Int32>(E_TTE_NODES.E_LAST);

This would not:
 private List<Int32> transmitIndex = new List<Int32>((Int32)E_TTE_NODES.E_LAST);


Q:

How to update data in array with user input values with java?

I am trying to create a garage with three floors and three lots on each floor. I am fairly new to java, so I am really having trouble with this. I want to ask the user if they are leaving (0) or parking (1), then which floor they were on or want to be on, and which lot they were in or want to be in. Then I want to use that data and update the array to show Reserved for that spot. But what I have isn't working. Any help would be appreciated.
import java.util.Scanner;

public class Parking {
    public static void main(String[] args) {
        String parkingspace[][] = new String[3][3];

        for(int floor=0; floor<parkingspace[0].length; floor++) {
            for(int lot=0; lot<parkingspace[floor].length; lot++) {
                parkingspace[floor][lot]="Empty";
            }
        }
        Scanner scan = new Scanner(System.in);
            while(true){
                for(int floor=0; floor<parkingspace[0].length; floor++) {
                    for(int lot=0; lot<parkingspace[floor].length; lot++) {
                        parkingspace[floor][lot]="Empty";
                        System.out.print("Floor "+floor + ":  Lot #" +lot +":  [" + parkingspace[floor][lot]+"]   ");
                    }
                    System.out.println();
            }
                System.out.println("Are you leaving(0) or parking(1)?");
                int input = scan.nextInt();

                System.out.println("Which floor (0, 1, 2)?");
                int floor = scan.nextInt();

                System.out.println("Which lot (0, 1, 2)?");
                int lot = scan.nextInt();

            if(input==1) {
                if(parkingspace[floor][lot].equals("Empty")) {
                    if(input==1) {
                        parkingspace[floor][lot]="Reserved";
                        System.out.print("Floor "+ floor + ":  Lot #" +lot +":  [" + parkingspace[floor][lot]+"]   ");
}
            }else if(input==0){
                parkingspace[floor][lot]="Empty";
                System.out.print("Floor "+ floor + ":  Lot #" +lot +":  [" + parkingspace[floor][lot]+"]   ");
}
        }
    }
}

A:

You are close. You need to delete the part where you reset all the parking spaces. Also, you probably don't need to print anything after the user has input their choice.
For extra credit, you need to add error checking. What if the user enters space #12345? Or "Hello"? You should handle these cases.
Here's your code, slightly modified:
public static void main(String[]args) {
    String parkingspace[][] = new String[3][3];

    // Make these variables to be consistent
    final String empty    = "EMPTY";
    final String reserved = "RSRVD";

    // Initialize
    for (int floor = 0; floor < parkingspace.length; floor++) {
        for (int lot = 0; lot < parkingspace[floor].length; lot++) {
            parkingspace[floor][lot] = empty;
        }
    }
    Scanner scan = new Scanner(System.in);
    while (true) {
        // Print the parking lot
        for (int floor = 0; floor < parkingspace.length; floor++) {
            System.out.print("Floor " + floor + ": ");
            for (int lot = 0; lot < parkingspace[floor].length; lot++) {
                System.out.print("Lot #" + lot + ":  [" + parkingspace[floor][lot] + "]   ");
            }
            System.out.println();
        }

        // Get user input
        System.out.println("Are you leaving(0) or parking(1)?");
        int input = scan.nextInt();
        System.out.println("Which floor (0, 1, 2)?");
        int floor = scan.nextInt();
        System.out.println("Which lot (0, 1, 2)?");
        int lot = scan.nextInt();

        // Update parking lot
        if (input == 1 && parkingspace[floor][lot].equals(empty)) {
            parkingspace[floor][lot] = reserved;
        }
        else if (input == 0 && parkingspace[floor][lot].equals(reserved)) {
            parkingspace[floor][lot] = empty;
        }
    }
}


Q:

div hover background color with textarea inside

I have a textarea inside a div. The textarea is almost the same as the size of the div, leaving only a narrow strip of the div around it visible. What I want to achieve ( preferrably with CSS only) is have the background of the div change when the mouse cursor is on it, but not when it is over the textarea. In other words, if the mouse cursor is on top of the visible div strip around the textarea, I want the div background color to change, but if it is on top of the textarea itself I do not want it to change
Here is a jsfiddle that illustrates the problem:
http://jsfiddle.net/TS98t/
HTML:
<div class="mydiv">
    <textarea class="mytextarea"></textarea>
</div>

CSS:
.mydiv {
    position: absolute;
    left: 0px;
    top: 0px;
    width: 200px;
    height: 200px;
    background-color: green;
}

.mydiv:hover {
    background-color: blue;
}

.mytextarea {
    position: absolute;
    top: 10px;
    bottom: 10px;
    left: 10px;
    right: 10px;
    resize: none;
    background-color: yellow;
}

The div is green the textarea is yellow. If i move the mouse over the div it becomes blue. But I don't want it to become blue when the mouse is over the textarea.
Thanks in advance.

A:

Selectors Level 4 allows this via the Determining the Subject of a Selector syntax:
.mydiv {
    background-color: green;
}

.mydiv:hover {
    background-color: blue;
}

!.mydiv textarea:hover {
    background-color: green;
}

… but that specification is currently a very early draft and I'd be surprised if there was any browser support for it at all.
Until that, you will need to look to JavaScript for this. For example:
.mydiv.textarea_hover {
  background-color: green;
}

and
var t = document.querySelector('textarea');
var d = t.parentNode;
t.addEventListener('mouseover', function () {
    d.className += " textarea_hover";
});
t.addEventListener('mouseout', function () {
    d.className = d.className.replace(/ textarea_hover/g, "");
});


Q:

CATIA and VB.NET detect closing of CATIA in external app

I latched onto the Catia using:
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim boolCatAlive As Boolean
    boolCatAlive = False

    Try
        Dim myCatia As INFITF.Application
        myCatia = Interaction.GetObject(vbNullString, "CATIA.Application")
        boolCatAlive = True

    Catch ex As Exception
        boolCatAlive = False
    End Try

    Select Case boolCatAlive
        Case True
           'continue loading app, do my stuff

        Case Else
           'end this now
            MsgBox("No running CATIA instance detected, please start a new CATIA instance and re-run this program.", MsgBoxStyle.Critical, "Error")
            End
    End Select

End Sub

So that is a simple boolean switch at the form loading that decides whether the app is going to load or not.
This works ok, but is doing the check only once when the app is started. Is there a way to continually detect CATIA status, so that - if a user exits CATIA in the middle of my app running - app gets notified and realises that the CATIA COM link is no longer alive?
I could also use that to detect selection changes for example?

A:

You can Check it All the time by using a timer.Add a timer and specify the same code in its TICK event.sorry to Post this as an answer.I don't have enough reputation to post comment.
http://vb.net-informations.com/gui/timer-vb.htm
This link will be helpfull to you.


Q:

Renting a simcha hall from a church

Is there a halachic problem with renting a hall that belongs to a church for a bar mitzvah?

A:

There are Halachic problems with entering a church, and even with using a former church building for some other purpose.  (Rabbi Frand has a tape about converting a church into a synagogue.)  So if the social hall is part of the church building, that's one whole set of issues.
If it's just a free-standing social hall that happens to belong to a church, we might still be concerned about your money going to a church?  While a complicated issue, the Mishna says we support non-Jewish charities too.
There could be additional problems simply with what message we're sending.
In short, it's complicated enough (many different opinions about some of the above issues; much may also depend on what type of church it is) that you really need to ask a rabbi.  But I hope this helps describe some of the issues involved.


Q:

Arduino can't output in both led screen and serial monitor at the same time

I am trying to have Arduino output on both LED screen using the LiquidCrystal library, and on Serial Monitor (later to a txt file or something like that).
In my code, I commented out Serial.begin(9600) and then the screen outputs correctly, but as soon as I include it, the serial monitor outputs fine but the screen flips out and outputs gibberish.
I'm fairly new and I know there's something basic I don't know like 9600 should be augmented because so much power is needed maybe?
#include <LiquidCrystal.h>
#include <DHT.h>
#include <math.h>

/*
    * Cannot do both screens and log in the console.
    * Currently Serial 9600 is commented out, to allow to print on the screen
    * Need Fixing
*/

#include "DHT.h"

#define DHTPIN 8     // what digital pin we're connected to

#define DHTTYPE DHT11   // DHT 11
// Connect a 10K resistor from pin 2 (data) to pin 1 (power) of the sensor

DHT dht(DHTPIN, DHTTYPE);

LiquidCrystal lcd(1, 2, 4, 5, 6, 7);

void setup() {
    //Serial.begin(9600);
    Serial.println("Temperature Recorder");

    dht.begin();

    // Now LiquidCrystal led monitor stuff
    lcd.begin(16,2);
    lcd.setCursor(2,0);
    lcd.print("** Wanet **");
    delay(1500);
    lcd.setCursor(1,1);
    lcd.print("Motherfuckers.");
    delay(3000);
    lcd.clear();
}

void loop() {
    // Wait a few seconds between measurements.
    delay(1000);

    // Reading temperature or humidity takes about 250 milliseconds!
    // Sensor readings may also be up to 2 seconds 'old' (its a very slow sensor)
    float h = dht.readHumidity();
    // Read temperature as Celsius (the default)
    float t = dht.readTemperature();
    // Read temperature as Fahrenheit (isFahrenheit = true)
    float f = dht.readTemperature(true);

    // Check if any reads failed and exit early (to try again).
    if (isnan(h) || isnan(t) || isnan(f)) {
    Serial.println("Failed to read from DHT sensor!");
    return;
    }

    // Compute heat index in Fahrenheit (the default)
    float hif = dht.computeHeatIndex(f, h);
    // Compute heat index in Celsius (isFahreheit = false)
    float hic = dht.computeHeatIndex(t, h, false);

    Serial.print("Humidity: ");
    Serial.print(h);
    Serial.print(" %\t");
    Serial.print("Temperature: ");
    Serial.print(t);
    Serial.print(" *C ");
    Serial.print(f);
    Serial.print(" *F\t");
    Serial.print(" | Heat index: ");
    Serial.print(hic);
    Serial.print(" *C ");
    Serial.print(hif);
    Serial.println(" *F");
    Serial.println("------------------------------------");

    //   led screen printing
    lcd.setCursor(0,0);
    lcd.print("Temp:  Humidity:");
    lcd.setCursor(0,1);
    lcd.print(t);
    lcd.print("   ");
    lcd.print(round(f));
    lcd.print("%");

    delay(5000);
    lcd.clear();
    lcd.setCursor(2,0);
    lcd.print("The world");
    lcd.setCursor(4,1);
    lcd.print("OURS");
    delay(6000);
}

Cheers

A:

On the docs of Arduino's Serial

Serial
It communicates on digital pins 0 (RX) and 1 (TX) as well as with the computer via USB. Thus, if you use these functions, you cannot also use pins 0 and 1 for digital input or output.

You have two options or you don't use those 2 pins
like this
LiquidCrystal lcd(2, 3, 4, 5, 6, 7);
or if you must have those pin you might consider to use a library like softwareSerial which emulates the serial communication a pair of pin of your choice. but the serial monitor via USB won't work anyway.


Q:

TSQL to recurse based on a condition

I have a query to get list of members in a group as below
;WITH CTE (GroupName, GroupMember, isMemberGroup)
     AS (SELECT ag.name,
                agm.Member,
                agm.MemberIsGroup
         FROM   tb1 ag
                LEFT JOIN tb2 agm
                  ON ag.ID = agm.ID
         WHERE  ag.name = 'somegroupame')
SELECT *
FROM   CTE

Group Name   Group Member  IsMemberGroup
Admin        John          0
Admin        Sam           0
Admin        GDBA          1
xyz          Dan           0
xyz          GXy           1

I want to write a query to get members of the sub group as well if IsMemberGroup is 1. Please guide me how to achieve that.
The expected result is to get a list of members including members of sub groups for a give group. The recursion should happen for all the sub groups' groups as well if any:
Resultant: Admin
     Group              Group Member
     Admin              John
     Admin              Sam
     Admin(GDBA)        Mike
     Admin(GDBA)        June
     Admin(GDBA/Bcksdmin)Mark

A:

You could solve this problem using a recursive CTE to generate your group member hierarchy.
This example using the following data:
/* Let's create some sample data to experiment with.
 */
DECLARE @Sample TABLE
    (
        GroupName            VARCHAR(50),
        GroupMember            VARCHAR(50),
        IsMemberGroup        BIT
    )
;

INSERT INTO @Sample
    (
        GroupName,
        GroupMember,
        IsMemberGroup
    )
VALUES
    ('Admin', 'John', 0),
    ('Admin', 'Sam', 0),
    ('Admin', 'GDBA', 1),
    ('GDBA', 'Mike', 0),
    ('GDBA', 'June', 0),
    ('GDBA', 'Bcksdmin', 1),
    ('Bcksdmin', 'Mark', 0)
;

The query uses the CTE to calculate the group hierarchy.  This is then joined back to the original data, like so:
/* Using a recursive CTE we can build the group name
 * hierarchy.
 */
WITH [Group] AS
    (
            /* Anchor query returns all top level teams, ie
             * those that do not appear in the group member
             * field.
             */
            SELECT
                s1.GroupName,
                CAST(s1.GroupName AS VARCHAR(MAX))        AS Breadcrumb
            FROM
                @Sample AS s1
                    LEFT OUTER JOIN @Sample AS s2    ON s2.GroupMember = s1.GroupName
            WHERE
                s2.GroupName IS NULL
            GROUP BY
                s1.GroupName

        UNION ALL

            /* Using recursion, find all children.
             * (Sub groups are identified by the IsMemberGroup flag).
             */
            SELECT
                s.GroupMember                            AS GroupName,
                g.Breadcrumb + '/' + s.GroupMember
            FROM
                [Group] AS g
                    INNER JOIN @Sample AS s        ON s.GroupName = g.GroupName
            WHERE
                s.IsMemberGroup = 1
    )
SELECT
    g.Breadcrumb,
    s.GroupMember
FROM
    @Sample AS s
        INNER JOIN [Group] AS g        ON g.GroupName  = s.GroupName
WHERE
    s.IsMemberGroup = 0
;

Although this solution works I would suggest you revisit the table design, if possible.  The column GroupMember is pulling double duty by storing both teams and team members.  Splitting this into Group (with parent lookup column) and GroupMember tables would simplify the task.  Each new table would only need to describe one real world object, making it clearer where new columns should be created.


Q:

Image, file, text uploader and URL shortener

I've made a tiny PHP script that sits on my server and receives images/files and text/urls I send to it from a desktop application. I'm a bit worried about how secure the whole thing is because the upload endpoint is the same URL as users who view the content I've uploaded go to.
This script takes uploaded things and stores them in the database under a unique, random, 5-character alphanumeric string. Text and URLs are stored verbatim (albeit mysqli_escape_string'd) in the database while files (this includes images) are stored in a subfolder named "upload" that the webserver user has 0755 access to. URLs are location redirected, text is displayed raw, and files are fpassthrough()ed when a user requests an existing 5-character string.
The database credentials ($db_*) and upload control variables ($upload_*) are in uploader_settings.inc.php (which is not included here).
index.php:
<?php
/**
 * Make sure the upload directory is chmod'ed to 755
 *
 */
require("./uploader_settings.inc.php");

$conn = mysqli_connect($db_url,$db_user,$db_pass,$db_database);
if (mysqli_connect_errno()) {
    http_response_code(500); //server error
    die();
}
//handle content
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    //all required data?
    if (!isset($_POST['type']) || !isset($_POST['value']) || !isset($_POST['pass'])) {
        http_response_code(400); //bad request
        echo "Malformed request!";
        die();
    }
    //correct password?
    if ($_POST['pass'] != $upload_pass) {
        http_response_code(401); //not authorized
        echo "Missing auth!";
        die();
    }
    //actually do it
    $value =  $_POST['value'];
    $random = random_str(5);
    do {
        $query = mysqli_query($conn,"SELECT * FROM ".$db_table." WHERE shortened = '".$random."';");
        if (mysqli_num_rows($query) == 0) {
            break;
        } else {
            $random = random_str(5);
        }
    } while (true);
    switch ($_POST['type']) {
        case "url":
        case "text":
            mysqli_query($conn,"INSERT INTO ".$db_table." (shortened,type,value) VALUES ('".$random."','".$_POST['type']."','".mysqli_real_escape_string($conn,$value)."');");
            break;
        case "file":
            $file = $_FILES['fileToUpload'];
            $newfile = "./upload/".$random.".".mysqli_real_escape_string($conn,pathinfo($file['name'],PATHINFO_EXTENSION));
            if ($file['error'] == UPLOAD_ERR_OK) {
                if (!move_uploaded_file($file['tmp_name'], $newfile)) {
                    http_response_code(500);
                    echo "File error!";
                    die();
                }
                mysqli_query($conn, "INSERT INTO " . $db_table . " (shortened,type,value) VALUES ('" . $random . "','file','" . $newfile . "');");
            } else {
                http_response_code(500);
                echo "Upload error!";
                die();
            }
            break;
        default:
            http_response_code(500);
            echo "Invalid type";
            mysqli_close($conn);
            die();
    }
    http_response_code(200);
    echo $upload_returnURL.$random;
    mysqli_close($conn);
    die();
} else { //getting a URL
    $query = mysqli_query($conn,"SELECT * FROM ".$db_table." WHERE shortened = '".mysqli_real_escape_string($conn,$_GET['selector'])."';");
    mysqli_close($conn);
    if (mysqli_num_rows($query) > 0) {
        $array = mysqli_fetch_array($query);
        $value = $array['value'];
        switch ($array['type']) {
            case "url":
                header("Location: ".$value);
                die();
            case "text":
                echo $value;
                die();
            case "file":
                header("Content-Type: ".mime_content_type($value));
                fpassthru(fopen($value,"rb"));
                die();
        }
    } else {
        header("Location: ".$upload_failRedirect);
        die();
    }
}

function random_str($length, $keyspace = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ')
{
    $str = '';
    $max = mb_strlen($keyspace, '8bit') - 1;
    for ($i = 0; $i < $length; ++$i) {
        $str .= $keyspace[random_int(0, $max)];
    }
    return $str;
}

And should it matter, .htaccess:
RewriteEngine on
#all files and directories
RewriteCond %{REQUEST_FILENAME} !-f [OR]
RewriteCond %{REQUEST_FILENAME} !-d
#pass to index as perameter
RewriteRule ^(.*)$ index.php?selector=$1 [NC,L,QSA]

A:

Use prepared statements
This, and other SQL statements in your code, is an SQL injection waiting to happen:

mysqli_query($conn,"INSERT INTO ".$db_table." (shortened,type,value) VALUES ('".$random."','".$_POST['type']."','".mysqli_real_escape_string($conn,$value)."');");

Don't construct SQL by embedding user input into a string.
Use prepared statements.
Don't store clear passwords
This suggests that you have somewhere a password stored in clear text:

if ($_POST['pass'] != $upload_pass) {

It's better to store passwords in a hashed form,
so that they cannot be stolen too easily.

A:

Pay close attention to the advice from @janos regarding your SQL injection vulnerability.  I agree with that assessment and so won't he-hash it here.

First, I would consider splitting the upload/record creation endpoint (POST use case) apart from the view/retrieval endpoint (GET use case).  Why introduce the complexity of managing both of these endpoints within a single script?  There is basically nothing to lose into splitting these endpoints, and a lot to gain in terms of simplifying your code.
A rule of thumb you can think about is that the more indented code you have in a script (via conditionals, loops, switches), the more likely you are to have bugs.  So in this case why deal with two wholly different codepaths with different expected results within one script?

I think you have already introduced bad behavior into this script by having the whole GET use case executed within an unconditional else block.  You just assume that if someone arrives at this script while not using POST action, that the request is fine and you go right into querying against the database.  There could be a whole lot of things wrong about that request that you should validate before making the relatively expensive database call. What if the request is not GET at all?  What if selector input parameter is not set, or is not within expected range of values?

In POST path, there should be no reason to try a select against the DB to see if the short code already exists.  If you have this table properly implemented with a unique index on the short code field, there is no reason to pre-select.  You could go directly to insert and check for duplicate index violation error and retry with new code if this fails.  This makes it to where happy path use case no longer takes two queries against the DB, it would only take one.

I am concerned with the whole approach in comparing $_POST['pass'] against some stored password variable (I am assuming this is defined in the include file). Does this mean you have a single password that, if compromised, gives any user of the system the ability to modify any record?  This seems like a poor security strategy, not to mention the apparent plain text nature of this as already noted. You should like have a separate user authentication/authorization mechanism rather having a single password passed at the time of especially since I am seeing nothing in your .htaccess or code (maybe this is in include) that is forcing HTTPS protocol to be used.

Though the code is not shown, here, you did comment that that your DB credentials a re set in the include file.  You should strongly consider moving away from a paradigm where credentials of any kind are stored in your code.  Ideally these are passed from environmental configuration.  Additionally, why would these value be in variables that are able to be changed at run time anywhere in your code?

In POST path, I think you should validate "type" value early in code path like you have done with other validations.  If an invalid value is set, you should use 400 error, not 500 as is currently given.

Why are you using mysqli escape on file name when forming file path?

You have a potential directory traversal vulnerability when creating your file path, as you are doing nothing to validate the path file name input.  What happens if file name has ../../ or similar in name?

You have both CSRF and XSS vulnerabilities in your code.  You should be using form tokens as mitigation against CSRF (this also means you need to be using sessions).  And you need to consider cleansing text input before insert (for example failing if you detect <script> tags or other XSS vectors), and at point of rendering (where you are also not even rendering proper HTML entities.).

I am guessing the GET path doesn't actually work as you are closing your DB connection before retrieving rows!

In your type="test" GET use case, you do not explicitly set http response headers.  This is actually probably not a problem, but this is not consistent with your usage in POST path.

I am not sure why you are using multibyte function in your random string generation function when you are not working with a multibyte "keyspace".

In general, you should get in the habit of using exact comparisons (===, !==) instead of loose comparisions, unless there is some specific reason you need to perform a loose comparison.  This will make your code more resilient against unexpected truthy/falsey evaluations.  That time you spend in typing the extra characters is negligible in comparison to the time you will spent debugging a codebase full of loose comparisons.

You should consider moving away from SELECT * queries.  These are oftentimes wasteful of bandwidth and application memory as most practical cases don't require all columns to be retirieved (so why retrieve them).  For example, you GET path has you sending back the short code in your query when that is the known value you are using for lookup.
One might also find that * selects can make their code fragile to database schema changes.
Finally, you code is much more readable when you see the exact fields that you are working with.  One doesn't need to know the DB schema to understand what the result set looks like.

Why is your random string function defined in this script instead of in the include?  It is good to get in the habit of separating your PHP code into files based on whether they represent application logic (i.e. classes, functions, interfaces, etc.) or whether they actually cause changes in the state of the application or render output. These leads to better code organization.

Your application should probobaly only have 600 permissions (or possibly 644 if other system users need to read to files) in the upload file directory.  I assume none of these files are going to be executed (thus needing 7).

Your code is very happy path oriented.  You just assume your code is going to work as expected.  For example, you assume that all database queries are going to work and have no handling of potentially failing queries.

You have basically no validation of input parameters (outside of their mere existence).  This combined with your happy path only code, means your whole script is very fragile to having unexpected behaviors and security vulnerabilities.


Q:

How to force emacs to use \n instead of \r\n

I have to use windows to write some shell scripts.  I decided to use emacs, but I get a weird error when running the script:
/bin/bash^M: bad interpreter: No such file or directory
Correct me if I'm wrong, but that looks like the shebang ends in \r\n instead of just \n.  How can I tell emacs to only write \n?  I'm in Shell-script major mode.  It's quite surprising this isn't fixed by default.

A:

As Jürgen mentioned, you need to use the set-buffer-file-coding-system. You can say
(set-buffer-file-coding-system 'unix)

and stick that into a function inside the find-file-hook so that it will set it for all the buffers you open. Alternatively, you can put it inside the write-file-hook list so that the file-coding-system is set properly before you dump the file to disk.
For a simpler way out, if you're using the GUI version of Emacs, you can click on the 3rd character in the modeline from the left. It's to toggle between eol formats.


Q:

Find folders by variables and action on them

I am trying to build a script with a variable based on a text file of folder names, find them in one directory and move them to a different directory (or delete them in an additional script).
For example:
$foldernames = Get-Content -Path "C:\Users\Me\Desktop\Folders.txt"
$startpath = "C:\Users\Me\Desktop\Test"
$topath = "C:\Users\Me\Desktop\Moved"

Then find each line item in folder names in the $startpath and if they are found move them to the $topath.

A:

this will do the job. [grin] it fakes reading in your text file of to-move dirs [use Get-Content to do that for real], then gathers a list of dirs in the source location. next, it tests to see if the .Name is in the list of dirs to be moved. finally, it runs Move-Item to move the dir.
note the -WhatIf on the end ... remove that when you are ready to do your live test on your test data set. [grin]
# fake reading in a text file
#    in real life, use Get-Content
$ToMoveDirNameList = @(
    'test1'
    'TuTu'
    'GoGoGadget'
    'WPF'
    )

$SourceDir = $env:TEMP
$DestDir = 'd:\temp'

$SourceDirList = Get-ChildItem -LiteralPath $SourceDir -Directory

foreach ($SDL_Item in $SourceDirList)
    {
    if ($SDL_Item.Name -in $ToMoveDirNameList)
        {
        Move-Item -LiteralPath $SDL_Item.FullName -Destination $DestDir -WhatIf
        }
    }

output ...
What if: Performing the operation "Move Directory" on target "Item: C:\Temp\test1 Destination: D:\temp\test1".
What if: Performing the operation "Move Directory" on target "Item: C:\Temp\TuTu Destination: D:\temp\TuTu".
What if: Performing the operation "Move Directory" on target "Item: C:\Temp\WPF Destination: D:\temp\WPF".

note #2 - there is NO error checking. this will give you lots of red error text if the destination already has a dir with the same name.
note #3 - there is no record of not-found dirs, either. [grin]


Q:

web2py ajax call fails from pages other than index

I am using the web2py ajax function, like this:
In index.html
{{=INPUT(_name='total_buy', _onkeyup=
  "ajax('key',['total_buy'], ':eval')")}}

and in default.py
def key():
return "jQuery('#target').html('%s');" % repr(float(request.vars.total_buy))

This works perfectly.  When a number is typed into the input field, it is immediatly echoed to the target div.
However, when I copy this to another page it stops working.  I do not see the input number being echoed.
For example, I move the code from index.html to plan.html and leave everything else untouched, I continue to see the echo in the index page, but not in the new plan page.
Taking a look at the server log, I see this:
127.0.0.1, 2011-10-15 13:55:50, POST, /medaim/default/key, HTTP/1.1, 200, 0.047000
127.0.0.1, 2011-10-15 13:55:52, POST, /medaim/default/key, HTTP/1.1, 200, 0.047000
127.0.0.1, 2011-10-15 13:55:52, POST, /medaim/default/key, HTTP/1.1, 200, 0.078000
127.0.0.1, 2011-10-15 13:55:59, GET, /medaim/default/plan/1, HTTP/1.1, 200, 0.094000
127.0.0.1, 2011-10-15 13:56:01, POST, /medaim/default/plan/key, HTTP/1.1, 500, 0.250000
127.0.0.1, 2011-10-15 13:56:01, POST, /medaim/default/plan/key, HTTP/1.1, 500, 0.218000
127.0.0.1, 2011-10-15 13:56:02, POST, /medaim/default/plan/key, HTTP/1.1, 500, 0.265000

It seems like, from the plan page, it is calling /medaim/default/plan/key rather than /medaim/default/key
How do I deal with this?

A:

Try
{{=INPUT(_name='total_buy', _onkeyup=
    "ajax('%s', ['total_buy'], ':eval')" % URL('default', 'key'))}}


Q:

show that number theory inequality $a_{1}+a_{2}+\cdots+a_{k}<\frac{5}{2}n$

Let $n,a_{1},a_{2},\cdots,a_{k}$ be postive integers and at least  greater than $1$,and such
$$(a_{1})!\cdot(a_{2})!\cdots(a_{k})!|n!$$
show that
$$a_{1}+a_{2}+\cdots+a_{k}<\dfrac{5}{2}n$$
I have know prove $k=2$ see Erdos 1968problem
But unfortunately I am looking for much smaller bound   Any idea would be helpful.
I think use
$$a_{1}+a_{2}+\cdots+a_{k}-s_{2}(a_{1})-s_{2}(a_{2})-\cdots-s_{k}(a_{k})<n-s_{2}(n)<n$$
where $s_{p}(n)$ is the sum of the digits of $n$ when
written in base $p$
Add it. the constant $\dfrac{5}{2}$ is best?

A:

If there is a counterexample $a_1≥a_2≥⋯≥a_k$ and $a_1≥4$, then new sequence generated by replacing $a_1$ with $a_1−2$ and $2$ is also counterexample. Therefore, we can assume every $a_i$ to be $2$ or $3$.
Because the exponent of $2$ in the factorization of $n!$ is less than $\sum_{i=0}^\infty\frac{n}{2^i}=n$, $k< n$.
Because the exponent of $3$ in the factorization of $n!$ is less than $\sum_{i=0}^\infty\frac{n}{3^i}=\frac{n}{2}$, less than $\frac{n}{2}$ of $a_i$s are equal to or larger than $3$.
Therefore, we have$$\sum_{i=1}^ka_i=2k+\text{#}(a_i=3)<2n+\frac{n}{2}=\frac{5n}{2}$$and it is done!


Q:

creating table using sqlalchemy

Am I missing something here while creating table using sqlalchemy?
from sqlalchemy import create_engine
from sqlalchemy import MetaData, Column, Table, ForeignKey
from sqlalchemy import Integer, String, DateTime

engine = create_engine('postgresql+psycopg2://postgres:password#@localhost:5432/LabData',echo=True)

metadata=MetaData(bind=engine)
main_table=('sample',metadata,
            Column('LIN',String(10),primary_key=True),
            Column('material_type',String(20),nullable=False),
            Column('source',String(20),nullable=False),
            Column('material_description',String(100)),
            Column('quantity',Integer),
            Column('location',String(2)),
            Column('received_by',String(20)),
            Column('received_date',DateTime,nullable=False),
            )

metadata.create_all()

The output on python console is:
2012-04-25 13:13:42,734 INFO sqlalchemy.engine.base.Engine select version()
2012-04-25 13:13:42,796 INFO sqlalchemy.engine.base.Engine {}
2012-04-25 13:13:42,796 INFO sqlalchemy.engine.base.Engine select current_schema()
2012-04-25 13:13:42,796 INFO sqlalchemy.engine.base.Engine {}

When I try to add the data to the table, it says nosuchtableerror.

A:

possible typo?
main_table=('sample',metadata,...

maybe should be
main_table=Table('sample',metadata,...
#          ^^^^^


Q:

AngularJS orderBy does not work with track by in ngOptions?

I am trying to sort ngOptions with track by
This is my template
<select ng-model="asd" ng-options="user.id as user.name for user in users track by user.id | orderBy: 'name'">

This is my controller
function AppCtrl($scope) {
  $scope.users = [
   {id : 25, name: 'Batista'},
   {id : 26, name: 'Ultimate Warrior'},
   {id : 27, name: 'Andre the giant'}
  ];
  $scope.name = 'asdasd';
  $scope.asd = 25;
 }

I wrote a snippet in JSBin to demonstrate this. The problem with this is the sorting does not work. Should I write a custom filter?

A:

In order to use tracking with filters, the track by expression needs to be added after the filter.
Try this instead:
user.id as user.name for user in users | orderBy: 'name' track by user.id

The documentation for ngRepeat mentions this under the "Arguments" section, specifically:

Filters should be applied to the expression, before specifying a tracking expression.

and

For example: item in items | filter:searchText track by item.id is a pattern that might be used to apply a filter to items in conjunction with a tracking expression.


Q:

Open Text file from Oracle Forms Prompt

I am using Oracle Forms and I would like to open a log file (text file) from a prompt. The prompt will ask if the user would like to open the text file and clicking yes would open it. Any recommendations?

A:

i was able to open the text file using the following by providing the full file path with the file name:
x_host('viewfile_nowait',w_filepath);


Q:

How do I solve $\lim_{x \to \infty} x(e^{(1/x)}-1)$ without L'Hopital?

I don't have experience with L'Hopital Rule nor series and thats what most solution are, is there is other method can be used to solve that limit? i thought about trying to use first principle of derivative but i dont know where to begin. i need some help to guide me to the right direction.

A:

This is precisely $$\lim_{x \to +\infty} \frac{\exp\left(\frac 1x\right) - 1}{\frac 1x} = \lim_{u \to 0^{+}} \frac{\exp\left(u \right) - 1}{u}$$
Does that remind you of some derivative?


Q:

jQuery fade - Display div on page load

I have a simple jquery fade working perfectly, I am trying to have it so that when the page is opened the first div is displayed automatically.
Currently when the page loads there is no content
http://jsfiddle.net/Wqc9N/10/
 $(".link").click(function(e) {
      e.preventDefault();
      $('.content-container div').fadeOut('slow');
      $('#' + $(this).data('rel')).fadeIn('slow');
  });

A:

Till now you are registering the click events for every link by this code
$(".link").click(function(e) {
    e.preventDefault();
    $('.content-container div').fadeOut('slow');
    $('#' + $(this).data('rel')).fadeIn('slow');
});

What i suggest is to fire the click once the page Document Object Model (DOM) is ready for JavaScript code to execute
So try this with your code
$( document ).ready(function() {
    $(".link")[0].click();
});

Fiddle


Q:

Show that $\langle x,y\rangle_A = \langle Ax,Ay\rangle$ is an inner product on $\mathbb R^n$

Let $A$ be an $n \times n$ matrix with real enteries. Define $\langle x,y\rangle_A = \langle Ax,Ay\rangle, \quad x,y \in \mathbb R^n$ , where $\langle,\rangle$ is a standard inner product on $\mathbb R^n$. Then  $\langle x,y\rangle_A$ is an inner product iff
1)  $\ker A = \{0\}$.
2) $\operatorname{rank} A= n$.
3) all eigenvalues of $A$ are positive.
4) all eigen value of $A$ are non negative.
Clearly if $\ker A \neq \{0\}$, then there exist $x \neq 0$ such that $Ax =0$, then $\langle Ax, Ax\rangle_A = 0$, then $\langle ,\rangle_A$ is not inner product, so $\ker A = \{0\}$, thus rank of $A$ is $n$.
I am unable to check the 3) and 4) option. Please help to check the other option. Thank you

A:

If $\lambda=0$ is an eigenvalue of $A$ then there is a nonzero $v$ for which $Av=\lambda v=0,$ and you have already noted that in this case $\langle Av,Av \rangle=0.$ So that only leaves possibility 3. There would still be needed a proof that if all eigenvalues positive then one gets an inner product this way.
Added: You seem to have a logic error in treating option (1). That says, that iff kernel of $A$ is zero, then one gets an inner product. But what you did was to assume kernel nonzero, then get that one doesn't get an inner product. This is one direction of the iff statement (1), rather than a refutation of choice (1). So it may be that choice (1) is the correct one after all.
As for choice (3), it does not work since if $A=-I$ all eigenvalues of $A$ are $-1,$ yet one does get an inner product by the construction.
So my suggestion is to try to show the other direction for choice (1), i.e. that if kernel of $A$ is zero then one does get an inner product by the construction.


Q:

Translate mongo nested array query into mongoose

I have the following query working with mongo, it returns the expected result
db.getCollection('trainings').find({"sections.employees.employee":ObjectId("5d3afa1a58a7160ea451d1db")})

but when I try the following call with mongoose, it returns an empty array
Training.find({'section.employees.employee': "5d3afa1a58a7160ea451d1db"})

Need some helping to translate the mongo query to mongoose.
If you need anything else just add a comment and I will post here.
It's worth mentioning that I have already tried passing a new ObjectId with the String value, but it also returns an empty array.
Edit: Query usage
        return await Training.find({'section.employees.employee': "5d3afa1a58a7160ea451d1db"})

Edit: Model
const mongoose = require("mongoose");
const Schema = mongoose.Schema;

const EmployeeSection = new Schema({
    employee: {type: Schema.Types.ObjectId, ref: 'Employee', required: true},
    fulfilled: {type: Boolean, default: null},
});

const Section = new Schema({
    order: {type: Number, required: true},
    date: {type: Date},
    employees: {type: [EmployeeSection]},
    answers: {type: Number},
    hits: {type: Number}
});

const GoalSchema = new Schema({
    understanding: {type: Number, required: true},
    fixation: {type: Number, required: true}
});

const Evidence = new Schema({
    description: {type: String, required: true},
    file: {type: String}
});

const Question = new Schema({
    participants: {type: Number},
    answers: {type: Number},
    hits: {type: Number}
});

const TrainingSchema = new Schema({
    company: {type: Schema.Types.ObjectId, ref: 'Company', required: true, index: true},
    creationDate: { type: Date, default: Date.now },
    title: {type: String},
    obs: {type: String},
    questionNumber: {type: Number},
    reference: {type: String},
    sections: {type: [Section]},
    goals: {
        answers: {type: GoalSchema, required: true},
        hits: {type: GoalSchema, required: true}
    },
    evidences: {type: [Evidence]},
    questions: {type: [Question]},
    area: {type: Schema.Types.ObjectId, ref: 'TrainingArea', required: true},
});

const Training = mongoose.model('Training', TrainingSchema);

module.exports = Training;

I am willing to change the Model schema, if the problem really lays there, but didn't really want to do it.

A:

Why its always a typo?
db.getCollection('trainings').find({"sections.employees.employee":ObjectId("5d3afa1a58a7160ea451d1db")})

Training.find({'section.employees.employee': "5d3afa1a58a7160ea451d1db"})

Forgot s on sections


Q:

Missing data in Fabric for IOS "Crashed: com.apple.root.default-qos"

I'm using Fabric.io to monitor and collect crash data for a IOS app.
I'm receiving now a lot of crash reports for this error "Crashed: com.apple.root.default-qos" but when I check Fabric to analyze it I got the following report:

where the stack-trace of the crash is missing.
What should I do to receive the complete stack-trace?
App uses some libraries imported using CocoaPods.
I'm attaching here also a screenshot with linked libraries:

A:

I have discovered that this report was sent because of missing "Privacy - Face ID Usage Description" (NSFaceIDUsageDescription) in Info.plist.
I have no idea why the report was not complete, but after adding this key my app has stopped crashing.


Q:

You know me best for being magic, but I can also mean a term of time... what am I?

Can someone help me with the following riddle?

You know me best for being magic, but I can also mean a term of time... what am I?

A:

The answer you're looking for is

 spell

Because you can

 cast a spell, or have a short spell of bad weather.


Q:

How to use gulp in laravel on ubuntu 16.04

I have problem with gulp in my project. I installed node, npm, gulp and I created file gulpfile.js.
If I use command gulp never nothing happens.
I don't know what is incorrect.
Please help me.
My code for example:
var gulp = require('gulp'),
    watch = require('gulp-watch'),
    sass = require('gulp-sass'),
    css_ = require('gulp-minify-css'),
    concat = require('gulp-concat'),
    livereload = require('gulp-livereload'),
    lr = require('tiny-lr'),
    clean = require('gulp-clean'),
    less = require('gulp-less'),
    server = lr();

var paths_css = {

    css: [  '/bower_components/AdminLTE/bootstrap/css/bootstrap.min.css',
            '/bower_components/AdminLTE/dist/css/AdminLTE.min.css',
            '/bower_components/AdminLTE/plugins/iCheck/flat/blue.css',
            '/bower_components/AdminLTE/plugins/morris/morris.css',
            '/bower_components/AdminLTE/plugins/jvectormap/jquery-jvectormap-1.2.2.css']
};

gulp.task('css', function() {
   return gulp.src(paths_css.css)
        .pipe(concat('css.css'))
        .pipe(sass())
        .pipe(gulp.dest('public/css/'));
});

gulp.task('default', ['css']);

A:

Try this:
var gulp = require('gulp'),
    watch = require('gulp-watch'),
    sass = require('gulp-sass'),
    css_ = require('gulp-minify-css'),
    concat = require('gulp-concat'),
    livereload = require('gulp-livereload'),
    lr = require('tiny-lr'),
    clean = require('gulp-clean'),
    less = require('gulp-less'),
    server = lr();

var paths_css = {

    css: [  'bower_components/AdminLTE/bootstrap/css/bootstrap.min.css',
            'bower_components/AdminLTE/dist/css/AdminLTE.min.css',
            'bower_components/AdminLTE/plugins/iCheck/flat/blue.css',
            'bower_components/AdminLTE/plugins/morris/morris.css',
            'bower_components/AdminLTE/plugins/jvectormap/jquery-jvectormap-1.2.2.css'] };

gulp.task('css', function() {    return gulp.src(paths_css.css)
        .pipe(concat('css.css'))
        .pipe(sass())
        .pipe(gulp.dest('public/css/')); });

gulp.task('default', ['css']);


Q:

Generate the Matrix Form of 2D Convolution Kernel

We know that a convolution can be replaced by a multiplication with a Toeplitz / Circulant Matrix. Meaning, assume I have convolution kernel $ h $ and matrix $ I $ (Of size $ m \times m $ for example), then there is a matrix $ H $ of size $ m^2 \times m^2 $ such that $ h \ast I $ is the same as $ H I^{cs} $ Where cs for column stacked image resized to $m \times m$ (reshape(H*I(:), [m, m])).
My question is - how to construct $H$? I know that every row of $H$ is responsible for single entry of the resulting multiplication (H(1,:)*I(:) gives the (1,1) entry of the convolution result), so I can try to work very hard to calculate each entry of $H$ (e.g. if the kernel $h$ is of size $3 \times 3$, than the convolution result in entry (i,j) is:
$$ h_{11}\cdot I(i-1,j-1) + h_{12}\cdot I(i-1,j) + h_{13}\cdot I(i-1,j+1) + h_{21}\cdot I(i,j-1) + h_{22}\cdot I(i,j) + h_{23}\cdot I(i,j+1) + h_{31}\cdot I(i+1,j-1) + h_{32}\cdot I(i+1,j) + h_{33}\cdot I(i+1,j+1) $$
except for near the edges of $I$. so it's somewhat possible with a lot of hard work to construct $H$ such that when multiplying by $I^{cs}$ I will get that result). But is there a 'generic' way for this construction? Or perhaps a made MATLAB function?
I am aware of the convmtx2() function in MATLAB, but the resulting matrix is not in the proper dimensions (not even square).

A:

I created a function to create a Matrix for Image Filtering (Similar ideas to MATLAB's imfilter()):
function [ mK ] = CreateImageFilterMtx( mH, numRows, numCols, operationMode, boundaryMode )
% ----------------------------------------------------------------------------------------------- %
% [ mK ] = CreateImageFilterMtx( mH, numRows, numCols, operationMode, boundaryMode )
% Generates an Image Filtering Matrix for the 2D Kernel (The Matrix mH)
% with support for different operations modes (Convolution / Correlation)
% and boundary conditions (Zeros, Symmetric, Replicate, Circular). The
% function should match the use of MATLAB's 'imfilter()' with the same
% parameters.
% Input:
%   - mH                -   Input 2D Convolution Kernel.
%                           Assumed to have odd dimensions.
%                           Structure: Matrix.
%                           Type: 'Single' / 'Double'.
%                           Range: (-inf, inf).
%   - numRows           -   Number of Rows.
%                           Number of rows in the output convolution
%                           matrix.
%                           Structure: Scalar.
%                           Type: 'Single' / 'Double'.
%                           Range: {1, 2, 3, ...}.
%   - numCols           -   Number of Columns.
%                           Number of columns in the output convolution
%                           matrix.
%                           Structure: Scalar.
%                           Type: 'Single' / 'Double'.
%                           Range: {1, 2, 3, ...}.
%   - operationMode     -   Operation Mode.
%                           Sets whether to use Convolution or Correlation
%                           for the operation mode.
%                           Structure: Scalar.
%                           Type: 'Single' / 'Double'.
%                           Range: {1, 2}.
%   - boundaryMode      -   Boundary Condition Mode.
%                           Sets the boundary condition mode for the
%                           filtering. The options are - Zeros, Symmetric,
%                           Replicate and Circular.
%                           Structure: Scalar.
%                           Type: 'Single' / 'Double'.
%                           Range: {1, 2, 3, 4}.
% Output:
%   - mK                -   Convolution Matrix.
%                           The output filtering matrix. Multiplying in
%                           the column stack form on an image should be
%                           equivalent to applying 'imfilter()' on the
%                           image.
%                           Structure: Matrix (Sparse).
%                           Type: 'Single' / 'Double'.
%                           Range: (-inf, inf).
% References:
%   1.  MATLAB's 'convmtx2()' - https://www.mathworks.com/help/images/ref/convmtx2.html.
% Remarks:
%   1.  The height and width of 'mH' are assumed to be odd number. In case
%       either or both are even the user should pad the kernel with zeros
%       (Either a row, column or both). according to the anchor of the
%       kernel the user do the padding pre or post the kernel.
% TODO:
%   1.  Refactor the code to share the common operations of different
%       boundary modes.
% Release Notes:
%   -   1.0.001     30/12/2019  Royi Avital
%       *   Fixed some bugs related to using 'numCols' instead of 'numRows'
%           in the calculation of 'pixelShift' for the cases 'jj + ll >
%           numCols' and 'jj + ll < 1'.
%   -   1.0.000     16/01/2018  Royi Avital
%       *   First release version.
% ----------------------------------------------------------------------------------------------- %

OPERATION_MODE_CONVOLUTION = 1;
OPERATION_MODE_CORRELATION = 2;

BOUNDARY_MODE_ZEROS         = 1;
BOUNDARY_MODE_SYMMETRIC     = 2;
BOUNDARY_MODE_REPLICATE     = 3;
BOUNDARY_MODE_CIRCULAR      = 4;

switch(operationMode)
    case(OPERATION_MODE_CONVOLUTION)
        mH = mH(end:-1:1, end:-1:1);
    case(OPERATION_MODE_CORRELATION)
        % mH = mH; %<! Default Code is correlation
end

switch(boundaryMode)
    case(BOUNDARY_MODE_ZEROS)
        mK = CreateConvMtxZeros(mH, numRows, numCols);
    case(BOUNDARY_MODE_SYMMETRIC)
        mK = CreateConvMtxSymmetric(mH, numRows, numCols);
    case(BOUNDARY_MODE_REPLICATE)
        mK = CreateConvMtxReplicate(mH, numRows, numCols);
    case(BOUNDARY_MODE_CIRCULAR)
        mK = CreateConvMtxCircular(mH, numRows, numCols);
end

end

function [ mK ] = CreateConvMtxZeros( mH, numRows, numCols )
%UNTITLED6 Summary of this function goes here
%   Detailed explanation goes here

numElementsImage    = numRows * numCols;
numRowsKernel       = size(mH, 1);
numColsKernel       = size(mH, 2);
numElementsKernel   = numRowsKernel * numColsKernel;

vRows = reshape(repmat(1:numElementsImage, numElementsKernel, 1), numElementsImage * numElementsKernel, 1);
vCols = zeros(numElementsImage * numElementsKernel, 1);
vVals = zeros(numElementsImage * numElementsKernel, 1);

kernelRadiusV = floor(numRowsKernel / 2);
kernelRadiusH = floor(numColsKernel / 2);

pxIdx       = 0;
elmntIdx    = 0;

for jj = 1:numCols
    for ii = 1:numRows
        pxIdx = pxIdx + 1;
        for ll = -kernelRadiusH:kernelRadiusH
            for kk = -kernelRadiusV:kernelRadiusV
                elmntIdx = elmntIdx + 1;

                % Pixel Index Shift such that pxIdx + pxShift is the linear
                % index of the pixel in the image
                pxShift = (ll * numRows) + kk;

                if((ii + kk <= numRows) && (ii + kk >= 1) && (jj + ll <= numCols) && (jj + ll >= 1))
                    vCols(elmntIdx) = pxIdx + pxShift;
                    vVals(elmntIdx) = mH(kk + kernelRadiusV + 1, ll + kernelRadiusH + 1);
                else
                    vCols(elmntIdx) = pxIdx;
                    vVals(elmntIdx) = 0; % See the accumulation property of 'sparse()'.
                end
            end
        end
    end
end

mK = sparse(vRows, vCols, vVals, numElementsImage, numElementsImage);

end

function [ mK ] = CreateConvMtxSymmetric( mH, numRows, numCols )
%UNTITLED6 Summary of this function goes here
%   Detailed explanation goes here

numElementsImage    = numRows * numCols;
numRowsKernel       = size(mH, 1);
numColsKernel       = size(mH, 2);
numElementsKernel   = numRowsKernel * numColsKernel;

vRows = reshape(repmat(1:numElementsImage, numElementsKernel, 1), numElementsImage * numElementsKernel, 1);
vCols = zeros(numElementsImage * numElementsKernel, 1);
vVals = zeros(numElementsImage * numElementsKernel, 1);

kernelRadiusV = floor(numRowsKernel / 2);
kernelRadiusH = floor(numColsKernel / 2);

pxIdx       = 0;
elmntIdx    = 0;

for jj = 1:numCols
    for ii = 1:numRows
        pxIdx = pxIdx + 1;
        for ll = -kernelRadiusH:kernelRadiusH
            for kk = -kernelRadiusV:kernelRadiusV
                elmntIdx = elmntIdx + 1;

                % Pixel Index Shift such that pxIdx + pxShift is the linear
                % index of the pixel in the image
                pxShift = (ll * numRows) + kk;

                if(ii + kk > numRows)
                    pxShift = pxShift - (2 * (ii + kk - numRows) - 1);
                end

                if(ii + kk < 1)
                    pxShift = pxShift + (2 * (1 -(ii + kk)) - 1);
                end

                if(jj + ll > numCols)
                    pxShift = pxShift - ((2 * (jj + ll - numCols) - 1) * numRows);
                end

                if(jj + ll < 1)
                    pxShift = pxShift + ((2 * (1 - (jj + ll)) - 1) * numRows);
                end

                vCols(elmntIdx) = pxIdx + pxShift;
                vVals(elmntIdx) = mH(kk + kernelRadiusV + 1, ll + kernelRadiusH + 1);

            end
        end
    end
end

mK = sparse(vRows, vCols, vVals, numElementsImage, numElementsImage);

end

function [ mK ] = CreateConvMtxReplicate( mH, numRows, numCols )
%UNTITLED6 Summary of this function goes here
%   Detailed explanation goes here

numElementsImage    = numRows * numCols;
numRowsKernel       = size(mH, 1);
numColsKernel       = size(mH, 2);
numElementsKernel   = numRowsKernel * numColsKernel;

vRows = reshape(repmat(1:numElementsImage, numElementsKernel, 1), numElementsImage * numElementsKernel, 1);
vCols = zeros(numElementsImage * numElementsKernel, 1);
vVals = zeros(numElementsImage * numElementsKernel, 1);

kernelRadiusV = floor(numRowsKernel / 2);
kernelRadiusH = floor(numColsKernel / 2);

pxIdx       = 0;
elmntIdx    = 0;

for jj = 1:numCols
    for ii = 1:numRows
        pxIdx = pxIdx + 1;
        for ll = -kernelRadiusH:kernelRadiusH
            for kk = -kernelRadiusV:kernelRadiusV
                elmntIdx = elmntIdx + 1;

                % Pixel Index Shift such that pxIdx + pxShift is the linear
                % index of the pixel in the image
                pxShift = (ll * numRows) + kk;

                if(ii + kk > numRows)
                    pxShift = pxShift - (ii + kk - numRows);
                end

                if(ii + kk < 1)
                    pxShift = pxShift + (1 - (ii + kk));
                end

                if(jj + ll > numCols)
                    pxShift = pxShift - ((jj + ll - numCols) * numRows);
                end

                if(jj + ll < 1)
                    pxShift = pxShift + ((1 - (jj + ll)) * numRows);
                end

                vCols(elmntIdx) = pxIdx + pxShift;
                vVals(elmntIdx) = mH(kk + kernelRadiusV + 1, ll + kernelRadiusH + 1);

            end
        end
    end
end

mK = sparse(vRows, vCols, vVals, numElementsImage, numElementsImage);

end

function [ mK ] = CreateConvMtxCircular( mH, numRows, numCols )
%UNTITLED6 Summary of this function goes here
%   Detailed explanation goes here

numElementsImage    = numRows * numCols;
numRowsKernel       = size(mH, 1);
numColsKernel       = size(mH, 2);
numElementsKernel   = numRowsKernel * numColsKernel;

vRows = reshape(repmat(1:numElementsImage, numElementsKernel, 1), numElementsImage * numElementsKernel, 1);
vCols = zeros(numElementsImage * numElementsKernel, 1);
vVals = zeros(numElementsImage * numElementsKernel, 1);

kernelRadiusV = floor(numRowsKernel / 2);
kernelRadiusH = floor(numColsKernel / 2);

pxIdx       = 0;
elmntIdx    = 0;

for jj = 1:numCols
    for ii = 1:numRows
        pxIdx = pxIdx + 1;
        for ll = -kernelRadiusH:kernelRadiusH
            for kk = -kernelRadiusV:kernelRadiusV
                elmntIdx = elmntIdx + 1;

                % Pixel Index Shift such that pxIdx + pxShift is the linear
                % index of the pixel in the image
                pxShift = (ll * numRows) + kk;

                if(ii + kk > numRows)
                    pxShift = pxShift - numRows;
                end

                if(ii + kk < 1)
                    pxShift = pxShift + numRows;
                end

                if(jj + ll > numCols)
                    pxShift = pxShift - (numCols * numRows);
                end

                if(jj + ll < 1)
                    pxShift = pxShift + (numCols * numRows);
                end

                vCols(elmntIdx) = pxIdx + pxShift;
                vVals(elmntIdx) = mH(kk + kernelRadiusV + 1, ll + kernelRadiusH + 1);

            end
        end
    end
end

mK = sparse(vRows, vCols, vVals, numElementsImage, numElementsImage);

end

The code was validated against MATLAB imfilter().
Full code is available in my StackOverflow Q2080835 GitHub Repository.


Q:

what's the difference between Lock and ReentrantLock in Java 5?

I don't understand the difference between them. I thought a lock from the lock interface was reentrant too then what's the difference between them? When would you use each?

A:

Lock is an interface. It defines a set of methods that all locks should have.
ReentrantLock is a concrete class that implements the Lock interface. It implements all the methods defined in Lock, plus much more. Additionally, as mentioned in the name, the lock is re-entrant which means the same thread can acquire the lock as many times as it wants. This is essentially the same behavior as the native object monitor locks provided by the synchronized keyword.
The Lock interface makes it possible for you to implement your own kind of lock. For example, you might design a lock that issues an HTTP request (performing network I/O) to lock a remote resource. Another class that uses your lock wouldn't care about the internal details of your lock; it only cares that your custom lock respects the Lock interface.


Q:

Tuning machines are too sensitive and change the pitch too much. What should I do?

I have just bought a steel guitar (actually a 10-string brazilian viola) and the tuning is too sensitive, because only a small movement on the peg changes the pitch too much. It's not an exaggeration to say that the "useful range" of movement is less than 5 angular degrees, and this is way different of what I got used in other instruments.
I suspect this might be due to two possible causes:

The machine heads turning ratio is poor;
The strings are too low-quality;

So, the questions are:

What is the expected turning ratio (handle revolutions per axis revolution) of a good-quality guitar machine head?
Is it possible that bad quality strings are the cause for my problem? Should I expect the tuning process to be easier with better strings?

Here's an image of the tuning machine model, taken from the manufacturer site:

A:

It is likely that the nut slots are too tight and the strings are sticking.  When they respond to the tuning peg, they are actually slipping and so you aren't getting a gradual change in pitch.
Next time you restring the instrument, try thinner strings (maybe it was set up that way) and you could consider putting some graphite powder in the slots as a dry lubricant so the strings glide through easier.
Ultimately, you may need to go to a luthier to have the instrument adjusted in some way (either tuners, nut, strings, etc).


Q:

Syncing a random variable in ruby

I am making a simple Tic tac toe game where the rows are represented by three arrays and columns are items in those arrays. For my computer choice I use two separate functions to get the row and column.
$first = ["-","-","-"]
$secound = ["-","-","-"]
$third = ["-","-","-"]
def get_row
    row = nil
    case rand(3)
    when 0
        row = $first
    when 1
        row = $secound
    else
        row = $third
    end
    row
end
def get_col
    col = nil
    case rand(3)
    when 0
        col = 0
    when 1
        col = 1
    else
        col = 2
    end
    col
end

I then use a third function that keeps generating a new "guess" until it finds an empty spot, at which point it marks an 0.
def computer_guess
    temp = false
    try = get_row[get_col]
    while temp == false
        if try == "-"
           get_row[get_col] = "O"
            temp = true
        else
            try = get_row[get_col]
        end
    end
end

My problem is that i cant return the guess to the same position that i check for validity. Is the there a way to sync these or do i need a different approach?

A:

The problem with your approach is that get_row[get_col] returns a random element every time it is called, so likewise get_row[get_col] = "O" will set a random element to "O". You inspect one element and then set another.
You could fix this quickly by modifying the retrieved element in-place:
if try == "-"
  try.replace("O")
  # ...

But semantically, I don't like that fix very much. Thinking of a tic-tac-toe board, I'd rather assign an "O" to the free spot than transforming the existing placeholder from "-" into "O".
Did you notice that your get_row method returns an array whereas get_col returns an index? I think this mixture of arrays and indices makes your code a bit convoluted.
It's much easier (in my opinion) to access both, row and column via an index.
To do so, you could put your three rows into another array:
$board = [
  ['-', '-', '-'],
  ['-', '-', '-'],
  ['-', '-', '-']
]

The first row can be accessed via $board[0] and its first element via $board[0][0]. To set an element you'd use: $board[1][2] = 'O' (this sets the middle row's right-most element to "O"). Of course, you can also use variables, e.g. $board[row][col].
With this two-dimensional array, your computer_guess could be rewritten using just two random indices: (get_row and get_col aren't needed anymore)
def computer_guess
  loop do
    row = rand(3)                # random row index
    col = rand(3)                # random column index
    if $board[row][col] == '-'   # if corresponding spot is "-"
      $board[row][col] = 'O'     #    set that spot to "O"
      break                      #    and break out of the loop
    end
  end
end

Note however that "blindly" guessing spots until you find a free one might not be the best approach.
Instead, you could generate a list of "free" spots. This can be done by first generating an array of all coordinates1 and then select-ing those row/col pairs whose spot is "-":
def free_spots
  coordinates = [0, 1, 2].product([0, 1, 2])
  coordinates.select { |row, col| $board[row][col] == '-' }
end

Now you just have to chose a random pair (via sample) and set the corresponding spot to "O":
def computer_guess
  row, col = free_spots.sample
  $board[row][col] = 'O'
end

1 Array#product returns the Cartesian product of the given arrays. It's an easy way to get all pairs:
[0, 1, 2].product([0, 1, 2])
#=> [[0, 0], [0, 1], [0, 2],
#    [1, 0], [1, 1], [1, 2],
#    [2, 0], [2, 1], [2, 2]]


Q:

C# data grid binding with custom objects

I'm trying to display account data in a DataGrid but the binding doesn't seem to be working correctly.
public ObservableCollection<AccountData> accountlist = new ObservableCollection<AccountData>();

public MainWindow()
        {
            InitializeComponent();
            AccountDataGrid.ItemsSource = accountlist;
        }

This is what my list looks like and how I bound it to the data grid.
GetAccountsResponse resp = GetAccountsResponse.GetAccounts(m_authImpl);

            List<AccountData> accounts = resp.Accounts;
            for (int i = 0; i < accounts.Count; ++i)
            {
                AccountData account = accounts[i];
                accountlist.Add(account);
            }

I'm using an API to get account data, then putting it into my list of observable accounts
<DataGrid x:Name="AccountDataGrid" HorizontalAlignment="Left" Height="249" Margin="10,278,0,0" VerticalAlignment="Top" Width="772" AutoGenerateColumns="False" IsReadOnly="True" >
            <DataGrid.Columns>
                <DataGridTextColumn Header="Type"  Binding="{Binding Path=m_type}"/>
                <DataGridTextColumn Header="Number"  Binding="{Binding Path=m_number}"/>
                <DataGridTextColumn Header="Status"  Binding="{Binding Path=m_status}"/>
                <DataGridTextColumn Header="isPrimary"  Binding="{Binding Path=m_isPrimary}"/>
                <DataGridTextColumn Header="isBilling"  Binding="{Binding Path=m_isBilling}"/>
                <DataGridTextColumn Header="clientAccountType"  Binding="{Binding Path=m_clientAccountType}"/>
            </DataGrid.Columns>
        </DataGrid>

This is the code for my Data grid
public class AccountData
    {
        public UserAccountType m_type;
        public string m_number;
        public AccountStatus m_status;
        public bool m_isPrimary;
        public bool m_isBilling;
        public ClientAccountType m_clientAccountType;

        public AccountData();
    }

This is what my object looks like!
Some backstory:
accountlist has all the correct information in the debugger but when it comes time to display the results in the data grid it shows as a blank entry.
public enum UserAccountType
    {
        Undefined = 0,
        Cash = 1,
        Margin = 2,
        TFSA = 3,
        RRSP = 4,
        SRRSP = 5,
        LRRSP = 6,
        LIRA = 7,
        LIF = 8,
        RIF = 9,
        SRIF = 10,
        LRIF = 11,
        RRIF = 12,
        PRIF = 13,
        RESP = 14,
        FRESP = 15,
        FX = 16,
        FXD = 17,
        Count = 18
    }

public enum AccountStatus
    {
        Undefined = -1,
        UnAllocated = 0,
        Active = 1,
        SuspendedClosed = 2,
        SuspendedViewOnly = 3,
        LiquidateOnly = 4,
        Closed = 5,
        Count = 6
    }

public enum ClientAccountType
    {
        Undefined = 0,
        Individual = 1,
        Joint = 2,
        InformalTrust = 3,
        Corporation = 4,
        InvestmentClub = 5,
        FormalTrust = 6,
        Partnership = 7,
        SoleProprietorship = 8,
        Family = 9,
        JointAndInformalTrust = 10,
        Institution = 11,
        Count = 12
    }

A:

Let's do it using MVVM. The main goal of the approach is: any changes made to the data are immediately displayed in DataGrid on-the-fly.
You'll need a helper class which implements INotifyPropertyChanged interface
NotifyPropertyChanged.cs
public class NotifyPropertyChanged : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;
    protected virtual void OnPropertyChanged([CallerMemberName]string propertyName = null)
        => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}

Then make the new data class deriving from NotifyPropertyChanged. For compartibility with AccountData class i've added an overload for constructor with AccountData argument.
UIAccountData.cs
public class UIAccountData : NotifyPropertyChanged
{
    private UserAccountType m_type;
    private string m_number;
    private AccountStatus m_status;
    private bool m_isPrimary;
    private bool m_isBilling;
    private ClientAccountType m_clientAccountType;

    public UserAccountType Type
    {
        get => m_type;
        set
        {
            m_type = value;
            OnPropertyChanged();
        }
    }
    public string Number
    {
        get => m_number;
        set
        {
            m_number = value;
            OnPropertyChanged();
        }
    }
    public AccountStatus Status
    {
        get => m_status;
        set
        {
            m_status = value;
            OnPropertyChanged();
        }
    }
    public bool IsPrimary
    {
        get => m_isPrimary;
        set
        {
            m_isPrimary = value;
            OnPropertyChanged();
        }
    }
    public bool IsBilling
    {
        get => m_isBilling;
        set
        {
            m_isBilling = value;
            OnPropertyChanged();
        }
    }
    public ClientAccountType ClientAccountType
    {
        get => m_clientAccountType;
        set
        {
            m_clientAccountType = value;
            OnPropertyChanged();
        }
    }

    public UIAccountData() { }

    public UIAccountData(AccountData account)
    {
        m_type = account.m_type;
        m_number = account.m_number;
        m_status = account.m_status;
        m_isPrimary = account.m_isPrimary;
        m_isBilling = account.m_isBilling;
        m_clientAccountType = account.m_clientAccountType;
    }

    public AccountData ToAccountData => new AccountData
    {
        m_type = m_type,
        m_number = m_number,
        m_status = m_status,
        m_isPrimary = m_isPrimary,
        m_isBilling = m_isBilling,
        m_clientAccountType = m_clientAccountType,
    };
}

Then create main class containing the collection and used for Bindings.
MainViewModel.cs
public class MainViewModel : NotifyPropertyChanged
{
    public ObservableCollection<UIAccountData> _accountlist;

    public ObservableCollection<UIAccountData> Accountlist
    {
        get => _accountlist;
        set
        {
            _accountlist = value;
            OnPropertyChanged();
        }
    }

    public MainViewModel()
    {
        // demo values
        Accountlist = new ObservableCollection<UIAccountData>
        {
            new UIAccountData { Type = UserAccountType.Cash, Number = "123", Status = AccountStatus.Active, IsPrimary = true, IsBilling = true, ClientAccountType = ClientAccountType.Individual },
            new UIAccountData { Type = UserAccountType.Margin, Number = "aaa", Status = AccountStatus.Active, IsPrimary = false, IsBilling = true, ClientAccountType = ClientAccountType.InformalTrust },
            new UIAccountData { Type = UserAccountType.LRRSP, Number = "bbb", Status = AccountStatus.SuspendedClosed, IsPrimary = true, IsBilling = false, ClientAccountType = ClientAccountType.Partnership },
            new UIAccountData { Type = UserAccountType.SRIF, Number = "456", Status = AccountStatus.SuspendedViewOnly, IsPrimary = false, IsBilling = false, ClientAccountType = ClientAccountType.Institution },
        };
        AccountData account = new AccountData() { m_type = UserAccountType.FX, m_number = "fff", m_status = AccountStatus.SuspendedViewOnly, m_isPrimary = true, m_isBilling = false, m_clientAccountType = ClientAccountType.Institution };
        Accountlist.Add(new UIAccountData(account));
    }
}

The full markup
MainWindow.xaml
<Window x:Class="WpfApp1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:WpfApp1"
        Title="MainWindow" Height="600" Width="1000" WindowStartupLocation="CenterScreen">
    <Window.DataContext>
        <local:MainViewModel/><!-- MainViewModel attached here -->
    </Window.DataContext>
    <Grid>
        <DataGrid ItemsSource="{Binding Accountlist}" HorizontalAlignment="Left" AutoGenerateColumns="False" IsReadOnly="True" Width="Auto">
            <DataGrid.Columns>
                <DataGridTextColumn Width="*" Header="Type" Binding="{Binding Type}"/>
                <DataGridTextColumn Width="*" Header="Number" Binding="{Binding Number}"/>
                <DataGridTextColumn Width="*" Header="Status" Binding="{Binding Status}"/>
                <DataGridCheckBoxColumn Width="*" Header="IsPrimary" Binding="{Binding IsPrimary}"/>
                <DataGridCheckBoxColumn Width="*" Header="IsBilling" Binding="{Binding IsBilling}"/>
                <DataGridTextColumn Width="*" Header="ClientAccountType" Binding="{Binding ClientAccountType}"/>
            </DataGrid.Columns>
        </DataGrid>
    </Grid>
</Window>

And finally
MainWindow.xaml.cs
public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
    }
}


Q:

Check in an array in java if value is lower than previous value and split it

I have an array with times
String[] times = {"08:00", "09:15", "09:45", "08:15", "08:45", "09:30"};

And I want to loop through every value of the array and check if it is higher than the previous value.
If that is true, it splits the array at that point so you get these two arrays:
String[] times1 = {"08:00", "09:15", "09:45"};
String[] times2 = {"08:15", "08:45", "09:30"};

How to do this in java?

A:

Use following code:
String[] times = {"08:00", "09:15", "09:45", "08:15", "08:45", "09:30"};
    String first[]=null;
    String second[]=null;
    for(int i=0;i<times.length-1;i++)
    {
        Date date=new SimpleDateFormat("hh:mm").parse(times[i]);
        Date date2=new SimpleDateFormat("hh:mm").parse(times[i+1]);
        if(date.getTime()>date2.getTime())
        {
            first=Arrays.copyOfRange(times, 0, i+1);
            second=Arrays.copyOfRange(times, (i+1), (times.length));
        }
    }

Hope it helps.


Q:

RSA encryption in Android and Java

I would like to encrypt a String with RSA encryption. My public/private keys were generated and stored in DB. In android, I use this code:
public static String encryptRSAToString(String text, String strPublicKey) {
    byte[] cipherText = null;
    String strEncryInfoData="";
    try {

    KeyFactory keyFac = KeyFactory.getInstance("RSA");
    KeySpec keySpec = new X509EncodedKeySpec(Base64.decode(strPublicKey.trim().getBytes(), Base64.DEFAULT));
    Key publicKey = keyFac.generatePublic(keySpec);

    // get an RSA cipher object and print the provider
    final Cipher cipher = Cipher.getInstance("RSA");
    // encrypt the plain text using the public key
    cipher.init(Cipher.ENCRYPT_MODE, publicKey);
    cipherText = cipher.doFinal(text.getBytes());
    strEncryInfoData = new String(Base64.encode(cipherText,Base64.DEFAULT));

    } catch (Exception e) {
    e.printStackTrace();
    }
    return strEncryInfoData.replaceAll("(\\r|\\n)", "");
}

For debug purpose, I try to call 2 times this method with the same parameters and String result were similar (as expected).
I want to generate the same encrypted String in java. However, "android.util.Base64" class is not available in Java, so I've tried with the default Base64 class:
public static String encryptRSAToString(String text, String strPublicKey) {

        byte[] cipherText = null;
        String strEncryInfoData="";
        try {

        KeyFactory keyFac = KeyFactory.getInstance("RSA");
        KeySpec keySpec = new X509EncodedKeySpec(Base64.decodeBase64(strPublicKey.trim().getBytes()));
        Key publicKey = keyFac.generatePublic(keySpec);

        // get an RSA cipher object and print the provider
        final Cipher cipher = Cipher.getInstance("RSA");
        // encrypt the plain text using the public key
        cipher.init(Cipher.ENCRYPT_MODE, publicKey);
        cipherText = cipher.doFinal(text.getBytes());
        strEncryInfoData = new String(Base64.encodeBase64(cipherText));

        } catch (Exception e) {
        e.printStackTrace();
        }
        return strEncryInfoData.replaceAll("(\\r|\\n)", "");
    }

But the String generated in Android and the one in java are different.
Generated in Android side :
Ky2T4j1JdI081ZESVJgxZXEf/xmtpehfv/EwpVvKQxUu1JI8lwXP2Rc66jHZRc0P846ZYuF3C9YEmWoKbXGXk2MBuT5KVxa2yoTbwZlMmhVOX3X3Efq0VyaO5zZ4qavIq036cA3MzvQbUAb678UdbALW/CjRCsOdeH+hSCzNQ+0=

Generated in JAVA side :
XhSLxfiJUUdZW5kWh0MEPSrqoROBBhNC/krfTx+sdnXML3WegYbMzSvNnPgB8+8Z9joEUBMmoeBI1OhTF6qPFL1EEixkFYAkGaryEFxvN/aFI75kEUj71OHNzAHAuvS+h+9Nssx9psSZ5gc2OoLQH0QtbGDyXB4p+qUGFCde4tY=

Does someone know how to solve my issue ?
thank you

A:

It looks like you've been undone by relying on defaults. Never do that if you hope for interoperability.
Here are the two examples of mistakenly relying on defaults in your code that I've found.
final Cipher cipher = Cipher.getInstance("RSA");
The tranformation string is supposed to be of the form "algorithm/mode/padding" but you've left off the mode and padding specifications. As a result you got default values for those. The defaults are evidently different on Android and Oracle Java. You should always fully specify the transformation, for example:
final Cipher cipher = Cipher.getInstance("RSA/ECB/OAEPWITHSHA-256ANDMGF1PADDING");
Another bad example is
cipherText = cipher.doFinal(text.getBytes());
In text.getBytes() you are relying on the no-args getBytes() method which uses the default charset for the platform. But this default charset differs on different platforms, and thus this is not portable. In almost all cases I've run across you should specify the UTF-8 charset. So the correct line would thus be
cipherText = cipher.doFinal(text.getBytes("UTF-8"));
and the correct string constructor to use to recreate the original string in the decrypt method is the String(byte [] data, String charsetName).


Q:

Responsive lightroom-style grid with css?

One of the simplest image gallery layouts is a square grid with centered images, like the Adobe Lightroom screenshot below.
There are many similar questions (1) (2) (3), but all these involve square images and a square grid.  Mine is more general, because it involves rectangular images and a square grid.
I’ve spent a long time trying to reproduce exactly the screenshot below using css flexbox and inline-box, but always failed to get the centering exactly right:
flex: jsfiddle.net/rmodrak/4sxzkonr/
inline-block: jsfiddle.net/rmodrak/wmunqzL6/
It’s hard to believe css doesn’t natively support such a layout.   Am I missing something?

A:

Try this:
Edit: Added responsive layout.

<!DOCTYPE html>

Nice photos, nice boxes.

Now with 100% more responsiveness!


Q:

How do I get the "session data" shown in an error?

I am adding some functionality to an existing application to show debug info. When examining an error from the error log view it shows something called "session data", typically it looks like:
eclipse.buildId=M20090917-0800
java.version=1.6.0_11
java.vendor=Sun Microsystems Inc.
BootLoader constants: OS=win32, ARCH=x86, WS=win32, NL=sv_SE
Framework arguments:  -product org.eclipse.epp.package.rcp.product
Command-line arguments:  -os win32 -ws win32 -arch x86 -product org.eclipse.epp.package.rcp.product

This is something that could be useful to know. how can I get this information?

A:

Some of those information should be able from a Plugin through the org.eclipse.core.runtime.Platform class, as shown by the org.eclipse.debug.internal.core.SystemVariableResolver source code:
public String resolveValue(IDynamicVariable variable, String argument) throws CoreException {
    if ("ARCH".equals(argument)) { //$NON-NLS-1$
        return Platform.getOSArch();
    } else if ("ECLIPSE_HOME".equals(argument)) { //$NON-NLS-1$
        URL installURL = Platform.getInstallLocation().getURL();
        IPath ppath = new Path(installURL.getFile()).removeTrailingSeparator();
        return getCorrectPath(ppath.toOSString());
    } else if ("NL".equals(argument)) { //$NON-NLS-1$
        return Platform.getNL();
    } else if ("OS".equals(argument)) { //$NON-NLS-1$
        return Platform.getOS();
    } else if ("WS".equals(argument)) { //$NON-NLS-1$
        return Platform.getWS();
    }
    return null;
}

Platform.getCommandLineArgs() should complete the display for the eclipse session (not for your program though).

For a RCP program, see this thread

Using the Application start(IApplicationContext context) method:

String[] args = (String[]) context.getArguments().get(IApplicationContext.APPLICATION_ARGS);


Q:

The first 'easy exercise' in Spivak's differential geometry book

I am a 'lowly physicist' (actually, only a prospective physicist) with little to no background in formal mathematics. Recently I decided it's time to get serious, so I started reading Spivak's 'Comprehensive Introduction to Differential Geometry'. The first chapter, on manifolds, starts off with the definition of a manifold:
Definition: A manifold is a metric space $M$ with the property that, for any point $x\in M$, there exists a neighborhood $U$ of $x$ and some integer $n\geq 0$ such that $U$ is homeomorphic to $\mathbb{R}^n$.
On the third page, Spivak argues that $U$ must be an open set. He has already demonstrated that we can always choose $U$ to be open. He gives, without proof, the 'Invariance of domain' theorem:
Theorem: If $U\subset \mathbb{R}^n$ is open and $f: U\to \mathbb{R}^n$ is one-one and continuous, then $f(U)\subset \mathbb{R}^n$ is open. (it follows that $f(V)$ is open for any open $V\subset U$, so $f^{-1}$ is continuous and $f:U\to f(U)$ is a homeomorphism.)
Now, Spivak states that it is 'an easy exercise' to show that this theorem implies that $U$ from the above definition must be open.
I have tried to look up and understand all the relevant definitions. What I (think I) have understood so far is the following. From the property that $U$ is homeomorphic to $\mathbb{R}^n$ it follows immediately that there is also a homeomorphism (i.e. a continuous and one-one (?) function) from $\mathbb{R}^n$ to $U$. If we denote the homeomorphism from $U$ to $\mathbb{R}^n$ by $f$, it is enough to show that $f(U)$ is open to conclude that $f$ is open by the invariance of domain theorem. However, it is not clear to me that this must be the case. Am I missing a subtlety in a definition? Or is there some nontrivial step here?

A:

The question is to prove that if $U \subset M$ is homeomorphic to $\mathbb{R}^n$ then $U$ is open. Choose a homeomorphism $f :U \to \mathbb{R}^n$ (yes, homeomorphisms are one-to-one, onto, and they are continuous with continuous inverse; also, to be explicit, the topology on $U$ is the subspace topology, whose open sets are the intersections of $U$ with open subsets of $M$).
Take a point $x \in M$. We can choose an open subset $V_x \subset M$ containing $x$ and a homeomorphism $f_x : V_x \to \mathbb{R}^n$. The set $V_x \cap U$ is open in the subspace topology on $U$. Therefore $f(V_x \cap U) \subset \mathbb{R}^n$ is open, and it contains $f(x)$. There is an open ball $B \subset \mathbb{R}^n$ centered on $f(x)$ such that $B \subset f(V_x \cap U)$. The function $f_x \circ f^{-1}$ restricted to $B$ is one-to-one and continuous, and so by applying the Invariance of Domain Theorem its image $f_x \circ f^{-1}(B)$ is an open subset of $f_x(V_x)=\mathbb{R}^n$. It follows that $f^{-1}(B) = f_x^{-1} \circ f_x \circ f^{-1}(B)$ is an open subset of $V_x$ which is an open subset of $M$. Therefore $f^{-1}(B)$ is an open subset of $M$. Also, by construction $x \in f^{-1}(B) \subset U$. Since $x \in U$ is arbitrary, $U$ is open.


Q:

Proper way to handle uploads using AJAX form

I'm using Valum's AJAX uploader, which is quite nice. I have a form that lets you fill out some info and optionally attach files.
I have a hidden input on the form that has a randomly generated "token" (5 character alnum). The uploads are sent to a tmp folder and the info about those files (name, dir, token) are kept in a uploads_tmp table in a database.
Then, when the user successfully submits the form, those files are moved to a more permanent location and the rows from the uploads_tmp are moved to the uploads table.
If the user submits and there are errors with the form, my script knows there are uploads from a previous attempt via the token. So there's no need to re-upload files.
Is this the right way of doing it or am I going about it all wrong? I'm using PHP (CodeIgniter to be exact).

A:

There isn't any one correct way of doing something like this.  Your method seems like a good intuitive one, but really it's down to whatever works for you and your situation.