Q: Convert a  in a My code has
<input class="menu_button" type="submit" value="Log in">
Register

The a href is styled perfectly in my css while the input button with type = submit DOES NOT...
How could I change

Into a a href?
Here is a jsfiddle.
http://jsfiddle.net/26tyd/
SEE HOW THE BUTTONS LOOK different. one higher up and smaller the other is perfect. Please help me figure out how to fix this issue.

A: Add this to your css:
input[type=submit]{
    height: 22px;
    line-height: 18px;
    cursor: pointer;
}

A: Instead of using height and width like you are currently doing you should use padding because then the text is vertically centred.
The reason that the is not being sent is because you are not currently using a form so you need to add a form tag around the stuff that you want in the form so you could use this:
<form action='#' method='get'>
    <input class="menu_button" type="submit" value="Log in" />
</form>

Here is a working fiddle:
http://jsfiddle.net/Hive7/26tyd/3/

A: You just need to add below code in your code:
    box-sizing: border-box;
    -moz-box-sizing: border-box;

And to adjust the hight and with I would sugegst you to play with "min-width" and "padding". As giving "Width" and "Height" can limit your button and if you have more test or padding the height and width will not let the background increase.
Please see the updated code:-
.menu_button {
   -moz-box-shadow:inset 0px -1px 0px 0px #000000;
    -webkit-box-shadow:inset 0px -1px 0px 0px #000000;
    box-shadow:inset 0px -1px 0px 0px #000000;
    background-color:#000000;
    -webkit-border-top-left-radius:0px;
    -moz-border-radius-topleft:0px;
    border-top-left-radius:0px;
    -webkit-border-top-right-radius:0px;
    -moz-border-radius-topright:0px;
    border-top-right-radius:0px;
    -webkit-border-bottom-right-radius:0px;
    -moz-border-radius-bottomright:0px;
    border-bottom-right-radius:0px;
    -webkit-border-bottom-left-radius:0px;
    -moz-border-radius-bottomleft:0px;
    border-bottom-left-radius:0px;
    text-indent:0;
    border:1px solid #fa1e0f;
    display:inline-block;
    color:#ffffff;
    font-family:Arial;
    font-size:12px;
    font-weight:normal;
    font-style:normal;
    text-decoration:none;
    text-align:center;
    text-shadow:1px 1px 0px #33302f;
    box-sizing: border-box; /*ADDED*/
    -moz-box-sizing: border-box; /*ADDED*/
    padding:5px;
}

Hope this helps!

A: Try
margin: 0;
padding: 0;
white-space: normal;
box-sizing: content-box;

The input tags are styled different by the user agent stylesheet than a tags.

A: As I understand you need to style both elements the same?
Here's one solution:
JSFIDDLE DEMO
.menu_button {
    -moz-box-shadow:inset 0px -1px 0px 0px #000000;
    -webkit-box-shadow:inset 0px -1px 0px 0px #000000;
    box-shadow:inset 0px -1px 0px 0px #000000;

    background-color:#000000;
    text-indent: 0;
    border: 1px solid #fa1e0f;
    display: inline-block;
    color: #fff;
    font: normal 12px/1 Arial;
    width: 58px;
    text-decoration: none;
    text-align: center;
    vertical-align: top;
    text-shadow: 1px 1px 0px #33302f;
    padding: 5px 0;
    ouotline: 0 none;
    margin: 0;
}
/*this is needed for firefox and buttons */
.menu_button::-moz-focus-inner { border: 0; padding: 0; outline: none; }


Q: Azure notification hub Cannot read property 'name' of undefined Scenario
I have created azure notification hub on my Visual Studio Enterprise subscription and new namespace in the azure portal according to this tutorial
Problem
After resources are created, I go into overview section of my notification hub in azure portal and I see error Cannot read property 'name' of undefined


Q: I need to convert a Node object to a string in C I am having trouble with a homework assignment. I finished most of it, but I'm stuck at this one part. If you look at the header file, you will see a comment that says:

Convert a Node object to a string.  We require a pointer to the Node object so that we can display the address of the object for further reference

I did as much as I could, but I don't know where to go from here.
The output from this test program looks like:

<0x0022ff40>[value: 2, left: 0x00000000, right: 0x00000000]
<0x0022ff30>[value: 3, left: 0x00000000, right: 0x00000000]
<0x0022ff20>[value: 4, left: 0x00000000, right: 0x00000000]

<0x0022ff10>[value: *, left: 0x0022ff30, right: 0x0022ff20]
<0x0022ff00>[value: +, left: 0x0022ff40, right: 0x0022ff10]
 Tree evaluation: 14

<0x0022ff00>[value: +, left: 0x0022ff40, right: 0x0022ff30]
<0x0022ff10>[value: *, left: 0x0022ff00, right: 0x0022ff20]
 Tree evaluation: 20

<0x0022ff00>[value: ., left: 0x0022ff40, right: 0x0022ff30]
<0x0022ff10>[value: *, left: 0x0022ff00, right: 0x0022ff20]
invalid operator: .

This is my main():
#include <stdio.h>
#include "TreeNode.h"

int main(void)
{
 Node n2, n3, n4, times, plus;

 setNode(&n2, 2, NULL, NULL, true);
 setNode(&n3, 3, NULL, NULL, true);
 setNode(&n4, 4, NULL, NULL, true);
 printf("\n");

 setNode(&times, '*', &n3, &n4, true);
 setNode(&plus, '+', &n2, &times, true);

 printf(" Tree evaluation: %d\n\n", eval(&plus));

 setNode(&plus, '+', &n2, &n3, true);
 setNode(&times, '*', &plus, &n4, true);

 printf(" Tree evaluation: %d\n\n", eval(&times));

 setNode(&plus, '.', &n2, &n3, true);
 setNode(&times, '*', &plus, &n4, true);

 printf(" Tree evaluation: %d\n\n", eval(&times));

 return 0;
}

This is my header:
#include <stdio.h>
#ifndef TREE_NODE
#define TREE_NODE

typedef struct Node_t {
    int value;
    struct Node_t   *left;
    struct Node_t   *right;
} Node, *Node_p;

typedef char* String;

typedef enum {false, true} bool;

/*
 *  Convert a Node object to a string.
 *
 *  We require a pointer to the Node object so that we can display the
 *  address of the object for further reference.
 */
String nodeToString(Node_p np) {
    static char output[0];
    sprintf(output, "<0x%d>\n", np, np->value, np->left, np->right);
    return output;
}

void setNode(Node_p np,
     int    value,
     Node_p    left,
     Node_p    right,
     bool    display) {
        np->value = value;
        np->left = left;
        np->right = right;
     if (display) {
          printf("%s\n", nodeToString(np));
     }

}

int eval(Node_p np){

    switch(np->value) {
        case '+':
               np->value = eval(np->left) + eval(np->right);
               return np->value;
        case '-':
               np->value = eval(np->left) - eval(np->right);
               return np->value;
        case '*':
               np->value = eval(np->left) * eval(np->right);
               return np->value;
        case '/':
               np->value = eval(np->left) / eval(np->right);
               return np->value;
        default:
                exit(1);
    }
    return 0;
}

#endif

A: You are using the same field for operator and value in the struct Node_t. Extend your struct as this:
typedef struct Node_t {
    int value;
    char op; /*operator*/
    struct Node_t   *left;
    struct Node_t   *right;
} Node, *Node_p;

Add a new parameter to the function setNode for the operator (set it to '\0' when Node is a number; you must do the switch of eval over this operator), and add
case '\0':
        return np->value;
        break;

to the switch of eval.


Q: Jquery .change() For some reason this is non functional any help appreciated.
 <script>
 $(document).ready(function(){
   $('select[name=materialSelect]').change(function(){
    alert("Changed");
   });
 });
</script>
<select name="materialSelect" id="materialSelect">
            <option value="-1">-----Select Material-----</option>
            <option value="0">Material</option>

</select>

A: Your code doesn't have any issue, be careful that you've called your
$('select[name=materialSelect]').change(function(){
    alert("Changed");
 });

after which your html is loaded.
For sample binding the document load to a function that called your code.

A: There is a on change function of jquery available already you are binding it with body load which means your select doesn't exists when you call the function, you should do this :
$(document).on('change', '#materialSelect', function () {
alert('changed');
});

A: Your code is fine as long as the HTML element (on which you are binding the event) is present when the binding script is running.
To be on safe side, always bind to a parent element (body for example) which will delegate the event it to the child.
So, try this,
 $('body').on('change', 'select[name=materialSelect]', function(){
    alert("Changed");
 });

Hope it helps.

A: <!DOCTYPE html>
    <html>
    <head>
      <meta charset="utf-8">
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
    </head>
    <body>
      <select name="materialSelect" id="materialSelect">
        <option value="">-----Select Material-----</option>
        <option value="0">Material</option>
      </select>
      <script type="text/javascript">
      $(document).ready(function(){
        $('select[name=materialSelect]').change(function(){
          alert("Changed");
        });
      });
      </script>
    </body>
    </html>

A: First, I'd look into where jQuery is being loaded. jQuery needs to be loaded before any scripts that use it.
Incorrect:
<script>
    $('.something').change(...
</script>
<script src=""></script><!-- jquery -->

Correct:
<script src=""></script><!-- jquery -->
<script>
    $('.something').change(...
</script>

Secondly, you should be using some kind of document on ready function. This will ensure your HTML is rendered before applying your events (eg "onchange")
Correct:
<script src=""></script><!-- jquery -->
<script>
    $(function () {
        // DOM is now ready
        $('.something').change(...
    })
</script>


Q: Why does Swagger UI POST form data with Content-Type: undefined? I'm trying to POST form data using Swagger UI, but the request is sent with Content-Type: undefined:

How can I configure it so it works? JSON POST works just fine.
Here is my API definition:
{
  "swagger": "2.0",
  "info": {
    "version": "V1",
    "title": "Title"
  },
  "paths": {
    "/api/getcalculation": {
      "post": {
        "tags": [
          "ArrearsOfPay"
        ],
        "operationId": "ApiArrearsOfPayPost",
        "consumes": [],
        "produces": [
          "application/json"
        ],
        "parameters": [
          {
            "name": "InsolvencyDate",
            "in": "formData",
            "required": false,
            "type": "string",
            "format": "date-time"
          },
          {
            "name": "DismissalDate",
            "in": "formData",
            "required": false,
            "type": "string",
            "format": "date-time"
          },
          {
            "name": "UnpaidPeriodFrom",
            "in": "formData",
            "required": false,
            "type": "string",
            "format": "date-time"
          },
          {
            "name": "UnpaidPeriodTo",
            "in": "formData",
            "required": false,
            "type": "string",
            "format": "date-time"
          },
          {
            "name": "ApClaimAmount",
            "in": "formData",
            "required": false,
            "type": "number",
            "format": "double"
          },
          {
            "name": "PayDay",
            "in": "formData",
            "required": false,
            "type": "integer",
            "format": "int32"
          },
          {
            "name": "ShifPattern",
            "in": "formData",
            "required": true,
            "type": "array",
            "items": {
              "type": "string"
            },
            "collectionFormat": "multi"
          },
          {
            "name": "WeeklyWage",
            "in": "formData",
            "required": false,
            "type": "number",
            "format": "double"
          },
          {
            "name": "StatutaryMax",
            "in": "formData",
            "required": false,
            "type": "number",
            "format": "double"
          },
          {
            "name": "NumberOfDaysWorkedInWeek",
            "in": "formData",
            "required": false,
            "type": "integer",
            "format": "int32"
          }
        ],
        "responses": {
          "200": {
            "description": "Success",
            "schema": {
              "$ref": "#/definitions/ArrearsOfPayCalculationResponseModel"
            }
          }
        }
      }
    }
  },
  "definitions": {
    "ArrearsOfPayCalculationResponseModel": {
      "type": "object",
      "properties": {
        "startOfPayWeek": {
          "format": "date-time",
          "type": "string"
        },
        "maximumLiability": {
          "format": "double",
          "type": "number"
        },
        "employerLiability": {
          "format": "double",
          "type": "number"
        },
        "minimumLiability": {
          "format": "double",
          "type": "number"
        }
      }
    }
  }
}

A: The problem is here:
"consumes": []

The consumes keyword specifies the Content-Type header in requests. Since you are POSTing form data, it should be:
"consumes": ["application/x-www-form-urlencoded"]

Tip: You can paste your spec into http://editor.swagger.io to check for syntax errors.


Q: Remove empty array elements Some elements in my array are empty strings based on what the user has submitted. I need to remove those elements. I have this:
foreach($linksArray as $link)
{
    if($link == '')
    {
        unset($link);
    }
}
print_r($linksArray);

But it doesn't work. $linksArray still has empty elements. I have also tried doing it with the empty() function, but the outcome is the same.

A: function trim_array($Array)
{
    foreach ($Array as $value) {
        if(trim($value) === '') {
            $index = array_search($value, $Array);
            unset($Array[$index]);
        }
    }
    return $Array;
}

A: $out_array = array_filter($input_array, function($item)
{
    return !empty($item['key_of_array_to_check_whether_it_is_empty']);
}
);

A: Just want to contribute an alternative to loops...also addressing gaps in keys...
In my case, I wanted to keep sequential array keys when the operation was complete (not just odd numbers, which is what I was staring at. Setting up code to look just for odd keys seemed fragile to me and not future-friendly.)
I was looking for something more like this: http://gotofritz.net/blog/howto/removing-empty-array-elements-php/
The combination of array_filter and array_slice does the trick.
$example = array_filter($example);
$example = array_slice($example,0);

No idea about efficiencies or benchmarks but it works.

A: I use the following script to remove empty elements from an array
for ($i=0; $i<$count($Array); $i++)
  {
    if (empty($Array[$i])) unset($Array[$i]);
  }

A: $my = ("0"=>" ","1"=>"5","2"=>"6","3"=>" ");

foreach ($my as $key => $value) {
    if (is_null($value)) unset($my[$key]);
}

foreach ($my as $key => $value) {
    echo   $key . ':' . $value . '<br>';
}

output

1:5
2:6

A:     $myarray = array_filter($myarray, 'strlen');  //removes null values but leaves "0"
    $myarray = array_filter($myarray);            //removes all null values

A: foreach($arr as $key => $val){
   if (empty($val)) unset($arr[$key];
}

A: Just one line :
Update (thanks to @suther):
$array_without_empty_values = array_filter($array);

A: You can just do
array_filter($array)

array_filter: "If no callback is supplied, all entries of input equal to FALSE will be removed." This means that elements with values NULL, 0, '0', '', FALSE, array() will be removed too.
The other option is doing
array_diff($array, array(''))

which will remove elements with values NULL, '' and FALSE.
Hope this helps :)
UPDATE
Here is an example.
$a = array(0, '0', NULL, FALSE, '', array());

var_dump(array_filter($a));
// array()

var_dump(array_diff($a, array(0))) // 0 / '0'
// array(NULL, FALSE, '', array());

var_dump(array_diff($a, array(NULL))) // NULL / FALSE / ''
// array(0, '0', array())

To sum up:

*

*0 or '0' will remove 0 and '0'

*NULL, FALSE or '' will remove NULL, FALSE and ''

A: foreach($linksArray as $key => $link)
{
    if($link === '')
    {
        unset($linksArray[$key]);
    }
}
print_r($linksArray);

A: In short:
This is my suggested code:
$myarray =  array_values(array_filter(array_map('trim', $myarray), 'strlen'));

Explanation:
I thinks use array_filter is good, but not enough, because values be like space and \n,... keep in the array and this is usually bad.
So I suggest you use mixture array_filter and array_map.
array_map is for trimming, array_filter is for remove empty values, strlen is for keep 0 value, and array_values is for re indexing if you needed.
Samples:
$myarray = array("\r", "\n", "\r\n", "", " ", "0", "a");

// "\r", "\n", "\r\n", " ", "a"
$new1 = array_filter($myarray);

// "a"
$new2 = array_filter(array_map('trim', $myarray));

// "0", "a"
$new3 = array_filter(array_map('trim', $myarray), 'strlen');

// "0", "a" (reindex)
$new4 = array_values(array_filter(array_map('trim', $myarray), 'strlen'));

var_dump($new1, $new2, $new3, $new4);

Results:
array(5) {
  [0]=>
" string(1) "
  [1]=>
  string(1) "
"
  [2]=>
  string(2) "
"
  [4]=>
  string(1) " "
  [6]=>
  string(1) "a"
}
array(1) {
  [6]=>
  string(1) "a"
}
array(2) {
  [5]=>
  string(1) "0"
  [6]=>
  string(1) "a"
}
array(2) {
  [0]=>
  string(1) "0"
  [1]=>
  string(1) "a"
}

Online Test:
http://sandbox.onlinephpfunctions.com/code/e02f5d8795938be9f0fa6f4c17245a9bf8777404

A: Another one liner to remove empty ("" empty string) elements from your array.
$array = array_filter($array, function($a) {return $a !== "";});

Note: This code deliberately keeps null, 0 and false elements.

Or maybe you want to trim your array elements first:
$array = array_filter($array, function($a) {
    return trim($a) !== "";
});

Note: This code also removes null and false elements.

A: use array_filter function to remove empty values:
$linksArray = array_filter($linksArray);
print_r($linksArray);

A: Remove empty array elements
function removeEmptyElements(&$element)
{
    if (is_array($element)) {
        if ($key = key($element)) {
            $element[$key] = array_filter($element);
        }

        if (count($element) != count($element, COUNT_RECURSIVE)) {
            $element = array_filter(current($element), __FUNCTION__);
        }

        return $element;
    } else {
        return empty($element) ? false : $element;
    }
}

$data = array(
    'horarios' => array(),
    'grupos' => array(
        '1A' => array(
            'Juan' => array(
                'calificaciones' => array(
                    'Matematicas' => 8,
                    'Español' => 5,
                    'Ingles' => 9,
                ),
                'asistencias' => array(
                    'enero' => 20,
                    'febrero' => 10,
                    'marzo' => '',
                )
            ),
            'Damian' => array(
                'calificaciones' => array(
                    'Matematicas' => 10,
                    'Español' => '',
                    'Ingles' => 9,
                ),
                'asistencias' => array(
                    'enero' => 20,
                    'febrero' => '',
                    'marzo' => 5,
                )
            ),
        ),
        '1B' => array(
            'Mariana' => array(
                'calificaciones' => array(
                    'Matematicas' => null,
                    'Español' => 7,
                    'Ingles' => 9,
                ),
                'asistencias' => array(
                    'enero' => null,
                    'febrero' => 5,
                    'marzo' => 5,
                )
            ),
        ),
    )
);

$data = array_filter($data, 'removeEmptyElements');
var_dump($data);

¡it works!

A: As per your method, you can just catch those elements in an another array and use that one like follows,
foreach($linksArray as $link){
   if(!empty($link)){
      $new_arr[] = $link
   }
}

print_r($new_arr);

A: I think array_walk is much more suitable here
$linksArray = array('name', '        ', '  342', '0', 0.0, null, '', false);

array_walk($linksArray, function(&$v, $k) use (&$linksArray){
    $v = trim($v);
    if ($v == '')
        unset($linksArray[$k]);
});
print_r($linksArray);

Output:
Array
(
    [0] => name
    [2] => 342
    [3] => 0
    [4] => 0
)

*

*We made sure that empty values are removed even if the user adds more than one space

*We also trimmed empty spaces from the valid values

*Finally, only (null), (Boolean False) and ('') will be considered empty strings
As for False it's ok to remove it, because AFAIK the user can't submit boolean values.

A: As you're dealing with an array of strings, you can simply use array_filter(), which conveniently handles all this for you:
print_r(array_filter($linksArray));

Keep in mind that if no callback is supplied, all entries of array equal to FALSE (see converting to boolean) will be removed. So if you need to preserve elements that are i.e. exact string '0', you will need a custom callback:
// PHP 7.4 and later
print_r(array_filter($linksArray, fn($value) => !is_null($value) && $value !== ''));

// PHP 5.3 and later
print_r(array_filter($linksArray, function($value) { return !is_null($value) && $value !== ''; }));

// PHP < 5.3
print_r(array_filter($linksArray, create_function('$value', 'return $value !== "";')));

Note: If you need to reindex the array after removing the empty elements, use: $linksArray = array_values(array_filter($linksArray));

A: You can use array_filter to remove empty elements:
$emptyRemoved = array_filter($linksArray);

If you have (int) 0 in your array, you may use the following:
$emptyRemoved = remove_empty($linksArray);

function remove_empty($array) {
  return array_filter($array, '_remove_empty_internal');
}

function _remove_empty_internal($value) {
  return !empty($value) || $value === 0;
}

EDIT: Maybe your elements are not empty per se but contain one or more spaces... You can use the following before using array_filter
$trimmedArray = array_map('trim', $linksArray);

A: The most popular answer on this topic is absolutely INCORRECT.
Consider the following PHP script:
<?php
$arr = array('1', '', '2', '3', '0');
// Incorrect:
print_r(array_filter($arr));
// Correct:
print_r(array_filter($arr, 'strlen'));

Why is this?  Because a string containing a single '0' character also evaluates to boolean false, so even though it's not an empty string, it will still get filtered.  That would be a bug.
Passing the built-in strlen function as the filtering function will work, because it returns a non-zero integer for a non-empty string, and a zero integer for an empty string.  Non-zero integers always evaluate to true when converted to boolean, while zero integers always evaluate to false when converted to boolean.
So, the absolute, definitive, correct answer is:
$arr = array_filter($arr, 'strlen');

A: If you are working with a numerical array and need to re-index the array after removing empty elements, use the array_values function:
array_values(array_filter($array));

Also see: PHP reindex array?

A: The most voted answer is wrong or at least not completely true as the OP is talking about blank strings only. Here's a thorough explanation:
What does empty mean?
First of all, we must agree on what empty means. Do you mean to filter out:

*

*the empty strings only ("")?

*the strictly false values? ($element === false)

*the falsey values? (i.e. 0, 0.0, "", "0", NULL, array()...)

*the equivalent of PHP's empty() function?

How do you filter out the values
To filter out empty strings only:
$filtered = array_diff($originalArray, array(""));

To only filter out strictly false values, you must use a callback function:
$filtered = array_diff($originalArray, 'myCallback');
function myCallback($var) {
    return $var === false;
}

The callback is also useful for any combination in which you want to filter out the "falsey" values, except some. (For example, filter every null and false, etc, leaving only 0):
$filtered = array_filter($originalArray, 'myCallback');
function myCallback($var) {
    return ($var === 0 || $var === '0');
}

Third and fourth case are (for our purposes at last) equivalent, and for that all you have to use is the default:
$filtered = array_filter($originalArray);

A: $a = array(1, '', '', '', 2, '', 3, 4);
$b = array_values(array_filter($a));

print_r($b)

A: For multidimensional array
$data = array_map('array_filter', $data);
$data = array_filter($data);

A: $linksArray = array_filter($linksArray);

"If no callback is supplied, all entries of input equal to FALSE will be removed." -- http://php.net/manual/en/function.array-filter.php

A: I had to do this in order to keep an array value of (string) 0
$url = array_filter($data, function ($value) {
  return (!empty($value) || $value === 0 || $value==='0');
});

A: With these types of things, it's much better to be explicit about what you want and do not want.
It will help the next guy to not get caught by surprise at the behaviour of array_filter() without a callback. For example, I ended up on this question because I forgot if array_filter() removes NULL or not. I wasted time when I could have just used the solution below and had my answer.
Also, the logic is language angnostic in the sense that the code can be copied into another language without having to under stand the behaviour of a php function like array_filter when no callback is passed.
In my solution, it is clear at glance as to what is happening. Remove a conditional to keep something or add a new condition to filter additional values.
Disregard the actual use of array_filter() since I am just passing it a custom callback - you could go ahead and extract that out to its own function if you wanted. I am just using it as sugar for a foreach loop.
<?php

$xs = [0, 1, 2, 3, "0", "", false, null];

$xs = array_filter($xs, function($x) {
    if ($x === null) { return false; }
    if ($x === false) { return false; }
    if ($x === "") { return false; }
    if ($x === "0") { return false; }
    return true;
});

$xs = array_values($xs); // reindex array

echo "<pre>";
var_export($xs);

Another benefit of this approach is that you can break apart the filtering predicates into an abstract function that filters a single value per array and build up to a composable solution.
See this example and the inline comments for the output.
<?php

/**
 * @param string $valueToFilter
 *
 * @return \Closure A function that expects a 1d array and returns an array
 *                  filtered of values matching $valueToFilter.
 */
function filterValue($valueToFilter)
{
    return function($xs) use ($valueToFilter) {
        return array_filter($xs, function($x) use ($valueToFilter) {
            return $x !== $valueToFilter;
        });
    };
}

// partially applied functions that each expect a 1d array of values
$filterNull = filterValue(null);
$filterFalse = filterValue(false);
$filterZeroString = filterValue("0");
$filterEmptyString = filterValue("");

$xs = [0, 1, 2, 3, null, false, "0", ""];

$xs = $filterNull($xs);        //=> [0, 1, 2, 3, false, "0", ""]
$xs = $filterFalse($xs);       //=> [0, 1, 2, 3, "0", ""]
$xs = $filterZeroString($xs);  //=> [0, 1, 2, 3, ""]
$xs = $filterEmptyString($xs); //=> [0, 1, 2, 3]

echo "<pre>";
var_export($xs); //=> [0, 1, 2, 3]

Now you can dynamically create a function called filterer() using pipe() that will apply these partially applied functions for you.
<?php

/**
 * Supply between 1..n functions each with an arity of 1 (that is, accepts
 * one and only one argument). Versions prior to php 5.6 do not have the
 * variadic operator `...` and as such require the use of `func_get_args()` to
 * obtain the comma-delimited list of expressions provided via the argument
 * list on function call.
 *
 * Example - Call the function `pipe()` like:
 *
 *   pipe ($addOne, $multiplyByTwo);
 *
 * @return closure
 */
function pipe()
{
    $functions = func_get_args(); // an array of callable functions [$addOne, $multiplyByTwo]
    return function ($initialAccumulator) use ($functions) { // return a function with an arity of 1
        return array_reduce( // chain the supplied `$arg` value through each function in the list of functions
            $functions, // an array of functions to reduce over the supplied `$arg` value
            function ($accumulator, $currFn) { // the reducer (a reducing function)
                return $currFn($accumulator);
            },
            $initialAccumulator
        );
    };
}

/**
 * @param string $valueToFilter
 *
 * @return \Closure A function that expects a 1d array and returns an array
 *                  filtered of values matching $valueToFilter.
 */
function filterValue($valueToFilter)
{
    return function($xs) use ($valueToFilter) {
        return array_filter($xs, function($x) use ($valueToFilter) {
            return $x !== $valueToFilter;
        });
    };
}

$filterer = pipe(
    filterValue(null),
    filterValue(false),
    filterValue("0"),
    filterValue("")
);

$xs = [0, 1, 2, 3, null, false, "0", ""];
$xs = $filterer($xs);

echo "<pre>";
var_export($xs); //=> [0, 1, 2, 3]

A: try this **
**Example
$or = array(
        'PersonalInformation.first_name' => $this->request->data['User']['first_name'],
        'PersonalInformation.last_name' => $this->request->data['User']['last_name'],
        'PersonalInformation.primary_phone' => $this->request->data['User']['primary_phone'],
        'PersonalInformation.dob' => $this->request->data['User']['dob'],
        'User.email' => $this->request->data['User']['email'],
    );

 $or = array_filter($or);

    $condition = array(
        'User.role' => array('U', 'P'),
        'User.user_status' => array('active', 'lead', 'inactive'),
        'OR' => $or
    );


Q: Do...while is not working in input verification So I'm trying to do an input verification for my program in java, and I'm trying to do that in this setter:
  public void setClientName(String clientName) {
        boolean valid;
        do{
            valid = false;
            try{
                 if(clientName.matches("[a-zA-Z]+")){
                    this.clientName = clientName;
                 }else{
                     throw new IllegalArgumentException("Invalid client name");
                 }
            }catch(Exception e){
                System.out.println("Invalid name");
                valid = true;
            }
        }while(!valid);
    }

But when I call it and put a wrong name, the do...while does not work and the program just continue
Here's where I call it
  public void openAccount(int i){
        nCartao = 2021120040 + i;
        System.out.println("Account Number : " + (nCartao));
        System.out.println("Client Name :");

        setClientName(sc.next()); // I CALL IT HERE

        System.out.println("Client Age : ");
        age = sc.nextInt();
        System.out.println("Balance :");
        balance = sc.nextInt();
    }

What am I doing wrong?

A: Maybe that's because in your catch you are stating that valid is true when it should be false to repeat the block.


Q: Deedle Frame From Database, What is the Schema? I am new to Deedle, and in documentation I cant find how to solve my problem.
I bind an SQL Table to a Deedle Frame using the following code:
namespace teste

open FSharp.Data.Sql
open Deedle
open System.Linq

module DatabaseService =

    [<Literal>]
    let connectionString = "Data Source=*********;Initial Catalog=*******;Persist Security Info=True;User ID=sa;Password=****";

    type bd = SqlDataProvider<
                ConnectionString = connectionString,
                DatabaseVendor = Common.DatabaseProviderTypes.MSSQLSERVER >

    type Database() =

        static member contextDbo() =
            bd.GetDataContext().Dbo

        static member acAgregations() =
            Database.contextDbo().AcAgregations |> Frame.ofRecords

        static member acBusyHourDefinition() =
            Database.contextDbo().AcBusyHourDefinition
            |> Frame.ofRecords "alternative_reference_table_scan", "formula"]

        static member acBusyHourDefinitionFilterByTimeAgregationTipe(value:int) =
            Database.acBusyHourDefinition()
            |> Frame.getRows

These things are working properly becuse I can't understand the Data Frame Schema, for my surprise, this is not a representation of the table.
My question is:
how can I access my database elements by Rows instead of Columns (columns is the Deedle Default)? I Thied what is showed in documentation, but unfortunatelly, the columns names are not recognized, as is in the CSV example in Deedle Website.

A: With Frame.ofRecords you can extract the table into a dataframe and then operate on its rows or columns. In this case I have a very simple table. This is for SQL Server but I assume MySQL will work the same. If you provide more details in your question the solution can narrowed down.
This is the table, indexed by ID, which is Int64:

You can work with the rows or the columns:
#if INTERACTIVE
#load @"..\..\FSLAB\packages\FsLab\FsLab.fsx"
#r "System.Data.Linq.dll"
#r "FSharp.Data.TypeProviders.dll"
#endif

//open FSharp.Data
//open System.Data.Linq
open Microsoft.FSharp.Data.TypeProviders
open Deedle

[<Literal>]
let connectionString1 = @"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\userName\Documents\tes.sdf.mdf"

type dbSchema = SqlDataConnection<connectionString1>
let dbx = dbSchema.GetDataContext()

let table1 = dbx.Table_1

query { for row in table1 do
        select row} |> Seq.takeWhile (fun x -> x.ID < 10L) |> Seq.toList
// check if we can connect to the DB.

let df = table1 |> Frame.ofRecords // pull the table into a df
let df = df.IndexRows<System.Int64>("ID") // if you need an index
df.GetRows(2L) // Get the second row, but this can be any kind of index/key
df.["Number"].GetSlice(Some 2L, Some 5L) // get  the 2nd to 5th row from the Number column

Will get you the following output:
val it : Series<System.Int64,float> =
2 -> 2

>
val it : Series<System.Int64,float> =
2 -> 2
3 -> 3
4 -> 4
5 -> 5

Depending on what you're trying to do Selecting Specific Rows in Deedle might also work.
Edit
From your comment you appear to be working with some large table. Depending on how much memory you have and how large the table you still might be able to load it. If not these are some of things you can do in increasing complexity:

*

*Use a query { } expression like above to narrow the dataset on the database server and convert just part of the result into a dataframe. You can do quite complex transformations so you might not even need the dataframe in the end. This is basically Linq2Sql.

*Use lazy loading in Deedle. This works with series so you can get a few series and reassemble a dataframe.

*Use Big Deedle which is designed for this sort of thing.


Q: Custom cell in list in Flash AS3 I am no expert in Flash, and I need some quick help here, without needing to learn everything from scratch.
Short story, I have to make a list where each cell contains an image, two labels, and a button.
List/Cell example:

img  - label - label - button

img  - label - label - button

As a Java-programmer, I have tried to quicly learn the syntax and visualness of Flash and AS3, but with no luck so far.
I have fairly understood the basics of movie clips etc.
I saw a tutorial on how to add a list, and add some text to it. So I dragged in a list, and in the code went list.addItem({label:"hello"}); , and that worked ofc. So i thought if I double-clicked the MC of the list, i would get to tweak some things. In there I have been wandering around different halls of cell-renderers etc.
I have now come to the point that I entered the CellRenderer_skinUp or something, and customized it to my liking. When this was done, I expected i could use list.addItem(); and get an empty "version" of my cell, with the img, labels and the button. But AS3 expects an input in addItem. From my object-oriented view, I am thinking that i have to create an object of the cell i have made, but i have no luck reaching it.. I tried to go
var test:CellRenderer = list.listItem;
list.addItem(test);
..But with no luck.
This is just for funsies, but I really want to make this work, however not so much that I am willing to read up on ALOT of Flash and AS3. I felt that I was closing in on the prize, but the compiler expected a semicolon after the variable (list.addItem({test:something});).
Note: If possible, I do NOT want this:
list.addItem({image:"src",label:"text",label"text",button:"text"});
Well.. It actually is what I want, but I would really like to custom-draw everything.
Does anyone get what I am trying to do, and has any answers for me? Am I approaching this the wrong way? I have searched the interwebs for custom list-cells, but with no luck.
Please, any guiding here is appreciated!
Sti

A: You could use a Datagrid as well, with each column pointing to the appropriate part of the data source (possibly even the same field, depending on what you're doing). You can then just use the ImageCell as the renderer for the second and third colums.
I think you're just not understanding that Adobe, in the own woolly-headed little way, is separating the Model from the View on your behalf. You hand the Model to the View and then get out of the way. The extent of what you can/should change is just telling it what renderer to pop your data into.
In fact, the fl.controls don't give you much control at all about how they work--I wouldn't go down the road of trying to create a custom itemRenderer with any signifcant functionality for them if you don't fully understand how the Display List works and if you're not comfortable digging around in the debugger and ferreting out all kinds of undocumented information.
For more details (to the extent anyone knows anything about how these work), see
http://www.adobe.com/devnet/flash/quickstart/datagrid_pt1.html
http://www.adobe.com/devnet/flash/quickstart/datagrid_pt2.htmlhttp://www.adobe.com/devnet/flash/quickstart/datagrid_pt3.html
http://www.adobe.com/devnet/flash/quickstart/tilelist_component_as3.html
Do you have the option to use the Flex Framework instead of pure Flash? It makes this kind of extension much more satisfying. It's aimed more at application developers, whereas Adobe sees Flash users more as designers.


Q: Fragment Missing From Product I created a localization fragment for one of our projects which works nicely when started from the IDE, but not at all when started from the exported product.
The fragment itself only really has two files, a MANIFEST.MF:
Manifest-Version: 1.0
Bundle-ManifestVersion: 2
Bundle-Name: L10N Fragment
Bundle-SymbolicName: org.acme.module.nl_xx;singleton:=true
Bundle-Version: 3.0.6.qualifier
Bundle-Vendor: ACME
Fragment-Host: org.acme.module;bundle-version="[1.0.0,2.0.0)"
Bundle-RequiredExecutionEnvironment: JavaSE-11

...and a properties file messages_de_de_xx.properties:
Special = Something

The product is started with -nl de_DE_XX and -Djava.language=de -Djava.country=DE -Djava.variant=XX. As noted, it works from Eclipse, but not from the finished EXE.
Things I tried to debug / fix:

*

*made sure the exported product contains the fragment

*made sure the build.properties / fragment JAR contains the above two files

*played around with the country and variant (toggled upper and lower case)

*cleared the OSGi instance area (i.e. the application preferences)

*made sure the fragment is resolved using the OSGi console

*tested it with a messages file for en_UK_XX (which is based on the English localization instead of the German one)

*made sure that the files configuration\org.eclipse.equinox.simpleconfigurator\bundles.info and artifacts.xml contain something that looks plausible for the fragment

Nothing worked, so I'm out of ideas.
What could be the problem? What can I do to debug the application?

A: This is an incredible stupid problem. The messages file is supposed to have the name messages_de_DE_XX.properties (note that the last two segments are in upper case).
My guess is it works when started from the IDE because Eclipse uses the filesystem and hence the OS standard, which is "ignore casing" for Windows.
When started from the finished product however the files are in JARs, where casing is important.


Q: Display or get the HTTP header attributes in Rails 4 I have an application developed in Rails and I am trying to see the attributes in the HTTP header.
Is there any way to read these attributes? Where are they stored?
Someone mentioned request.headers. Is this correct? I am not able to see any attributes inside this array.

A: This code solved my question request.env["HTTP_MY_HEADER"]. The trick was that I had to prefix my header's name with HTTP

A: I've noticed in Rails 5 they now expect headers to be spelled like this in the request:
Access-Token
Before they are transformed into:
HTTP_ACCESS_TOKEN
In Rails. Doing ACCESS_TOKEN will no longer work.

A: request.headers does not return a hash, but an instance of ActionDispatch::Http::Headers, which is a wrapper around rack env.
ActionDispatch::Http::Headers implements many methods like [] and []= which make it behave like a hash, but it doesn't override the default inspect, hence you can't see the key-value pairs by just p or pp it.
You can, however, see the request headers in the rack env:
pp request.headers.env.select{|k, _| k =~ /^HTTP_/}

Remember that the request headers in rack env are the upcased, underscored and HTTP_ prefixed version of the original http request headers.
UPDATE
Actually there are a finite set of request headers that are not prefixed HTTP_. These (capitalized and underscored) header names are stored in ActionDispatch::Http::Headers::CGI_VARIABLES. I list them below:
    AUTH_TYPE
    CONTENT_LENGTH
    CONTENT_TYPE
    GATEWAY_INTERFACE
    HTTPS
    PATH_INFO
    PATH_TRANSLATED
    QUERY_STRING
    REMOTE_ADDR
    REMOTE_HOST
    REMOTE_IDENT
    REMOTE_USER
    REQUEST_METHOD
    SCRIPT_NAME
    SERVER_NAME
    SERVER_PORT
    SERVER_PROTOCOL
    SERVER_SOFTWARE

So the full version of listing request headers would be
pp request.headers.env.select{|k, _| k.in?(ActionDispatch::Http::Headers::CGI_VARIABLES) || k =~ /^HTTP_/}

A: You can see hash of actual http headers using @_headers in controller.


Q: Finding files in list using bash array loop I'm trying to write a script that reads a file with filenames, and outputs whether or not those files were found in a directory.
Logically I'm thinking it goes like this:
$filelist = prompt for file with filenames
$directory = prompt for directory path where find command is performed

new Array[] = read $filelist line by line

for i, i > numberoflines, i++
     if find Array[i] in $directory is false
        echo "$i not found"
export to result.txt

I've been having a hard time getting Bash to do this, any ideas?

A: First, I would just assume that all the file-names are supplied on standard input. E.g., if the file names.txt contains the file-names and check.sh is the script, you can invoke it like
cat names.txt | ./script.sh

to obtain the desired behaviour (i.e., using the file-names from names.txt).
Second, inside script.sh you can loop as follows over all lines of the standard input
while read line
do
  ... # do your checks on $line here
done

Edit: I adapted my answer to use standard input instead of command line arguments, due to the problem indicated by @rici.

A: while read dirname
do
  echo $dirname >> result.txt
  while read filename
  do
    find $dirname -type f -name $filename >> result.txt
  done <filenames.txt
done <dirnames.txt


Q: Force browser to display ISO-8859-1 without interpreting as Windows-1252 Historically, a lot of web pages advertising themselves as being in the ISO-8859-1 (Latin-1) encoding actually contained content in the Windows-1252 encoding (which is a strict superset of Latin-1).
This was enough of a problem that browsers updated their behaviour to treat all Latin-1 text as if it were Windows-1252. This behaviour was then rationalised into the HTML5 [draft] standard.
I'm writing a set of pages on which I want to show the difference between the two encodings, however this seems to be impossible because my Latin-1 page is never actually treated as Latin-1. Is there any way, in any browser, that I can actually force the page encoding to be respected and display the demo?

A: I’m afraid there is no direct way. I thought Opera once had an option for this, and its current version has an option (via opera:config) to force a specific encoding, overriding HTTP headers and all, but even there, iso-8859-1 actually means windows-1252. I checked Opera versions 5 and 9 too, no luck.
But using the current version of Opera (12.02), you can set the encoding via View → Encoding, and in the “Western” set (where iso-8859-1 means windows-1252 as usual), selecting iso-8859-15 causes the range 130–159 (decimal) of bytes to be effectively ignored in display, not shown as per windows-1252. So this more or less means treating the data as genuinely iso-8859-1 – except of course that the few graphic characters where iso-8859-1 and iso-8859-15 differ, the latter is used.
Technically, those bytes represent C1 Controls in iso-8859-1, and in the mode described above, Opera actually treats them that way. They are disallowed in HTML but normally just ignored by browsers.


Q: Cross browser video autoplay loop I have a copy of a mp4 video which I want to show on my website and I want to know how is it possible with javascript to autoplay and loop for ever the video.
I want to make it compatible with all browsers.
I want to load the video on load of the page with js
Thank you.

A: <video autoplay loop>
  <source src="movie.mp4" type="video/mp4" />
  <source src="movie.ogg" type="video/ogg" />
</video>

You mean this?

A: You’ll need to mute the video (adding the muted attribute on the <video> tag) as videos with sound don’t autoplay in all browsers. Then also add the attributes autoplay and playsinline. Also you can use the videoEnd event and call play() to ensure it loops.


Q: JSON_QUERY unable to handle NULL I have a table. Few columns are of String, Integer type. And few are JSON type. I am writing a query to form each row as a json object. I have issues with JSON_QUERY(jsondataColumnName). If the column is populated NULL JSON_QUERY fails.
I have already written query below.
select
(
    SELECT     [customerReferenceNumber] as customerReferenceNumber
              ,[customerType] as customerType
              ,[personReferenceNumber] as personReferenceNumber
              ,[organisationReferenceNumber] as organisationReferenceNumber
              ,json_query(isnull(product,'')) as product
              ,json_query(isnull([address],'')) as address

  FROM [dbo].[customer]
  FOR JSON PATH, WITHOUT_ARRAY_WRAPPER) AS customer
from [dbo].[customer] P

Msg 13609, Level 16, State 1, Line 2
  JSON text is not properly formatted. Unexpected character '.' is found at position 0.

A: By default, for JSON don't work with NULL VALUES. Use INCLUDE_NULL_VALUES to handle.
As Example:  JSON PATH, WITHOUT_ARRAY_WRAPPER, INCLUDE_NULL_VALUES) AS customer
As reference:
 https://learn.microsoft.com/en-us/sql/relational-databases/json/include-null-values-in-json-include-null-values-option?view=sql-server-ver15


Q: I want to display PDFs and images in Firebase Storage I would like to use FirebaeStorage to display PDFs and images.
↓The code below is the code to display the file list
（I was able to get the data from Firebase and display the List.）

class Gakubu extends StatefulWidget {
  const Gakubu({Key? key}) : super(key: key);

  @override
  State<Gakubu> createState() => _GakubuState();
}

class _GakubuState extends State<Gakubu> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('学部'),
      ),
      body: Container(
        child: ListView(
          children: [
            Card(
              child: ListTile(
                leading: Icon(Icons.folder),
                trailing: Icon(Icons.chevron_right),
                title: Text('工学部'),
                onTap: () =>
                    Navigator.of(context).push(MaterialPageRoute(
                      builder: (context) => kougaku(),
                    )
                    ),
              ),
            ),
            Card(
              child: ListTile(
                  leading: Icon(Icons.folder),
                  trailing: Icon(Icons.chevron_right),
                  title: Text('情報理工学部'),
                onTap: () =>
                    Navigator.of(context).push(MaterialPageRoute(
                      builder: (context) => zyouhourikou(),
                    )
                    ),              ),
            ),
            Card(
              child: ListTile(
                leading: Icon(Icons.folder),
                trailing: Icon(Icons.chevron_right),
                title: Text('教育学部'),
                onTap: () =>
                    Navigator.of(context).push(MaterialPageRoute(
                      builder: (context) => kyouiku(),
                    )
                    ),
              ),
            ),
            Card(
              child: ListTile(
                leading: Icon(Icons.folder),
                trailing: Icon(Icons.chevron_right),
                title: Text('獣医学部'),
                onTap: () =>
                    Navigator.of(context).push(MaterialPageRoute(
                      builder: (context) => zyuui(),
                    )
                    ),
              ),
            ),
            Card(
              child: ListTile(
                leading: Icon(Icons.folder),
                trailing: Icon(Icons.chevron_right),
                title: Text('理学部'),
                onTap: () =>
                    Navigator.of(context).push(MaterialPageRoute(
                      builder: (context) => rigaku(),
                    )
                    ),
              ),
            ),
            Card(
              child: ListTile(
                leading: Icon(Icons.folder),
                trailing: Icon(Icons.chevron_right),
                title: Text('生命科学部'),
                onTap: () =>
                    Navigator.of(context).push(MaterialPageRoute(
                      builder: (context) => seimei(),
                    )
                    ),
              ),
            ),
            Card(
              child: ListTile(
                leading: Icon(Icons.folder),
                trailing: Icon(Icons.chevron_right),
                title: Text('生物地球学部'),
                onTap: () =>
                    Navigator.of(context).push(MaterialPageRoute(
                      builder: (context) => seibutu(),
                    )
                    ),
              ),
            ),
            Card(
              child: ListTile(
                leading: Icon(Icons.folder),
                trailing: Icon(Icons.chevron_right),
                title: Text('経営学部'),
                onTap: () =>
                    Navigator.of(context).push(MaterialPageRoute(
                      builder: (context) => keiei(),
                    )
                    ),
              ),
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          //ポップアップメニュー実装
          showModalBottomSheet(
            //モーダルの背景の色、透過
              backgroundColor: Colors.transparent,
              //ドラッグ可能にする（高さもハーフサイズからフルサイズになる様子）
              isScrollControlled: true,
              context: context,
              builder: (BuildContext context) {
                return Container(
                  margin: EdgeInsets.only(top: 150),
                  decoration: BoxDecoration(
                    //モーダル自体の色
                    color: Colors.white,
                    //角丸にする
                    borderRadius: BorderRadius.only(
                      topLeft: Radius.circular(20),
                      topRight: Radius.circular(20),
                    ),
                  ),
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.start,
                    children: [
                      Text(
                        '過去問をアップロード',
                        style: TextStyle(
                          fontSize: 25,
                          color: Colors.black,
                          fontWeight: FontWeight.bold,
                        ),
                      ),
                      Padding(
                        padding: const EdgeInsets.all(8.0), //マージン
                        child: SizedBox(
                          width: double.infinity,
                          height: 50,
                          child: ElevatedButton.icon(
                            icon: Icon(Icons.photo_library),
                            label: Text(
                              'アルバムから選択',
                              textAlign: TextAlign.left,
                            ),
                            onPressed: () {},
                          ),
                        ),
                      ),
                      Padding(
                        padding: const EdgeInsets.all(8.0), //マージン
                        child: SizedBox(
                          width: double.infinity,
                          height: 50,
                          child: ElevatedButton.icon(
                            icon: Icon(Icons.camera),
                            label: Text(
                              '写真を撮る',
                              textAlign: TextAlign.left,
                            ),
                            onPressed: () {},
                          ),
                        ),
                      ),
                      Padding(
                        padding: const EdgeInsets.all(8.0), //マージン
                        child: SizedBox(
                          width: double.infinity,
                          height: 50,
                          child: ElevatedButton.icon(
                              icon: Icon(Icons.folder),
                              label: Text(
                                '複数以上のファイル',
                                textAlign: TextAlign.left,
                              ),
                              onPressed: () => launch(
                                  'https://docs.google.com/forms/d/e/1FAIpQLSda45WF5uVd9mRFs_4nPCiM6bxFqpUKZSApYFWUVlAVtDlg_g/viewform?usp=sf_link')),
                        ),
                      ),
                      Padding(
                        padding: const EdgeInsets.all(8.0), //マージン
                        child: SizedBox(
                          width: double.infinity,
                          height: 50,
                          child: ElevatedButton.icon(
                              icon: Icon(Icons.link),
                              label: Text(
                                'ドライブなどのURL',
                                textAlign: TextAlign.left,
                              ),
                              onPressed: () => launch(
                                  'https://docs.google.com/forms/d/e/1FAIpQLSdEIS3eOynTihQ3AEk0zrp7mSpmcfqpEGxTOUIDp6Mzi19jqA/viewform?usp=sf_link')),
                        ),
                      ),
                      Text(
                        'アップロードあざます！',
                        style: TextStyle(
                          fontSize: 20,
                          color: Colors.black,
                        ),
                      ),
                    ],
                  ),
                );
              });
        },
        child: const Icon(Icons.upload_rounded),
      )
      ,
    );
  }
}

This code is for displaying images and PDFs. (This code can only display PDFs.)

class ImagePage extends StatelessWidget {
  final FirebaseFile file;

  const ImagePage({
    Key? key,
    required this.file,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    final isImage = ['.jpeg', '.jpg', '.png'].any(file.name.contains);
    final isPdf = ['.pdf'].any(file.name.contains);

    return Scaffold(
      appBar: AppBar(
        title: Text(file.name),
        centerTitle: true,
      ),
      body: SfPdfViewer.network(
        file.url
      ),
    );

  }
  }

 final isImage = ['.jpeg', '.jpg', '.png'].any(file.name.contains);
    final isPdf = ['.pdf'].any(file.name.contains);

Here I would like to have the process change depending on the file extension.
for example
sfpdfview for PDF
imageview for image
Any ideas?


Q: ImportError: No module named django.core.wsgi for wsgi server setting I am setting with djano and uwsgi
$uwsgi --ini uwsgi.ini
My Django root is here /var/www/html/myapp/current
It must be  quite simple setting however I am not sure the yet.
I have these two files
/var/www/html/myapp/current/myapp/settings.py
/var/www/html/myapp/current/myapp/wsgi.py
[uwsgi]
chdir=/var/www/html/myapp/current #it success
module=myapp.wsgi:application #it success
env DJANGO_SETTINGS_MODULE=myapp.settings # it success
http-socket = 0.0.0.0:8008
processes = 1
threasds = 1
master = 1
max-requests = 100000

The error is below, but I can't dig the detailed logs.
spawned uWSGI worker 1 (pid: 27353, cores: 1)
--- no python application found, check your startup logs for errors ---
[pid: 27353|app: -1|req: -1/1] 172.17.1.143 () {28 vars in 334 bytes} [Thu Mar 26 17:37:01 2020] GET / => generated 21 bytes in 0 msecs (HTTP/1.1 500) 2 headers in 83 bytes (0 switches on core 0)

And this error occurs.
*** Operational MODE: single process ***
Traceback (most recent call last):
  File "./myapp/wsgi.py", line 13, in <module>
    from django.core.wsgi import get_wsgi_application
ImportError: No module named django.core.wsgi
unable to load app 0 (mountpoint='') (callable not found or import error)
*** no app loaded. going in full dynamic mode ***
*** uWSGI is running in multiple interpreter mode ***
spawned uWSGI master process (pid: 1705)
spawned uWSGI worker 1 (pid: 1706, cores: 1)
spawned uWSGI http 1 (pid: 1707)

error happens here
from django.core.wsgi import get_wsgi_application

Also I am using anaconda3
$conda activate py37 then
start this command
$uwsgi --ini uwsgi.ini

A: I solved the problem , the problem was uwsgi itself.
My setting file was ok.
install uwsgi by conda
conda install -c conda-forge libiconv
conda install -c conda-forge uwsgi
then start uwsgi /home/ubuntu/anaconda3/envs/py37/bin/uwsgi --ini uwsgi.ini


Q: Add style to bundled code using webpack GitHub: https://github.com/Chirag161198/react-boilerplate 1
Here is the react boilerplate I’m trying to make from scratch.
I have bundled html with the react code but I’m not able to add styles (CSS).
I have heard about ExtractTextPlugin but not able to configure it.
Please suggest some way to add styles to it.
Thank you in advance.

A: You need to use style-loader and css-loader in your webpack.config.js
First, install these two packages via npm:
npm install style-loader, css-loader --dev
Then, create a styles.css in your src folder and append the following styles into the file (just for demo purpose, so you know it's working correctly):
body {
  background-color: #ff4444;
}

Don't forget to import the css file in your src/index.js:
import React from 'react';
import ReactDOM from 'react-dom';
import App from './components/App.js';
import './styles.css'; // <- import the css file here, so webpack will handle it when bundling

ReactDOM.render(<App />, document.getElementById('app'));

And use style-loader and css-loader in your webpack.config.js:
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {
  entry: './src/index.js',
  output: {
    path: path.join(__dirname, 'dist'),
    filename: 'bundle.js',
  },
  module: {
    rules: [
      {
        test: /\.js$/,
        exclude: /node_modules/,
        use: { loader: 'babel-loader' },
      },

      {
        test: /\.css$/,
        use: ['style-loader', 'css-loader'],
      },
    ],
  },

  plugins: [
    new HtmlWebpackPlugin({
      template: './src/index.html',
    }),
  ],
};

If you don't see the correct output, you might need to restart the webpack dev server again. I have cloned your repo and made the changes like I mentioned above, it works.
As for ExtractTextPlugin, you will need this when bundling for a production build, you can learn more from their Repo
Hope it helps!

A: Hi Chirag ExtractTextPlugin works great but when it comes to caching and bundle hashing. Css bundle becomes 0 bytes. So they introduced MiniCssExtractPlugin which has tackled this issue. It is really important to cache static files as your app size increase by time.
import plugin first:
var MiniCssExtractPlugin = require("mini-css-extract-plugin");

add these in your webpack config:
rules: [

   {
      test: /\.js$/,
      exclude: /node_modules/,
      use: {
        loader: 'babel-loader'
      }
    },
    {
      test: /\.scss$/,
      use:  [  'style-loader', MiniCssExtractPlugin.loader, 'css-loader', 'sass-loader']
    }
  ]
}
plugins: [
  new MiniCssExtractPlugin({
    filename: 'style.css',
  }),
  new HtmlWebpackPlugin({
    template: './src/index.html',
  }),

Let me know you the issue still persists.

A: first you need to load style-loader and css-loader.Then you will add the following code in "rules" in webpack.config.js file.
{ test: /\.css$/,use: ['style-loader', 'css-loader']}

then import the "style.css" file location into the "index.js" file and for example:
import "./style.css";

When you package, "css" codes will be added in "bundle.js".


Q: MS Access: Report to contain info from third table I'm currently working on a database for a company, for them to use when making production orders. A report is to be made consisting of several things, mainly product number, order number etc etc. A part of the report is to be made up of a list of spare parts needed for the production of the item in question. I have a table with an order number and product number, which needs to look in another table to find the necessary spare parts. However, the name, location and stock of those spare parts are in a third table, and I can't seem to find a way to include these things automatically when the product number is known. I'm pretty new to MS Access, so any help will be greatly appreciated. Thanks!
I have a table called Table1, which uses a combobox to automatically fill boxes such as production time, test time etc from a given product number. This data is gathered from the second table StandardTimes, which has as a primary key the product number. Other columns in this table includes production area, standard quantity, average production time, and also includes in several columns, the necessary spare parts needed. In a third table called Inventory, we have the product numbers of the spare parts, their location in storage, and number of items currently in store. I created a report using a query which takes an order number, and creates a report on that order number from Table1. What needs to be included in this report is a list of the spareparts necessary, the location in the storage, and the number of items currently in store.

Revised from new user input
Your question still does not provide actual columns or data. As a result, it's hard to model your needs.
However, based on what I can read, I think that you have are missing some basic design setup items in a relational model.
Assuming that you have 3 tables: Table1 (Orders), StandardTimes (Products) and Inventory (SpareParts)
In English, every order has one or more products. Every product has one or more spare parts. Really you'd want an orders table, and an order details table which has records for each item as part of that order. But I'm answering it on your setup which I believe is flawed.
Orders <-(1:M)-> Products <- (1:M) -> SpareParts
You have an OrderID, a ProductID, and a SparePartID.
A query such as this would join those 3 tables together with that kind of relationship.
SELECT  o.OrderNum, o.ProductNum, st.ProductionArea, st.StandardQuality, i.SparePartsNum, i.Location, i.Qty
FROM Orders as o
INNER JOIN StanardTimes as st on o.ProductNum = st.ProductNum
INNER JOIN Inventory as i on i.ProductNum = st.ProductNum

A: Some sample data would be helpful to help design the queries.
In principal you would need to join the tables together to get the desired result.
You would join the productID on tblOrders to the ProductID on tblProducts. This will net you the name of the product etc.
This would be an INNER join, as every order has a product.
You would then join to tblSpareParts, also using the productID so that you could return the status of the spare parts for that product. This might be a LEFT JOIN instead of an INNER, but it depends on if you maintain a value of 0 for spare parts (e.g. Every product has a corresponding spare parts record), or if you only maintain a spare parts record for items which have spare parts.


Q: cgridveiw to display fetched data via customized query I am a newbei in yii, when a person clicks on a category display him all products under that particular category in a gridview
view
productcategory
    <?php $this->widget('zii.widgets.grid.CGridView', array(
'id'=>'admin-grid',
'dataProvider'=>$model->SelectedCategoryProducts,
'filter'=>$model,
'columns'=>array(
    'Name',
    'Model',
    'Brand',
    'Price',

    array(
        'class'=>'CButtonColumn',
    ),
),
 )); ?>

controller
product
    public function actionProductcategory($id)

{
$model= Product::model()->SelectedCategoryProducts($id);
    var_dump($model);

    $this->render('productcategory',array(
        'model'=>$model,'id'=>$id,
    ));

}
  model
   product
  public function SelectedCategoryProducts($id)
{
    $dataProvider=new CActiveDataProvider('Product', array(
 'criteria'=>array(
                        'select'=>'name,model,price,brand',
        'condition'=>'category=:category',
                        'params'=>array(':category'=>$id),
    )));
    var_dump($dataProvider);
   return $dataProvider;
   }
CException

Property "CActiveDataProvider.sellerSelectedCategoryProducts" is not defined.

PLEASE HELP! I am losing my mind on this ... not able to display in gridview.

A: Hope this might help
Controller file
public function actionProductcategory($id)
      {
$model=new Product;
$this->render('productcategory',array('model'=>$model,
'id'=>$id));
 }

In View file
'dataProvider'=>$model->SelectedCategoryProducts($id),

UPDATE 1
'columns'=>array(
    'name',
    'model',
    'brand',
    'price',

change them to lowercase which are your original column names

A: Pass $id to your view file.
$this->render('productcategory',array('model'=>$model,'id'=>$id));

Then pass id to model function in ccgridview function.
'dataProvider'=>$model->SelectedCategoryProducts($id),

A:         $dataProvider=new CActiveDataProvider('Product', array(
     'criteria'=>array(
                            'select'=>'name,model,price,brand',
            'condition'=>'category=:category',
                            'params'=>array(':category'=>$id),
        )));

this can retrieve needed data....  first check that data is perfect ... is it right after that take second step....


Q: HyperlinkedRelatedField doesn't work in drf-nested-routers I'm using drf-nested-routers as below
calendar_router = DefaultRouter()
calendar_router.register(r'calendars', views.CalendarViewSet, base_name='calendars')

event_router = routers.NestedSimpleRouter(calendar_router, r'calendars', lookup='calendar')
event_router.register(r'events', views.EventViewSet, base_name='events')

When I add url field to Calendar serializer, it works well, but when add url field to 'Event' serializer, it just raise below exception

Could not resolve URL for hyperlinked relationship using view name
  "event-detail". You may have failed to include the related model in
  your API, or incorrectly configured the lookup_field attribute on
  this field.

A: Replace:
event_router.register(r'events', views.EventViewSet, base_name='events')

with
event_router.register(r'events', views.EventViewSet, base_name='event')


Q: Run Command Prompt Through Python (Or Vice Versa) I found myself doing a repetitive task and wondered how I can automate it.
I can write a function script with python(3), to iterate through each item in a folder, but I'm not sure how I would run that through command prompt.

I have sort of looked into how it would be possible, but I think a direct response to my exact question would be more helpful and easier to grasp.
My question comes more from a desire to learn than it does from laziness!

A: You could use os.system, but subprocess.run is probably better. You should also use glob:
import glob
import subprocess

files = glob.glob('*.wav')

for file in files:
    subprocess.run(['xWMAEncode', file, file.replace('.wav', '.xwm')])


Q: Uncaught TypeError: arr.filter is not a function I have printed arr values in console they are like
[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]

but when this function gives an error i am not getting any values in arr

Uncaught Type Error: arr.filter is not a function

I am new to java-script and i don't have any idea what's this error is
function filter(arr, criteria) {
   return arr.filter(function (obj) {
        return Object.keys(criteria).every(function (c) {
            return obj[c] == criteria[c];
        });
    });
}

A: Seems like the arr you are sending to the filter function is not an array, which is why the error is saying that arr.filter is not a function.
Just tried this and it works, so your function seems ok:
function filter(arr, criteria) {
   return arr.filter(function (obj) {
        return Object.keys(criteria).every(function (c) {
            return obj[c] == criteria[c];
        });
    });
}

const arr = [
  {
    name: "David",
    age: 54
  },
  {
    name: "Andrew",
    age: 32
  },
  {
    name: "Mike",
    age: 54
  }
];
const myFilter = {"age": 54};
const result = filter(arr, myFilter);

console.log(result);


Q: Pyspark - Divide the customers into income buckets How to divide customers into income buckets using pyspark?
Assume I've 2 columns named Customer and Income having range 10K to 50K.
Now I want to Divide the customers into income buckets 10K -20K, 20K-30K etc using pyspark Data frame.
TIA!


Q: How do I improve my RBX.Lua procedural generation code? This is my first post in stack overflow, and I have no clue whether I can post stuff about roblox development here.
But anyways, here I go. I'm making a top-down pixel art survival game, and am procedurally generating "flat" worlds with many different biomes. The code is working fine, it's just that the results look really unnatural, and I don't know what to do about it.
Some examples of what I mean:
world 1, world 2, world 3
Here is my code:
local biomeInfo = require(script.BiomeInfo)

local heightSeed = math.random(-2147483640, 2147483640)
local moistureSeed = math.random(-2147483640, 2147483640)
local heatSeed = math.random(-2147483640, 2147483640)

local mapSize = 250
local resolution = 20
local frequency = 15
local amplitude = 95

-- Generate noise maps
local grid = {}
for x = 1, mapSize do
    grid[x] = {}

    for z = 1, mapSize do
        local heightMap = math.noise(x / resolution * frequency / amplitude, z / resolution * frequency / amplitude, heightSeed)
        local moistureMap = math.noise(x / resolution * frequency / amplitude, z / resolution * frequency / amplitude, moistureSeed)
        local heatMap = math.noise(x / resolution * frequency / amplitude, z / resolution * frequency / amplitude, heatSeed)

        --[[local heightMap = math.noise(x / resolution * 1.2 / 3.2, z / resolution * 1.2 / 3.2, heightSeed)
        local moistureMap = math.noise(x / resolution * 4 / 5.6, z / resolution * 4 / 5.6, moistureSeed)
        local heatMap = math.noise(x / resolution * 2.7 / 7, z / resolution * 2.7 / 7, heatSeed)]]

        grid[x][z] = {
            ["Height"] = math.clamp(heightMap, -0.5, 0.5) + 0.5,
            ["Moisture"] = math.clamp(moistureMap, -0.5, 0.5) + 0.5,
            ["Heat"] = math.clamp(heatMap, -0.5, 0.5) + 0.5,
        }
    end
end

-- Generate blocks
for x = 1, mapSize do
    for z = 1, mapSize do

        -- Get all available biomes for this block
        local availableBiomes = {}
        for name, value in pairs(biomeInfo) do
            local condition = grid[x][z]["Height"] >= biomeInfo[name]["Height"] and grid[x][z]["Moisture"] >= biomeInfo[name]["Moisture"] and grid[x][z]["Heat"] >= biomeInfo[name]["Heat"]
            if condition and not availableBiomes[name] then
                table.insert(availableBiomes, name)
            end
        end

        -- Calculate value differences for all available biomes for this block
        local valueDiffs = {}
        for _, biome in pairs(availableBiomes) do
            valueDiffs[biome] = (grid[x][z]["Height"] - biomeInfo[biome]["Height"]) + (grid[x][z]["Moisture"] - biomeInfo[biome]["Moisture"]) + (grid[x][z]["Heat"] - biomeInfo[biome]["Heat"])
        end

        -- Get the lowest value difference, assign the corresponding biome
        local lowestValue = 1
        local selectedBiome
        for biome, value in pairs(valueDiffs) do
            if value < lowestValue then
                lowestValue = value
                selectedBiome = biome
            end
        end

        -- Generate the block
        local block = Instance.new("Part")
        block.Anchored = true
        block.Size = Vector3.new(8, 8, 8)
        block.Position = Vector3.new(x * 8, 0, z * 8)
        block.Parent = game.Workspace.World
        if grid[x][z]["Height"] <= 0.2 then -- Water level
            block.BrickColor = BrickColor.new("Electric blue")
        elseif selectedBiome == "Grasslands" then
            block.BrickColor = BrickColor.new("Bright green")
        elseif selectedBiome == "Taiga" then
            block.BrickColor = BrickColor.new("Baby blue")
        elseif selectedBiome == "Desert" then
            block.BrickColor = BrickColor.new("Cool yellow")
        elseif selectedBiome == "Swamp" then
            block.BrickColor = BrickColor.new("Slime green")
        elseif selectedBiome == "Mountains" then
            block.BrickColor = BrickColor.new("Dark stone grey")
        elseif selectedBiome == "Jungle" then
            block.BrickColor = BrickColor.new("Earth green")
        elseif selectedBiome == "Snowy tundra" then
            block.BrickColor = BrickColor.new("White")
        else
            block.BrickColor = BrickColor.new("Bright green")
        end

        block.Position = Vector3.new(x * 8, 4.5, z * 8)
        block.Parent = game.Workspace.World
    end
    game:GetService("RunService").Heartbeat:Wait()
end

Note: I'm aware that the many elseif statements is inefficient, this is temporary, please ignore it.
The "BiomeInfo" module script:
return {
    ["Grasslands"] = {
        ["Height"] = 0.27,
        ["Moisture"] = 0.21,
        ["Heat"] = 0.25
    },
    ["Desert"] = {
        ["Height"] = 0.15,
        ["Moisture"] = 0.05,
        ["Heat"] = 0.49
    },
    ["Taiga"] = {
        ["Height"] = 0.28,
        ["Moisture"] = 0.16,
        ["Heat"] = 0.12
    },
    ["Swamp"] = {
        ["Height"] = 0.16,
        ["Moisture"] = 0.44,
        ["Heat"] = 0.14
    },
    ["Mountains"] = {
        ["Height"] = 0.43,
        ["Moisture"] = 0.08,
        ["Heat"] = 0.11
    },
    ["Jungle"] = {
        ["Height"] = 0.22,
        ["Moisture"] = 0.51,
        ["Heat"] = 0.31
    },
    ["Snowy tundra"] = {
        ["Height"] = 0.17,
        ["Moisture"] = 0.12,
        ["Heat"] = 0.03
    },
}

This is my first time working with procedural generation, so I'm not sure if I'm applying the most efficient methods for everything.


Q: How to test select html control object using SpecFlow? I have html select on page:
<select id="StateName" name="StateName">
<option value=""></option>
<option value="value1">value1</option>
<option value="value2">value2</option>
<option value="value3">value3</option>
<option value="value4">value4</option>
<option value="value5">value5</option>
</select>

I've already tried such step definition
[When("I select value \"(.*)\" of select object with id \"(.*)\"")]
public void ThenSelectValueOfSelect(string value, string selectId)
{
   var select = TestsRunner.Browser.GetElementById(selectId);
   select.Click();
   var item = TestsRunner.Browser.GetElementsByTag(@"option").SingleOrDefault(o => o.GetAttribute("value").Equals(value, StringComparison.OrdinalIgnoreCase));
   item.Click();
}

As testsrunner browser I use firefox. The problem is select items are dropped down but concrete option isn't selected.

A: I think it can be done much shorter/easier. The way I'm selecting values from dropdownboxes:
SelectElement dropdown = new SelectElement(Driver.FindElement(By.Id(dropdownID)));
dropdown.SelectByValue(valueToBeSelected);

It's pretty simple and straight forward and it just works.


Q: Creating private reminders using iOS API? Does EKEventStore allow the creation of "private" reminders, i.e. reminders that will be visible only to my app (the one that calls against the EventKit -- iOS events API) but not e.g. to Apple's default reminders app (for either iOS or OS X)?

A: The EKEventStore provides access to the calendar/reminder resources that are available to the OS that are configured by the user.
It is not possible to configure a separate event store for private developer use.
Reminders can be made local so they are not synced in the cloud.
However, if the device has reminder lists that are synced to the cloud, then it is no longer possible to access the local reminders either by your app or the Reminders app.
This same behavior seems to apply to local Calendars where I answered a question about their availability at Local EKCalendar saved with not errors, disappears.
The question at Unable to create local EKCalendar (Reminders) if iCloud is set to not sync Reminders seems to support my conclusions and suggests this behavior has been present for at least a couple of years.


Q: Using "object" of mainfile, in function saved in other file In my work, I am receiving orders in PDF file, while I need to rewrite them into Excel table. Both Excel file and PDF file have every time exact structure, that does not change, so I have decided to automate this process and create python script that will do it for me.
At the moment, I am about to end, I just need to write into excel file last data, but I am having serious issues, so serious, that I might need to rewrite/redesign half of my code (that has about 500 lines atm).
The "problem" is, that I have my code split into 3 files:

*

*main (the one I am executing)

*functions (where all complicated logical functions are stored)

*config (where constants and configuration is stored)

The problem, however is, that I have in main file constructor of xlsxwritter, which creates Excel files and sheets.
Exactly this:
# Creation of new EXCEL file
xlsx_file = 'Red_vyplaty_' + termin_file + '.xlsx'
print 'Creating excel file "%s"' % xlsx_file
excel_file = xlsxwriter.Workbook(xlsx_file)

# Adding sheet, called "Listky_obce_nad_300"
obce_nad_300_sheet = excel_file.add_worksheet('Listky_obce_nad_300')
print 'Adding data sheet "Listky_obce_nad_300" into "%s"' % (xlsx_file)
obce_nad_300_sheet.set_column(0, 0, 2)
obce_nad_300_sheet.set_column(1, 1, 2)

But, I need(or want is more accurate) to create a function, in functions file that will have one imput, and based on this one imput, it will get data from config-constants file, and write them into this sheet(obce_nad_300_sheet).
The problem is, if i create function like:
def create_footer(suma_cell, starting_row, flag):
    """
    Function to creade footer of listok
    flag = 0 / 1 / 2 (data sheet where to write header)
    """
    obce_nad_300_sheet.write(row, 4, 'Test')

it will (obviously) throw exception, that global variable obce_nad_300_sheet does not exist, bla bla bla..im sure you all know it :)
I know, that I have 2 options how to solve it:

*

*Move whole creating and adding and writting into worksheet from main.py, into functions.py

*

*that could do it, but, it would be too much work for me, and most of those new functions will be just calling one xlsxwritter function, so kinda waste of time

*Create these new function in main.py file

*

*while I am not sure if it would work, I am sure, that having some functions in function.py file, and others in main.py file, will be totally ugly and against my rules of clear code.

BUT I would like to have 3rd option, that I am not aware of yet and will be both, simple and "nice"??? :)
PS: No, xlsxWritter is not able to open/read excel file, it can only create new one, so if i define it inside function, it will rewrite everything I have written into file before.

A: I feel that your code is not very well organized. Without entering into too much trouble, I would use obce_nad_300_sheet as an object an move it around. Like this:
def create_footer(sheet, suma_cell, starting_row, flag):
    """
    Function to creade footer of listok
    flag = 0 / 1 / 2 (data sheet where to write header)
    """
    sheet.write(row, 4, 'Test')

I don't know how the library works however. Does it "commit" the changes with a call to write or need some sort of a save or commit method after that?

Without knowing too much about your situation nor the library, I would probably create an object inheriting from xlsxwriter.Workbook, store the sheets in an attribute of that object (probably a dict of {"sheet_name": WorkSheet}) and write the methods in the object. It could look like this:
class MyWorksheet(xlsxwriter.Workbook):

    def __init__(self, *args, **kwargs):
        [...]
        super(MyWorksheet, self).__init__(*args, **kwargs)
        self.sheets = {}
        [...]

    def add_worksheet(self, name):
        [...]
        self.sheets[name] = super(MyWorksheet, self).add_worksheet(name)
        [...]

    def create_footer(self, sheet_name, suma_cell, starting_row, flag):
        [...]
        self.sheets[sheet_name].write(row, 4, "Test")
        [...]

And then in what you call main file do:
my_sheet = MyWorksheet()
my_sheet.add_worksheet("Listky_obce_nad_300")

my_sheet.create_footer("Listky_obce_nad_300", suma, starting, flag)


Q: Deciding which derived class is passed as an argument I'm struggling with my current design and would like to know, if theres a possibility to decide which method to call without using a casting method. Say I've got a base Fence class.
And at the moment my workers know how to build wooden fences and how to build barb wire fences. And they can add two fences together... but up to now they only learned how to connect the wooden ones with wooden ones, and the barb wired ones with barb wired ones.
But as they probably will learn more, the Fence class has a virtual addFence(const Fence& fence) method.
As I wanted to avoid any casting methods, I tried to add special addFence()methods in both classes. Here is an example:
class Fence {
public:
    virtual void addFence(const Fence& fence) = 0;
    ...
};

class BarbWireFence : public Fence {
public:
    ...
    void addFence(const Fence& fence) {
        //only add such a fence, if it is a barb wired one
    }
    void addFence(const BarbWireFence& fence) {
        //continue the fence with the given one
    }
};

class WoodenFence : public Fence {
public:
    ...
    void addFence(const Fence& fence) {
        //only add the fence, if it is a wooden one
    }
    void addFence(const WoodenFence& fence) {
        //continue the fence with the given one
    }
};

Now I would like to do something like
Fence *woodenFence1 = new WoodenFence();
Fence *woodenFence2 = new WoodenFence();
woodenFence1->addFence(*woodenFence2);

But as it is a runtime decision what sort of fence I've got, I only have the base Fence* pointer and therefore the definition of the base class Fence is used in the last line.
So is there a better implementation to decide 'automatically' what sort of fence I've got? Or should I use a completely different design?

A: I'm not aware of a general approach in C++ but assuming you have a fixed set of derived classes, you can actually deal with the situation using an extra indirection:
class BarbWireFence;
class WoodenFence;
class Fence {
public:
    virtual void add(Fence& fence) = 0;
    virtual void add(BarbWireFence& fence) = 0;
    virtual void add(WoodenFence& fence) = 0;
};

class BarbWireFence {
    void add(Fence& fence) override { fence.add(*this); }
    void add(BarbWireFence& fence) override; // deal with the actual addition
    void add(WoodenFence& fence) override;   // deal with the actual addition
};
class WoodenFence {
    void add(Fence& fence) override { fence.add(*this); }
    void add(BarbWireFence& fence) override; // deal with the actual addition
    void add(WoodenFence& fence) override;   // deal with the actual addition
};

A: Welcome to the wonderful world of binary methods.
There is no satisfactory solution to this problem. You may want to learn about double dispatch and its more formal sibling the Visitor pattern. These two things are basically the same, only presented a bit differently. In the most simplistic scenario you do this:
class WoodenFence;
class BarbWireFence;

class Fence {
public:
    virtual void addFence(const Fence& fence) = 0;
    virtual void addMe(BarbWireFence& fence) const = 0;
    virtual void addMe(WoodenFence& fence) const = 0;
    ...
};

class BarbWireFence : public Fence {
public:
    ...
    void addFence(const Fence& fence) {
      fence->addMe(*this);
    }
    void addMe(BarbWireFence& fence) const {
      fence->addBarbWireFence(*this);
    }
    void addMe(WoodenFence& fence) const {
      throw error("bad fence combo");
    }

    void addBarbWireFence(const BarbWireFence& fence) {
      // actually add fence...
    }
};

class WoodenFence : public Fence {
public:
    ...
    void addFence(const Fence& fence) {
      fence->addMe(*this);
    }
    void addMe(BarbWireFence& fence) const {
      throw error("bad fence combo");
    }
    void addMe(WoodenFence& fence) const {
      fence->addWoodenFenceFence(*this);
    }

    void addWoodenFence(const WoodenFence& fence) {
      // actually add fence...
    }

    ...
};

You can figure out what should happen when you add 10 other fence types.
There's a totally different direction one might take, namely, templatize the entire business and get rid of the Fence base class, as it doesn't provide a type-safe interface.
class BarbWireFence {
public:
...
void addSimilarFence(const BarbWireFence& fence) {
    //continue the fence with the given one
    }
};

class WoodenFence {
public:
...
void addSimilarFence(const WoodenFence& fence) {
    //continue the fence with the given one
    }
};

template <typename Fence>
void addFence (Fence& f1, const Fence& f2) {
   f1->addSimilarFence(f2);
}


Q: Custom filename for generated file in Jekyll In my _config.yml file I have defined the permalink like permalink: /posts/:title/ (notice the ending slash).
For a post in _posts/my_first_post/2017-05-06-my_first_post.markdown the generated file is _site/posts/my_first_post/index.html.
How can I change the filename from index.html to something arbitrary like something.htm?
Edit 1:
Didn't want to do this, but I ultimately had to look at the Jekyll source code:
In the lib/jekyll/page.rb there is this:
def destination(dest)
  path = site.in_dest_dir(dest, URL.unescape_path(url))
  path = File.join(path, "index") if url.end_with?("/")
  path << output_ext unless path.end_with? output_ext
  path
end

And in lib/jekyll/document.rb there is this:
def destination(base_directory)
  dest = site.in_dest_dir(base_directory)
  path = site.in_dest_dir(dest, URL.unescape_path(url))
  if url.end_with? "/"
    path = File.join(path, "index.html")
  else
    path << output_ext unless path.end_with? output_ext
  end
  path
end

So the index.html part is hardcoded. This question cannot be answered...unless there is a plugin that does what I want.

A: You can adjust the code of Jekyll to your specific requirement.
Open lib\jekyll\Page.rb in jekyll folder and update the destination method:
module Jekyll
  class Page
    def destination(dest)
      path = site.in_dest_dir(dest, URL.unescape_path(url))
      path = File.join(path, "index") if url.end_with?("/")
      path << output_ext unless path.end_with? output_ext

      # replace index with title
      path.sub! 'index',  data['title'] if data['title']

      path
    end
  end
end

Also update the destination method in lib\jekyll\Document.rb with the same line before returning path

A: Create a plugin and monkey patch those classes

Create _plugins/_my_custom_index.rb
module Jekyll
  class Page
    def destination(dest)
      path = site.in_dest_dir(dest, URL.unescape_path(url))
      path = File.join(path, "index") if url.end_with?("/")
      path << output_ext unless path.end_with? output_ext

      # replace index with title
      path.sub! 'index',  data['title'] if data['title']
      path
    end
  end
end

module Jekyll
  class Document
    def destination(base_directory)
      dest = site.in_dest_dir(base_directory)
      path = site.in_dest_dir(dest, URL.unescape_path(url))
      if url.end_with? "/"
        path = File.join(path, "index.html")
      else
        path << output_ext unless path.end_with? output_ext
      end

      # replace index with title
      path.sub! 'index',  data['title'] if data['title']

      path
    end
  end
end

A: You can change to permalink /posts/:title/:title.html
However, the post will be now accessible via http://server/post/my_first_post/my_first_post.html
If you want to change the default behavior, you should modify Jekyll.Page.destination

A: You can use permalink: /posts/:title/something:output_ext in the _config.yml or in post front matter


Q: struts2 s:property tag: Better way to replace value? I have a POJO whose properties I'm displaying on a JSP using Struts2 property tags:
public Class message
{
    string messageText;
    string messageType;

    //getters and setters, here
}

Text: <s:property value="messageBean.messageText"/>
Type: <s:property value="messageBean.messageType"/>

The object is created either by user input, or reading from a database.  The "messageType" attribute only ever has integer values in it, which are used as keys for a lookup table within the database.
When selecting the "type" values, users are given a radio selection on a previous page, and each option corresponds to an integer.  When I'm displaying the values, I'm currently showing just the integer.  I'd like to show the text that corresponds to the integer, and I would accomplish this by having a key/value lookup method in the action class, and change the code to appear as follows:
//in Action class
public String getTranslatedType()
{
    if (messageBean.getMessageType().equals("12"))
        return "Message for frequent callers.";

    if (messageBean.getMessageType().equals("17"))
        return "Message for first time callers.";
    //etc
}

Text: <s:property value="messageBean.messageText"/>
Type: <s:property value="translatedType"/>

Is there a better way to do this?
This does not seem to work:
Type: <s:property value="Utility.getTranslatedText(messageBean.messageType)"/>

Is there a syntax for calling a static utility method from within the property tag?

A: I'm not sure exactly what you are trying to achieve.  Why would you prefer to use a static call instead of accessing data from the ValueStack (which is where the action properties are accessed from)?  It really is best to avoid static calls if possible and stick to the intended design of the framework and access data from the ValueStack/action.
If you just wish to separate the logic from your action, you could change your method to:
public String getTranslatedType() {
   return Utility.getTranslatedText(getMessageBean().getMessageType());
}

Or are you wishing to have the translated text appear on the page dynamically?  If so, perhaps you could use Javascript and JSON to achieve your goal with something along the lines of the following steps:

*

*Place your messageType integers (as the keys) and your translatedText Strings (as the values) into a map along the lines of messageTypeText.put(12, "Message for frequent callers.");

*Convert this to JSON using something like (new JSONObject(messageTypeText)).toString();

*Then expose this to the client by any of a number of ways such as var messageTypeText = <s:property value="messageTypeText"/>;

*Bind a javascript method to the messageType radio button that then displays the translated text by accessing it from the javascript map/array using the value of the currently selected radio/messageType.  I could give more detail on this approach, but I don't want to waste my time if its not what you're looking for!  :)


Q: How to disable zuul decoding encoded slash %2F? I'm using a solution with Spring Cloud Zuul and Eureka. The REST application register itself with Eureka and Zuul provide access to the Service via Eureka Service Discovery.
I had to configure the REST application to accept encoded slash in URL with:
System.setProperty("org.apache.tomcat.util.buf.UDecoder.ALLOW_ENCODED_SLASH", "true");

To accept encoded dash in the Spring Boot REST application, and:
@Bean
public HttpFirewall allowUrlEncodedSlashHttpFirewall() {
    DefaultHttpFirewall firewall = new DefaultHttpFirewall();
    firewall.setAllowUrlEncodedSlash(true);
    return firewall;
}

@Override
public void configure(WebSecurity web) throws Exception {
    web.httpFirewall(allowUrlEncodedSlashHttpFirewall());
}

In WebSecurityConfigurerAdapter for the same purpose. And:
@Override
public void configurePathMatch(PathMatchConfigurer configurer) {
    UrlPathHelper urlPathHelper = new UrlPathHelper();
    urlPathHelper.setUrlDecode(false);
    configurer.setUrlPathHelper(urlPathHelper);
}

In WebMvcConfigurer to skip decoding url encoded characters.
After that, the REST application alone started to answer normally the request with the encoded slash. When I connected the REST application with Zuul, the gateway, the problem happened with slash encoded happens again. I did the same configuration of REST application with Zuul plus the property decode-url: false in application.yml and the combination of Zuul and REST application worked again.
When I added the Service Discovery/Service Registration solution with Eureka, the problem begun happen again. I searched a lot, even cloned the Spring Cloud Netflix Eureka Server 2.1.0.RELEASE and Eureka Core 1.9.8 but couldn't find any solution.
How to disable the decoding of slash in Eureka encoded in URL?

A: The solution is to change Spring Boot version from 2.1.3.RELEASE to 2.1.4.RELEASE in the gateway.