text:
Q: react-js based web page crashes when refreshing the page I am using Reactjs, redux, webpack and webpack server to develop a website.
The website crashes when I refresh a certain pages. To be more specific when I visit   http://localhost:8080/article/Id   the page works like a charm, but when I hit refresh the page turns to white with errors.
GET http://localhost:8080/article/scripts/vendor.bundle.js?cfd99d78961c5e13afca 404 (Not Found)
Refused to execute script from 'http://localhost:8080/article/scripts/vendor.bundle.js?cfd99d78961c5e13afca' because its MIME type ('text/html') is not executable, and strict MIME type checking is enabled.

The error displayed by Chrome is this and this.
My webpack config page looks like this :

//webpack.config.js

var webpack = require('webpack')
var HtmlWebpackPlugin = require('html-webpack-plugin')
var ExtractTextPlugin = require('extract-text-webpack-plugin')
var UglifyJsPlugin = require('uglifyjs-webpack-plugin')
var path = require('path')

var isProd = process.env.NODE_ENV === 'production'
var cssDev = ['style-loader', 'css-loader', 'sass-loader']
var cssProd = ExtractTextPlugin.extract({
    use: [{
            loader: 'css-loader',
            options: {
                minimize: 'true'
            }
        },
        {
            loader: 'sass-loader'
        }
    ],
    fallback: 'style-loader',
    publicPath: '/docs'
})
var cssConfig = isProd ? cssProd : cssDev

module.exports = {
    entry: {
        'app': './src/app.js',
        'vendor': './src/vendor.js'
    },
    output: {
        path: path.resolve(__dirname, 'docs'),
        filename: 'scripts/[name].bundle.js'
    },
    module: {
        rules: [{
                test: /\.jsx?/,
                exclude: [/node_modules/, path.resolve(__dirname, './src/lib')],
                use: 'babel-loader',
            },
            {
                test: /\.(png|jpe?g|gif|svg|woff|woff2|ttf|eot|ico)$/,
                loader: 'file-loader?name=assets/[name].[hash].[ext]'
              },
            {
                test: /\.s?css$/,
                use: cssConfig
            },
            {
                test: /\.(jpe?g|png|gif|svg)$/i,
                use: [
                    'file-loader?name=images/[name].[ext]',
                    'image-webpack-loader'
                ]
            },
            {
                test: /\.(xml|json|ico)$/i,
                use: [
                    'file-loader?name=images/[name].[ext]',
                ]
            }
        ]
    },
    devServer: {
        contentBase: path.join(__dirname, 'docs'),
        compress: true,
        hot: true,
        stats: 'errors-only',
        open: true,
        disableHostCheck: true,
        historyApiFallback: true, //when refreshing
        inline: true //reloads the entire browser page
    },
    plugins: [
        new ExtractTextPlugin({
            filename: 'styles/[name].bundle.css',
            disable: !isProd,
            allChunks: true
        }),
        new HtmlWebpackPlugin({
            title: 'React MovieDB - Powered by The Movie Database',
            minify: {
                collapseWhitespace: true
            },
            hash: true,
            template: './src/index.ejs'
        }),
        new webpack.HotModuleReplacementPlugin(),
        new webpack.NamedModulesPlugin(),
        new UglifyJsPlugin()
    ],
    watch : true
}

And I run the project with : "dev": "webpack-dev-server",
And this how my index.ejs looks like:

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <link rel="apple-touch-icon" sizes="180x180" href="<%= require('./icons/apple-touch-icon.png') %>">
    <link rel="icon" type="image/png" sizes="32x32" href="<%= require('./icons/taleed.png') %>">
    <link rel="icon" type="image/png" sizes="16x16" href="<%= require('./icons/taleed.png') %>">
    <link rel="manifest" href="<%= require('./icons/manifest.json') %>">
    <link rel="mask-icon" href="<%= require('./icons/safari-pinned-tab.svg') %>" color="#01d277">

    <meta name="theme-color" content="#ffffff">
    <title>
        Archive Search Engine
    </title>

Honestly, I can't manage to figure out the main source of the problem because the project is based on a template and I couldn't get in touch with the template' maker.

A: You're trying to grab the bundle from the base path, which works just fine. But when you go to a different part of the app, you are requesting to get the bundle from /articles/app.bundle.... So you need to change the index file to pull from the absolute path from the server for the bundle instead of a relative path.
You need to do something like this to your server.js (if you use node);
app.get('/*', (req, res) => {
    res.send(template({
        css: bundle.css,
        js: bundle.js,
    }));
});

for example on using mustache as the template engine.


text:
Q: Custom fields in fb:request form with FBML on iframes I'm converting my FBML app to iframe and I want to pass custom fields by setting fb_protected=true. It used to work on FBML apps. But doesn't work when using the FBML tags in iframe. Any pointers ?

A: You can use this too

and/or

A: for rendering fbml tags you need to import fb js , that is

that div tag is reqiured else it will throw an error.
And use FB.XFBML.parse(); to render your fbml.

redpajama_set_name: RedPajamaStackExchange


text:
Q: My jQueryMobile Datepicker works in google chrome but not on my phonegap mobile application I am currently trying to implement the jQueryMobile Datepicker (calbox) from http://dev.jtsage.com/jQM-DateBox2/ into my phonegap mobile application for android.
The script tags which reference the various different jquery and jqueryMobile files located within my project look like the following:
<link rel="stylesheet" href="css/themes/default/jquery.mobile-1.2.0.css">
    <link rel="stylesheet" href="css/main.css">
    <script src="js/jquery-1.10.2"></script>
    <script src="js/jquery.mobile-1.2.0.js"></script>
    <script src="cordova-2.7.0.js"></script>
    <script src="js/mustache.js"></script>
    <link rel="stylesheet" type="text/css" href="http://code.jquery.com/mobile/latest/jquery.mobile.min.css" />
<link rel="stylesheet" type="text/css" href="http://dev.jtsage.com/cdn/datebox/latest/jqm-datebox.min.css" />
    <script src="js/jqm-datebox-1.1.0.comp.calbox"></script>
    <script src="js/jqm-datebox.mode.calbox.min"></script>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
<script type="text/javascript" src="http://code.jquery.com/mobile/latest/jquery.mobile.min.js"></script>
<script type="text/javascript" src="http://dev.jtsage.com/cdn/datebox/latest/jqm-datebox.core.min.js"></script>
<script type="text/javascript" src="http://dev.jtsage.com/cdn/datebox/latest/jqm-datebox.mode.calbox.min.js"></script>
<script type="text/javascript" src="http://dev.jtsage.com/cdn/datebox/i18n/jquery.mobile.datebox.i18n.en_US.utf8.js"></script>

Then within a form tag within my html file I implemented the datepicker as follows:
<label for="mydate">Select Covering Date:</label>

<input name="mydate" id="mydate" type="date" data-role="datebox" data-options='{"mode": "calbox", "calShowWeek": true}'>

The datepicker works when I view the particular html file it is implemented in on Google Chrome, however when I run my project via my android device, the datepicker seems to operate as a textfield and no calendar is shown.
Any help in fixing this problem would be greatly appreciated, thank you!

A: 1) Check the js loading order. First jQuery, jQueryMobile and then date-picker.
2) Looks like there are some duplicated js files included. For example jquery-1.7.1.min.js and query-1.10.2. Similary for jquery mobile.


text:
Q: how to perform a jquery calculation on the dynamically generated textbox by ajax hi i have a form which dynamically generates fields when i select a value from a combo box with the value associated with the combo box value the problem is i have a jquery calculation function too which will calculate percentage  from  the textbox generated by ajax. can any one help me in this here is my ajax file
<?php
session_start();
require("includes/dbconnect.php");
require("includes/function.php");
$zdb = $_SESSION["zdbyear"];
mysql_select_db($zdb);
$code = $_GET["code"];
$ztit = $_SESSION["tit"];
//browse($code);
$result = mysql_query("SELECT * FROM `loctype` WHERE code='".$code."'") or die(mysql_error());
require("includes/dbconnect.php");
$getcomp = mysql_query("SELECT * FROM `compyear` WHERE finyear='".$ztit."'") or die(mysql_error());
$st = mysql_fetch_array($getcomp);

  $row = mysql_fetch_array($result);
  echo "
";
  echo "
";
  echo ' Deposit <input type="text" size="20"  maxlength="40" name="deposit" value="'.$row["deposit"].'" class="qty form-input-rate" text-align:left ;  />	';
  echo ' Rent <input type="text" id="rent" size="20" maxlength="40" name="rent" value="'.$row["rent"].'" class="form-input-rate"  />	';
  echo ' S.T <input type="text" id="stperc" size="5"  maxlength="40" name="servtax" style="width: 50px;" value="'.$st["stperc"].'" class="form-input-rate" text-align:left ;  />%	';
  echo '
';
  echo '
';
    echo ' S.T <input type="text" size="20"  maxlength="40" id="stamt" name="stamt" value="" class="form-input-rate" text-align:left ;  />	';
    echo ' Amount<input type="text" size="20" maxlength="40" id="totamt" name="totamt" value="" class="form-input-rate"  readonly/>	';

  echo '
';
  echo "
";
}
?>

here is my jquery calculation part
$(document).ready(function () {
    $("#stperc").keyup(function () {
        alert($("#stperc").val());
        var value = $("#stperc").val();
        var value2 = $("#rent").val();
        $('#stamt').val((value * value2) / 100).toFixed(2);
    });
    $("#stperc").blur(function () {
        var val = parseInt($("#rent").val());
        $('#totamt').val(val + Number($("#stamt").val())).toFixed(2);
    });
});

A: Use delegation:
$("#some_table_id").on('keyup', '#stperc', function(){
  // do it here
});

Similarly you can delegate blur event
$("#some_table_id").on('blur', '#stperc', function(){
  // do it here
});

Give an id to the table in your html code so that the action can be executed on any inputs added in that table (some_table_id is the dummy id I use)
echo "
";

A: The events might not be triggered because they are created before the #stperc is in the DOM. You could bind this to document like this:
$(document).on({
   "keyup":function() {
      alert($(this).val());
      var value = $(this).val();
      var value2 = $("#rent").val();
      $('#stamt').val((value * value2) / 100).toFixed(2);
  },
 "blur":function() {
      var val = parseInt($("#rent").val());
      $('#totamt').val(val + Number($("#stamt").val())).toFixed(2);
 }
},"#stperc");

Since you're adding these events to the same element, you could queue it up together.
I also changed #stperc inside the keyup event to $(this).
Here's a demo at jsFiddle
Alternatively, you could bind these events to the parent of table. You can't use table as a parent here because
 is also dynamic. For more info, see on()


text:
Q: Past or Present form of the verb when using "Hypothetically speaking" in sentence? When making a hypothetical statement, do I have to use the past form of verbs or the present form in the main clause?
For example,

Hypothetically speaking, if I finish my homework by dinner, I will be able to ~.
  Hypothetically speaking, if I finished my homework by dinner, I would be able to ~.

Are they both correct in different situations?

A: The phrase hypothetically speaking is used to refer to a hypothesis. Both conditional sentences you provide can be considered to be a hypothesis in the form of if.../then... They both "predict"  that if one thing  happens,  then something else happens.

1 Hypothetically speaking, if I finish my homework by dinner, (then) I will be able to watch TV.
2 Hypothetically speaking, if I finished my homework by dinner, (then) I would  be able to watch TV.

The difference in the two sentences  is that the first is a real conditional  and the second is an unreal conditional. In unreal conditional sentences, the if-clause uses a past tense form, and a modal in the main clause.
These two terms reflect the speaker's attitude. The real conditional does not specify any particular attitude. Thus the speaker leaves open the possibility that the proposition may come true. Sometimes this kind of conditional is called an open conditional. The unreal conditional expresses that the speaker has some doubt about the proposition. In the unreal conditional (If I finished..., then I would be able...) indicates that the speaker has some doubt (is not sure) that he can finish his homework. (This explanation of real versus unreal is  based on The English Verb (2nd edition), upon which this answer is heavily dependent).
Let's look at another example of real versus unreal:

3 Hypothetically speaking, if  Donald Trump is elected president, (then) will you be happy?
4 Hypothetically speaking, if Donald Trump were elected president, (then) would you be happy?

In the real conditional (sentence 3) the sentence does not comment upon the speaker's attitude toward the truth of the hypothesis. In the unreal conditional (4),the speaker indicates some doubt that Trump will become president and thus uses the past tense form in the if-clause and a modal (here, would) in the main clause.
Not all conditional sentences are hypothetical or predictive. Some refer to one thing that can be inferred from another thing. One example of this is a 'past real' conditional.

If I finished my homework by dinner, (then) I was able to watch TV.

Here the truth of one proposition (I was able to watch TV) is inferred from the truth of the other (I finished my homework by dinner).
So, hypothetically speaking wouldn't be appropriate here, since there is no prediction involved.
Of course English speakers are free to stick the two words hypothetically speaking before any sentence,  and it doesn't  have to equate with the grammatical explanation I've used here.
Hypothetically speaking I want to move to California does not express a  hypothesis in the sense used in this answer.


text:
Q: Restricting php endpoints with AWS apigateway I have backend API written in the laravel framework. Every client request goes through a single AWS api-gateway. This gateway only verifies the users identity(authenticates) and proxies it to the php backend API. Gateway does not have API for each resources like user, product, order etc. I have two types of users in AWS user pool. Admin and normal users. Now, I want to restrict certain php API endpoints (edit, delete) to the non admin users.
One way of doing this is to maintain the user information with their role and permission in the database and handle logic in the php code itself. While I am reading AWS documentation, it says it can control the access to the API. As I have already mentioned I don't have separate api-gateway for each resources, I don't know if it is possible to control access in the gateway itself. Can somebody help me which approach should i use. Is maintaining RBAC logic in the php code the right approach or just overkill.

A: Simplest way might be to go with standard IAM roles and policies: https://docs.aws.amazon.com/apigateway/latest/developerguide/permissions.html

To allow an API caller to invoke the API or refresh its caching, you must create IAM policies that permit a specified API caller to invoke the API method for which the IAM user authentication is enabled. The API developer sets the method's authorizationType property to AWS_IAM to require that the caller submit the IAM user's access keys to be authenticated. Then, you attach the policy to an IAM user representing the API caller, to an IAM group containing the user, or to an IAM role assumed by the user.

You can find more information in the official documentation, but here is an IAM policy example:
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Permission",
      "Action": [
        "execute-api:Execution-operation"
      ],
      "Resource": [
        "arn:aws:execute-api:region:account-id:api-id/stage/METHOD_HTTP_VERB/Resource-path"
      ]
    }
  ]
}


text:
Q: Android: odd response, possible redirect from PHP login So this is a follow up to this post. I've tested the code in that post on other websites and I get valid responses and successful log ins. However on this site I get back what looks like a redirect. Here is the php file I'm trying to access.
<?php
session_start();
error_reporting(E_ALL^ E_NOTICE);
//include the connection and variable defination page
include("include/server.php");
include("include/function.php");
//checking the form has been submit by user or not
if(isset($_POST['cmdSubmit']) and $_POST['cmdSubmit']="Login")
{
//$refLink  = $_SERVER['HTTP_REFERER'];
$refLink    = "index.php?err_msg=1";
$user = addslashes($_POST['username']);
$pass = addslashes($_POST['password']);
$remember = $_POST['remember'];

$strErrorMessage = "";
if($user==""){
    $strErrorMessage = "User Name can not be blank";
}
if($pass==""){
    $strErrorMessage = "Password can not be blank";
}
if($user=="" and $pass==""){
    $strErrorMessage = "User Name and Password can not be blank";
}

if($strErrorMessage=="")
{

    if(isset($_POST['remember'])){
        //removing all the cookie at set the user name password in cookies
        unset($_COOKIE[session_name()]);
        setcookie("usernamex", $_POST['username'], time()+60*60*24*100);
        setcookie("userpassx", $_POST['password'], time()+60*60*24*100);
        setcookie("rememberx", $_POST['remember'], time()+60*60*24*100);
    }else{
        if(isset($_COOKIE['rememberx']) && isset($_COOKIE['usernamex']) && isset($_COOKIE['userpassx']))
        {
            unset($_COOKIE[session_name()]);
            setcookie("usernamex", $_POST['username'], time());
            setcookie("userpassx", $_POST['password'], time());
            setcookie("rememberx", $_POST['remember'], time());
        }
    }

    $sqlLogin   = "select * from member_mast where username = '".$user."' and password = '".$pass."' and is_deleted_flg=0 and is_profile=0";
    $queryLogin = mysql_query($sqlLogin) or die(mysql_error()." Please check the Query");
    $totLogin   = mysql_num_rows($queryLogin);

    //here checking the user is authorized or not
    if($totLogin>0)
    {
        $rsLogin                = mysql_fetch_array($queryLogin);
        $_SESSION['uid']        = trim($rsLogin['username']);
        $_SESSION['memberid']       = trim($rsLogin['user_id']);
        $_SESSION['userType'] = trim($rsLogin['member_role']);

        if(isset($_POST["page"]) and trim($_POST["page"])!="")
        {
            $pageName       = trim($_POST["page"]);
            $pagepassId     = trim($_POST["pageid"]);
            $redirect_url   = "http://www.fakesite.com/fspv2/welcome.php?page=".$pageName."&pageid=".$pagepassId;
        }
        else
        {
            //$redirect_url = "http://www.fakesite.com/fspv2/welcome.php";
            //$redirect_url = "welcome.php";
            $redirect_url   = "welcome.php";
        }
//header("Location: ".$redirect_url);
?>
        <script>window.location.href="<?php echo $redirect_url; ?>";</script>
      <!--  <meta http-equiv="refresh" content="0;url=<?php echo $redirect_url; ?>">    -->
<?php
}
else
{
        $displayMessage = "Login failed. If you are authorized, try again";
        session_destroy();
        $state = "inv";
        $_SESSION['username'] = $_POST['username'];
        $_SESSION['password'] = $_POST['pass'];
        $username = $_SESSION['username'];
        $password = $_SESSION['password'];
    ?>
        <script>window.location.href="<?php echo $refLink; ?>";</script>
    <?php
    }
}
else
{
    $state = "inv";
    $_SESSION['username'] = $_POST['userid'];
    $_SESSION['password'] = $_POST['pass'];
    $username = $_SESSION['username'];
    $password = $_SESSION['password'];
    $displayMessage = $strErrorMessage;
?>
    <script>window.location.href="<?php echo $refLink; ?>";</script>
<?php
}
}
 //header("Location: ".$refLink);
?>
<!--<script>window.location.href="<?php echo $refLink; ?>";</script>--> <!-- <meta http-equiv="refresh" content="0;url=<?php echo $refLink; ?>">  -->

Now when I connect to this login.php it doesnt matter if the username/pw is valid or not. The only response I get is this
05-18 17:08:50.160: V/RESPONSE(30797):  <!--<script>window.location.href="";</script>-->       <!-- <meta http-equiv="refresh" content="0;url=">                -->

Which looks as though it's javascript attempting to redirect me because it's a mobile device. The only redirect I can find in there is to redirect the client to the "welcome.php" which would be if they successfully logged in. I've gone through the files on the site and there does not appear to be a mobile login.php (i may be wrong). It should be noted I did not design the site I'm trying to log into and the site is operational and users can log in from this php file from their browser. I also have access to all the files. *My question is why isn't this php file allowing me to login via my android app and instead giving me this odd response? * If you need to see any other code please just ask. Thanks!

A: Where the javascript is coming from is easy to answer:
?>
<!--<script>window.location.href="<?php echo $refLink; ?>";</script>--> <!-- <meta http-equiv="refresh" content="0;url=<?php echo $refLink; ?>">  -->

After your PHP tag ends, there is additional text. Namely the javascript. If you don't want that in the response, you'll need to remove it from the PHP file or put in a PHP if condition to make it only displayed in some contexts.
As far as you Android code goes, you need to add
nameValuePairs.add(new BasicNameValuePair("cmdSubmit", "Login"));

Otherwise your first if (PHP) clause is false.


text:
Q: How do I find nodes with whitespace at the end and get line position? How can I search a xml file for whitespace just before the close tag of any tag and get its actual position using (IXmlLineInfo)'s LinePosition property
For example in case of the below xml file
<?xml version="1.0" encoding="utf-8"?>
<main>
    <child1>anything</child1>
    <child2>whatever </child1>
    <pp>
        <ccl>i dont know</ccl>
        <ccp>1253 </ccp>
    </pp>
</main>

The output should be like
Whitespace found at position 4,19
Whitespace found at position 7,14

What is the easiest way of doing this using XDocument?

A: First task is to find all nodes that ends with a space, then get the line info by casting them to IXmlLineInfo, assuming document is the XDocument:
document.Descendants()
        .Where(node => ((string)node).EndsWith(" "))
        .Select(node => node as IXmlLineInfo);

This will give you the line infos that contain line number and position of the node. If you want the find line position of the space, you will need to do some calculation on this value, i.e. add the length of the node's value to line position, you will get the position of the whitespace. Also you might need to add the lenght of node's name including opening and closing tags to find exact position.


text:
Q: How to modify the real value with a multiply operation A simple question :
1) In Python using numpy, how to get without parisitic decimals the follwing result (true value 0.6968) ? :
>>> 0.67*(1.04)
0.6968000000000001

If I convert to string, I can find the right value :
>>> str(0.67*(1.04))
'0.6968'

2) By the way, how to control the rounding to systematically get the real value ? I saw that epsilon machine with Python (and/or Numpy) was around 2e-16.
So, I conclude that taking 16 decimals is too small and implies random values after 16th decimal or more precisely below 2e-16.
I don't want to troll but Matlab (I like also Python) doesn't produce this kind of error.

A: use %g for that.
x = 0.67*(1.04)
x = '%g'%(x)
print("x:",x)

your question is duplicate of this post.


text:
Q: DCOM configuration for Win 10 Where can I find up-to-date information on configuring remote DCOM access on a modern Windows 10 Pro or Enterprise system? The last time I did this was for Windows 7 and I dare say that a lot has changed. Searching online for information turns up a great many obsolete articles and books.
Under Windows 7 I had managed to do it for a Linux Java program using the old j-interop library, supplying the account name, password and Class ID. Since it is so old, j-interop uses only the NTLMv1 and v2 protocols. I'd like to make this combination work again for Windows 10. In a general way I recall that you have to make firewall rules exposing a port-mapper port and the ports it may open. Then you have use DCOM configuration to allow your account access to the particular server. But I don't know how to do those things now and don't know what else may be required.

A: Well, in the end the answer turned out to be "Don't do it that way!". I ended up writing a web server to read the data using local OPC DA and then export it via HTTP. Basically Python Bottle + OpenOPC. A commercial OPC UA gateway with local OPC DA capablility would also have worked.


text:
Q: How to read and split comma separated file in a bash shell script? I want to read a file line by line, split each line by comma (,) and store the result in an array. How to do this in a bash shell script?
Sample line in my comma separated file
123,2014-07-21 10:01:44,123|8119|769.00||456|S

This should be the output after splitting:
arr[0]=123 arr[1]=2014-07-21 10:01:44 arr[2]=123|8119|769.00||456|S

A: Use read -a to split each line read into array based from IFS.
while IFS=, read -ra arr; do
    ## Do something with ${arr0]}, ${arr[1]} and ${arr[2]}
    ...
done < file

If the third field can also contain commas, you can prevent it from being split by using finite non-array parameters:
while IFS=, read -r a b c; do
    ## Do something with $a, $b and $c
    ...
done < file

From help read:

Reads a single line from the standard input, or from file descriptor FD
if the -u option is supplied.  The line is split into fields as with word
splitting, and the first word is assigned to the first NAME, the second
word to the second NAME, and so on, with any leftover words assigned to
the last NAME.  Only the characters found in $IFS are recognized as word
delimiters.

  -a array  assign the words read to sequential indices of the array
            variable ARRAY, starting at zero


text:
Q: Count the amount of numbers that are length of 5 and has exactly two repeating numbers I'm trying to count the amount of numbers that are length of 5 and has exactly two repeating numbers (where zero can be leading like 00123). What I did:
def checkNumber(num):
    temp = [0] * 10
    for d in map(int, str(num)):
        temp[d] += 1
    contains_two_unique_digits = False
    for d in temp:
        if d > 2:
            return False
        if d == 2:
            if contains_two_unique_digits:
                return False
            contains_two_unique_digits = True
    return True

counter = 0
for num in range(10000,100000):
    counter += checkNumber(num)
print(counter)

But of course it does not count the cases with a leading zeros. How can I add them here? Python does not allow 001234 numbers.

A: The zfill method of the str type might be of help.
>>> "123".zfill(5)
'00123'
>>> "123456789".zfill(5)
'123456789'

To convert an int to a str, simply use str:
>>> str(123)
'123'

A: If you NEED to accept integers in python, then you are correct that no solution can be made. If you can accept a string and treat the values inside as integers, then you can definitely make it happen. A integer or float with leading zeros will always cause an error in Python.
def checkNumber(string_input):
    # is it a string?
    if not isinstance(string_input, str):
        string_input = str(string_input)
    # does it have five characters?
    if not len(string_input) == 5:
        raise ValueError('You must enter a string of length 5.')

    counter_list = [0] * 10
    # iterate over the string and count how many of each integer we have
    for value in string_input:
        if value.isdigit():
            counter_list[int(value)] += 1

    # check to see if any of them have identically two
    for value_count in counter_list:
        if value_count == 2:
            return True
    return False

print(checkNumber('01234'))

A: If you want to iterate over numbers by their digit representation, then itertool.product() will likely be more useful. itertools.product(string.digits, repeat=5) will yield each of the numbers you need, as digit tuples.
Taking advantage of collections.Counter can also help here, and avoids the flag / loop logic.
from collections import Counter
from itertools import product
from typing import Tuple
import string

def has_two_repeats(digits: Tuple[str, ...]):
    counts = Counter(digits).values()
    return (
        # no digits occur more than 2 times
        sum(count > 2 for count in counts) == 0 and
        # one digit occcurs two times
        sum(count == 2 for count in counts) == 1
    )

def all_two_repeats_five_digits() -> int:
    return sum(
        has_two_repeats(digits)
        for digits in product(string.digits, repeat=5)
    )

print(all_two_repeats_five_digits())


text:
Q: Why WNetOpenEnum gets ERROR_INVALID_ADDRESS (487) result? trying to rewrite using WINAPI library https://learn.microsoft.com/en-us/windows/win32/wnet/enumerating-network-resources on Rust
let dw_result: DWORD;
let mut h_enum: LPHANDLE = null_mut();
let mut lpnr_local: LPNETRESOURCEW = null_mut();

dw_result = WNetOpenEnumW(RESOURCE_GLOBALNET, // all network resources
                          RESOURCETYPE_ANY,   // all resources
                          0,  // enumerate all resources
                          lpnr_local,       // NULL first time the function is called
                          h_enum);
if dw_result != WN_NO_ERROR {
     println!("WnetOpenEnum failed with error {:?}\n", dw_result);
}

But this code assign 487 into dw_result which means ERROR_INVALID_ADDRESS
And I can't get what is wrong

A: I guess your doubt is the difference between LPHANDLE and HANDLE.

LP stands for Long Pointer. It's a pointer to a handle.

If you want to use LPHANDLE, please give it a legal address。
Like this:(C++)
HANDLE ph;
LPHANDLE hEnum = &ph;

Or simply use HANDLE.
let mut h_enum: HANDLE;
...
dw_result = WNetOpenEnumW(RESOURCE_GLOBALNET, // all network resources
                      RESOURCETYPE_ANY,   // all resources
                      0,  // enumerate all resources
                      lpnr_local,       // NULL first time the function is called
                      &h_enum);

Related: LPHANDLE vs. HANDLE


text:
Q: recursively sort a vector in R I have a task like
n <- 5
set.seed(11)
X <- rnorm(n)

X.sort <- {}
for(i in 1:n){
  X.sort <- sort.int(c(X.sort, X[i]), decreasing = TRUE)
  print(X.sort) # actually, other computations with X.sort
}

resulting in output of the sort of
[1] -0.5910311
[1]  0.02659437 -0.59103110
[1]  0.02659437 -0.59103110 -1.51655310
[1]  0.02659437 -0.59103110 -1.36265335 -1.51655310
[1]  1.17848916  0.02659437 -0.59103110 -1.36265335 -1.51655310

It strikes me as inefficient to "re-sort" X.sort in each round of the loop, when the vector is already sorted except for the new entry X[i] that is to be inserted.
I have tried "telling" R where to insert the element via
library(R.utils)

X.sort <- {}
for(i in 1:n){
  pos <- match(F, X.sort>X[i])
  if(is.na(pos)){
    X.sort <- c(X.sort,X[i])
  } else {
    X.sort <- insert(X.sort, pos, X[i])
  }
  print(X.sort)
}

but that does not yield any gains when benchmarking.
Is there an obvious improvement, or does R already efficiently exploit the knowledge that X.sort is sorted?
EDIT:
Benchmarking suggests [BUT PLEASE ALSO CONSIDER THE REPLIES BELOW] the accepted answer to be quickest (at least when n gets close to 1,000), which moreover appears to also work for large n, and to be the simplest one.
library(R.utils)
library(microbenchmark)
n <- 600
set.seed(11)
X <- rnorm(n)

sorted_insert <- function(x, y) {
  c(x[x >= y], y, x[x < y])
}

recursive_fun <- function(ans=list(NULL), vec, i=1) {
  if (i > length(vec)) {
    tail(ans, -1)
  } else {
    ans <- c(ans, list(sorted_insert(ans[[i]], vec[i])))
    recursive_fun(ans=ans, vec, i=i+1)
  }
}

microbenchmark(
  {
    X.sort <- {}
    for(i in 1:n){
      X.sort <- sort.int(c(X.sort, X[i]), decreasing = TRUE)
    }
  },{
    X.sort <- {}
    for(i in 1:n){
      pos <- match(F, X.sort>X[i])
      if(is.na(pos)){
        X.sort <- c(X.sort,X[i])
      } else {
        X.sort <- insert(X.sort, pos, X[i])
      }
    }
    },{
    X.sort <- {X[1]}
    for(i in 2:n){
      X.sort <- append(X.sort, X[i], after = sum(X.sort > X[i]))
    }
  },{
    lapply(seq_along(X), function(a) {sort(X[seq_len(a)], decreasing = T)})
  },{
    lapply(1:length(X), function(i) sort(X[1:i], decreasing = T))
  },
  {
    recursive_fun(vec=X)
  },
  times=50
)

Result:
       min        lq      mean    median        uq       max neval
 21.308012 22.264314 24.065012 22.798643 26.381362 34.629395    50
 19.554413 20.334643 21.875769 20.617807 24.085896 30.625841    50
  4.497919  4.804550  5.380192  4.912923  5.114310 13.522485    50
 23.540616 24.105807 25.311692 24.335780 24.985024 30.348792    50
 23.251905 24.067122 25.722031 24.745380 27.986197 30.010018    50
  3.928746  4.096568  4.358911  4.258701  4.390684  9.106202    50

A: The bottleneck in your code is actually the print statement.
Here is another way that is about 5x faster (if you do not need to print) :
n <- 10000
set.seed(11)
X <- rnorm(n)

X.sort <- {X[1]}
for(i in 2:n){
  X.sort <- append(X.sort, X[i], after = sum(X.sort > X[i]))
}

A: You could try this recursive approach
The working function is sorted_insert, which inserts the new-element at the vector position between elements >= new-element, vec[vec >= y], and < new-element, vec[vec < y]. This assumes that the vector is always sorted (which is true in this case).
sorted_insert <- function(x, y) {
    c(x[x >= y], y, x[x < y])
}

sorted_function is called recursively by recursive_fun. If the counter i is <= the length of the vector (i.e. the entire unsorted-input-vector has not been traversed) then it will call sorted_function using the previous sorted-answer, ans[[i]] as the input-vector and vec[i] as the new-element to insert. That is, the sorted-vector at each iteration is built up using the sorted-vector from the previous iteration and a new element from the unsorted-input-vector. Sorry, tried my best to explain it.
recursive_fun <- function(ans=list(NULL), vec, i=1) {
    if (i > length(vec)) {
        tail(ans, -1)
    } else {
        ans <- c(ans, list(sorted_insert(ans[[i]], vec[i])))
        recursive_fun(ans=ans, vec, i=i+1)
    }
}

Using the given example
n <- 5
set.seed(11)
X <- rnorm(n)
recursive_fun(vec=X)

A larger example
n <- 1000
set.seed(11)
X <- rnorm(n)
recursive_fun(vec=X)

There is a problem if your unsorted-input-vector is large
n <- 10000
set.seed(11)
X <- rnorm(n)
recursive_fun(vec=X)
# Error: evaluation nested too deeply: infinite recursion / options(expressions=)?

Note that if you do not want to collect the result at each iteration, you can use Reduce(sorted_insert, X), which should be fast.

A: Here's a way with lapply -
n <- 5
set.seed(11)
x <- rnorm(n)

lapply(seq_along(x), function(a) {
  sort(x[seq_len(a)], decreasing = T)
})

[[1]]
[1] -0.5910311

[[2]]
[1]  0.02659437 -0.59103110

[[3]]
[1]  0.02659437 -0.59103110 -1.51655310

[[4]]
[1]  0.02659437 -0.59103110 -1.36265335 -1.51655310

[[5]]
[1]  1.17848916  0.02659437 -0.59103110 -1.36265335 -1.51655310

For performance, you should consider @cyrilb38 approach with Reduce. See benchmarks below -
n <- 600
set.seed(11)
x <- rnorm(n)

r_sort <- function(x, y) {
  append(x, y, after = sum(x > y))
}

microbenchmark(
  lapply = lapply(seq_along(x), function(a) {
  sort(x[seq_len(a)], decreasing = T)
  }),
  forloop = {
    x.sort <- x[1]
    for(i in 2:n){
      x.sort <- append(x.sort, x[i], after = sum(x.sort > x[i]))
    }
  },
  Reduce = Reduce(r_sort, as.list(x), accumulate = T), # only if you want intermediate results
  Reduce2 = Reduce(r_sort, as.list(x)),
  times = 50
)

Unit: milliseconds
    expr       min        lq      mean    median        uq       max neval
  lapply 35.069533 36.318154 45.302362 37.870738 41.959249 203.45682    50
 forloop  8.366112  8.743501 11.196852  9.128391 11.800904  30.76272    50
  Reduce  4.574459  4.861448  7.418195  5.332593 11.076522  22.40293    50
 Reduce2  4.556300  4.754075  6.918486  5.161860  9.563809  14.41776    50


text:
Q: Tomcat JDBC connection pool reaches full capacity with XtraBackup I'm trying to workout a managed backup scheme on a production database with XtraBackup.
According to our DBA, XtraBackup doesn't lock the database, but issues a series of SHOW TABLE STATUS commands and then works on the file system level.
Still, just as XtraBackup runs my logs start to blow up with connection pool errors:
Error getting database connection:[http-nio-8080-exec-5] Timeout: Pool empty. Unable to fetch a connection in 10 seconds, none available[size:100; busy:100; idle:0; lastwait:10000].
There's some suggestion that turning off innodb-stats-on-metadata might help so we're trying that.
At the same time I want to confirm my connection pool settings are good:
<Resource name="jdbc/mydatabase_master"
          auth="Container"
          type="javax.sql.DataSource"
          factory="org.apache.tomcat.jdbc.pool.DataSourceFactory"
          testWhileIdle="true"
          testOnBorrow="true"
          testOnReturn="false"
          validationQuery="SELECT 1"
          validationInterval="30000"
          timeBetweenEvictionRunsMillis="30000"
          maxActive="100"
          minIdle="10"
          maxWait="10000"
          initialSize="10"
          removeAbandonedTimeout="60"
          removeAbandoned="true"
          minEvictableIdleTimeMillis="30000"
          jdbcInterceptors="org.apache.tomcat.jdbc.pool.interceptor.ConnectionState;
            org.apache.tomcat.jdbc.pool.interceptor.StatementFinalizer"
          username="db_user"
          password="mypassword"
          driverClassName="com.mysql.jdbc.Driver"
          url="jdbc:mysql://my.ip:3306/my_database"
          />

For everything besides the backup, this configuration works very well. Under most of our traffic the connection pool size hovers around the initialSize. It seems like setting the maxActive higher will just spawn new connections in the pool that are hanging.
Anything else seem like it could be tweaked in relation to XtraBackup?

A: After asking around, it looks like the issue is the strain XtraBackup puts on the database server. While XtraBackup doesn't use locking on all InnoDB databases, it still puts a strain on  the system. From the documentation

"Although innobackupex does not block your database's operation, any
  backup can add load to the system being backed up. On systems that do
  not have much spare I/O capacity, it might be helpful to throttle the
  rate at which innobackupex reads and writes InnoDB data. You can do
  this with the --throttle option."

We ended up just bumping up maxActive instead opting for throttling at this time. When XtraBackup initially runs, the queries are enough to slow the database down, causing the thread  pool to max out. Adding a higher level of maxActive connections allowed XtraBackup to run without maxing the connection pool.
It also seemed that turning innodb-stats-on-metadata to OFF helped speed up the SHOW TABLE STATUS queries, further lowering the strain on the DB.
Kind of a particular situation, but hopefully this will help anyone if they're in the same situation.


text:
Q: Can typescript-eslint naming-convention allow numbers? I've recently updated my @typescript-eslint/eslint-plugin and @typescript-eslint/parser from 5.9.1 to 5.38.1, and it's led my eslint . to begin complaining that purely-numeric object indices aren't allowed in my code. Is there some way to configure my ESLint to enforce a convention but not exclude numbers?
EDIT: the warning seems to only appear when numerical indices are not in square brackets, as in the example below. So the in-code fix seems easy enough - just add square brackets to any constants - but it would be good if ESLint reacted consistently!
My .eslintrc contains the following:
'@typescript-eslint/naming-convention': ['warn', {
    'selector': 'property',
    'format': ['strictCamelCase']
}],

I would like to be able to have an object (say, in a test file) like:
{
    0: true,         // should be accepted; currently raises a warning
    8: false,        // should be accepted; currently raises a warning
    [12]: true,      // accepted
    "foo": "bar",    // accepted
    "foo-bar": "baz" // should cause a warning because not strictCamelCase
}

The above numeric indices give the following error:
warning  Object Literal Property name `3` must match one of the following formats: strictCamelCase  @typescript-eslint/naming-convention

A: I was able to get the expected results using the filter property described in the rule.
'@typescript-eslint/naming-convention': ['warn', {
    'selector': 'property',
    'format': ['strictCamelCase'],
    'filter': { 'regex': '\\d+', 'match': false }
}],

DEMO
The idea is to exclude property names that consist only of digits from being checked against the camel case format. The pattern '\\d+' matches digit-only identifiers as required.


text:
Q: Checking for uploaded files with file_exists I have a form for uploading data into my database.The form has a number of input fields ranging form text,number,textarea and file(images).
When the form is submitted, i check if there are any images being uploaded and if so, check if the image being uploaded passes a series of checks( below maximum file size, correct extension etc), with the entire process in a try/catch block set to throw exceptions should any check fail.
My checks are as follows:
$upload=$_FILES['Upload']['tmp_name'];
if(isset($upload))
{
    if(!empty($upload) && is_uploaded_file($upload))
    {
        //Checks file size,extension and uploads the file
    }
    else
    {
        //throw new Exception
    }
}
else
{
    //throw new Exception
}

However, when using the above, isset would return true, even when no files are being uploaded.Upon some googling and looking on stack overflow, specifically isset and !empty not passing through a check for uploaded files , where it is stated that isset will return true due to $_FILES being a superglobal, i looked around for a solution and eventually settles on file_exists() as a replacement for isset() in my code.
My rationale for using file_exists() is that file that are uploaded(submitted) will be stored in a temp directory during the upload process, and if i check for this temp directory, i would thus be able to ascertain if a file is really uploaded.
After replacing isset() with file_exists my code is now working fine, but i am wondering if this is the correct way to proceed, or if there are any other better alternatives.
I look forward to any opinions and/or advice.

A: I would use the error-code given by $_FILES:
if($_FILES['Upload']['error'] == UPLOAD_ERR_OK) {
    //seems to have worked
}

There are even other error-codes you could check against, for example if the file was to big etc.

A: $upload=$_FILES['Upload']['tmp_name'];
if($upload)
{}

This will give the file temp name or null.


text:
Q: What is a T-Join? I have been struggling with the concept of T-Joins for an embarrassingly long time.
This is a definition from a text book:

Let G be a graph and let T be an even subset of V . A spanning subgraph H
  of G is called a T-join if $d_H(v)$ is odd for all v ∈ T and even for all v ∈ V \ T.

From Graph Theory by J.A. Bondy and U.S.R. Murty
Am I right in saying that this means that a T-Join is a graph which has all the same vertices of the original graph, but only the edges which ensure that all of the vertices in some set T have odd degree, and all the vertices which are not in T have even degree?
Questions:

*

*Do all graphs have T-Joins for all different sets of T?

*Can a graph have multiple T-Joins for the same T?

*Are there other properties of T-joins I should think about?

*Why are T-Joins so important?
Thank you very much for your time

A:
Do all graphs have T-Joins for all different sets of T?

No. In fact, an immediate consequence of the handshaking lemma, there is no T-join with |T| odd. On the other hand, if the vertices T lie in the same component and |T| is even, then there exists a T-join.

Can a graph have multiple T-Joins for the same T?

Yes. If you have a T-join and add/remove a cycle to/from it, you still have a T-join, since every vertex in the join will have the same parity.

Are there other properties of T-joins I should think about?

This is a useful characterization: $H$ is a T-join if and only if $H$ can be partitioned into edge-disjoint cycles and paths such that the |T|/2 paths connect disjoint vertices in T.
Thus you may think about the set of $\emptyset$-joins being the set of all Eulerian subgraphs. If $T=\{s,t\}$, then T-joins are $st$-paths plus some number of edge-disjoint cycles.

Why are T-joins so important?

From a computational perspective, T-joins generalize many natural graph problems and can still be computed efficiently. For example, determining if there is a path between two nodes $s$ and $t$ is equivalent to determining if there is an $\{s,t\}$-join. Moreover, one can efficiently optimize over T-joins; given a weight function $w$ on the edges, there is a polynomial-time algorithm to find a minimum-cost T-join with respect to $w$.
The Chinese Postman Problem is a famous non-trivial problem that can be easily cast as a minimum-cost T-join problem. The goal is to find the shortest tour of an undirected graph $G = (V, E)$ that visits every edge at least once and returns to the starting vertex. Although superficially similar to the Traveling Salesman Problem, the Chinsese Postman Problem can be solved in polynomial time as follows. Let $T$ be the set of vertices of odd degree and set $w(e) = 1$ for all edges $e$. Now compute a minimum-cost $T$-join $J$ with respect to $w$, and form the multigraph $G'$ by duplicating the edges in $J$. An Eulerian cycle in $G'$ now corresponds to the desired Chinese Postman tour in $G$.


text:
Q: Can I change the submit path the record identification creates for a form builder? I'm using the scaffold-generated _form partial.  The form_builder submit section looks like this:
<%= form_for(@party) do |f| %>

...

<div class="actions">
    <%= f.submit %>
</div>

This partial gets used in several views, but for update, it sends the PUT to an URL that contains the record ID.  That's not what I want (the model contains a token field that should be used instead).  My routes are correct, but if I'm understanding things correctly, record identification is creating this URL.  Can I change that, or do I need to move the submit section out of the partial?

A: You can use something like
<%= for_for(@party, url: the_url) do |f| %>

Reference

A: If the issue is simply that you don't want to use the numeric, DB ID in the url, consider either:

*

*Using to_param, or

*Something like friendly_id


text:
Q: Is it safe to invoke a AJAX call and let the browser cancel the request? If I make a AJAX reqeust it will be displayed in the network tab in Chrome. If I in the same moment makes a client based redirect, the AJAX request will canceled. But will the request make it to the server and execute as normal? Is it something in HTTP/TCP that know's that the client has canceled the request? I don't think so, but I want to be sure.

A: This is one of the few cases where synchronous requests (async: false in the $.ajax(...) options) are appropriate. This usually avoids the browser from navigating to the other page until the request has finished.

A: If you're running PHP server-side, it will stop processing in the event of a client-side abort. (From what I've read, this isn't the case with other server-side technologies, which will continue processing after a client aborts.) See:
http://php.net/manual/en/features.connection-handling.php
But, it's best not to assume anything one way or another. The browser may cancel the request. And this cancellation may occur in time to stop processing server-side. But, that's not necessarily the case. The client could cancel at any stage during the request -- from right before the request is actually sent to just after a response body is sent. Also bear in mind, there are other things which can interrupt server-side request processing (hardware, power, OS failure, etc.). Expect some unpredictability.
From this, I'd make two recommendations:

*

*Write your code be as transaction-safe as possible. If a request makes data changes, don't commit them until all changes have been piped to the database. And if your application relies on multiple AJAX requests to change some data, don't commit any of the changes until the the end of "final" AJAX request.

*Do not assume, even if a request finishes, that the client receives the response. Off the top of my head, that means if your application is AJAX-heavy, always rely on client-side state to tell the server what information it has, rather than relying on server-side state to assume the client "knows" something.


text:
Q: Threaded access log replayer for Tomcat? Suffered a "DOS" attack, which brought down my Tomcat 6 server by issuing numerous GET requests. I would like to replay the access file, preferably with multiple threads. Anyone know a good tool, or do I need to write it myself?

A: JMeter can do it, found this guide.


text:
Q: OTA gives a menu with option "Open in 'App Store' ", but does not install OTA from OwnCloud OTA gives a menu with option "Open in 'App Store' ", but does not install OTA from OwnCloud
I have read Apple Ad hoc and Enterprise distribution documents.  I referenced StackOverFlow posting
wireless iphone app distribution - problem with itms-services protocol .   I am using OwnCloud as server to distribute Ad hoc iOS 7.1 apps.  When I download the Index.html with
 Install iOS app

I get a action sheet menu that shows the above URL and options to 'Open in "AppStore", copy or cancel.
OwnCloud is running on an Apache server so I have updated the Mime types as suggested in StackOverFlow posting
Ad-hoc distribution fail
When I click the option "Open inApp Store", nothing happens and app does not install.
What prompts should I receive if install would run as expected?  Any suggestions to help trouble-shoot this issue are appreciated.
Updated with key contents from my plist
<key>url</key>
      <string>https://owncloud-myserver.net/index.php/apps/files?dir=/mydirectory/myAdApp.ipa</string>

A: The problem was Owncloud URL was going to logon page.  For OTA to work on SSl [https] website...web page URL must be direct without logon layer first.

A: We've had similar problems when old versions of the application, signed with outdated provisioning profiles, were still on the device. Manually deleting the application and/or profiles seems to fix it.


text:
Q: Converting changing JSON api with GSON Consider the following JSON
{
 "category": [
        {
          "code": "JCAT02",
          "value": " administrative"
        },
        {
          "code": "CAT19",
          "value": " government"
        }
      ],
 "studies": {
        "code": "C",
        "value": "Secundary degree"
      }
}

This is a piece of a result I get from calling a rest api. When I call that same api but for a different item, I get this answer:
{
     "category":
            {
              "code": "JCAT02",
              "value": " administrative"
            },
     "studies": [
          {
            "code": "C",
            "value": "Secundary degree"
          },
          {
            "code": "E",
            "value": "Master"
          }
        ]
    }

As you can see, the api is not very consequent in its answers and sometimes returns an object instead of an array. I wonder how i can deal with this in my Java object? I am getting  "Expected BEGIN_ARRAY but was BEGIN_OBJECT at line" . I a naive spur of the moment, I tried putting a list (with annotation @SerializedName ) and the object with the correct name in my class definition, but to no avail as you cant have multiple fields with the same name.
Is there another obvious way of dealing with this? I did a fast search google, but couldn't find what I was looking for.


text:
Q: MS Access date conversion error My MS Access sql string is:
select billdate from sales where billdate=#27/07/2014#;
This string displays results as: 27/07/2014.
But, if I input
select billdate from sales where billdate=#01/08/2014#;
The string doesn't display any result.
But if I substitute billdate #01/08/2014# with #08/01/2014#
The string displays results as: 01/08/2014.
In the sales table, the date format for billdate column is Short Date.
My system date and time settings are in dd/mm/yyyy format.
I am actually using VB.NET. But the problem persists with Access rather than my VB code. I am using MonthCalendar object.
Kindly provide solution at database level if possible. If it is not possible then only give me the code at coding level.

A: Try to format your Value in VB.net.
Your string should build like this:
Dim SQL as string = "select billdate from sales where billdate=" & Format(YourDate, "#yyyy\/MM\/dd#")


text:
Q: Apache2 Rewrite, remove file extensions Question
With an apache rewrite, when a user inputs:
example.com/home/
OR
example.com/home

The website will send the user to:
example.com/home.php

but the url will continue to be:
example.com/home/

My broken solution
My current code in .htaccess is:
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(home/)$ home.php [NC,L]

but it seems to redirect the user to "home.php.php.php.php" and so on.

A: First of all, it is a bad idea to have both example.com/home/ and example.com/home leading to same content (duplicate content is not appreciate by search engines like Google).
Then, you have to disable MultiViews to get the behaviour you want.
You can try with this code
Options -MultiViews
RewriteEngine On

RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^home/$ /home.php [NC,L]
# or ^home$ if you don't want it with trailing slash

A: Try this
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^\.]+)$ $1.php [NC,L]

You can access any PHP file without php extension :)


text:
Q: yield return vs Lazy I've learnt about lazy execution with yield return. Now I've seen a type which was introduced in .Net 4 (Lazy<T>). My question is: Is there any connection between these? I've checked the methods of Lazy<T> in ILSpy, but I haven't seen method implementation with yield return. So are they connected at lower levels?

A: They have nothing to do with each-other.
Iterator methods (methods which use yield return, such as LINQ methods) used deferred execution.
That means that the code in the method will not run until you enumerate its results.
Lazy<T> is a wrapper that will only compute its value when the Value property is first accessed.

A: No, they has nothing to do with each other .
yield is used to return current pointer to an object during iteration. It's very useful on iterating over large data sets and filtering/validating... some data contemporary (during iteration), so you don't need to cache filtered (say) values first, as it will make memory grow unreasonably big.
Lazy, is about a late/lazy or defered initialization, instead .  It's all about late intialization of an instance of a type you specify like such.
Example: you have a type, that on initilization allocates a lot of memory, but it's very common case in your application workflow that user will not need that type (some specific, user requested operation), so you use Lazy<T>, to define a type, but do not initialize it, so allocate memory only when it actually needed.
You can see that there is no any relation between these concepts.

A: No - an iterator is intended to serve a different function than Lazy<T>.
While iterators provide a way to implement IEnumerable<T> using deferred execution, and provide a form of "laziness", they're intended use case is quite different than Lazy<T>.  Lazy<T> provides lazy constructor with multiple fetches of the same instance.  Iterators, on the other hand, are intended to evaluate and return a sequence of values, not a single value.
Calling a method implemented with an iterator (yield return) will re-evaulate the sequence each time.
In addition, Lazy<T> can (optionally) provide thread safety guarantees.

A: Not really.  yield return is used to implement a method with a return type of IEnumerable<T> or IEnumerator<T>.  As Lazy<T> has no  methods with such return types clearly iterator blocks aren't used in its implementation.

A: No, the two doesn't use or depend on each other in any way.
Using yield return will not use Lazy<T>.
The point of Lazy<T> is to defer production of some costly data until (or even if) actually needed.
You can return it to say "if you really need this data, I can go and produce it, but if you don't need it, we've saved some time".


text:
Q: Getting 3G instead of 4G (LTE) I've got a Sierra Wireless Airprime MC7354 module, supplying a cellular communication to my x86.
By default, on module boot, it searches for an LTE network connection, and if fails - it falls back to 3G.
Though I'm supplied with several Sim cards, from different providers, all are LTE compatible (works great on my phone) - I can only get a 3G network (no LTE).
Ideas anyone?

A: Turns out the MC7354 supports only specified LTE bands in specific regions and is marketed for Americas region with LTE bands: B2, B4, B5, B13, B17, B25.
My provider was not supplying LTE connection in one of the above bands. I had to switch to another model that works on an LTE band that my provider provides.
For a list of suitable LTE bands provided by Sierra Wireless:

*

*https://www.sierrawireless.com/products-and-solutions/embedded-solutions/networking-modules/#/mcseriesembeddedmodules
For lists of LTE networks and frequency bands around the world:

*

*https://en.wikipedia.org/wiki/List_of_LTE_networks

*https://en.wikipedia.org/wiki/LTE_frequency_bands


text:
Q: Comments for my iPhone App I have created my iPhone App and i must do a document like javaDoc in java but i don't find anything with google.
I think that the comments have similar syntax but i'm not sure. (/*    */)
Can you help me?
Thanks

A: As Peter said above, there is DOxygen and then also DOxyClean which cleans it up a bit.  More info here: http://developer.apple.com/tools/creatingdocsetswithdoxygen.html
Comments can either be like this
// this is a comment above some line of code
if (foo != 0) {
    // do something
}

or like this
/*
// look ma, i'm commenting out a bunch of code

if (foo != 0) {
   // do something here
}

*/

or like this
// TODO: i'm marking something that will show up as a To-Do item in XCode's drop down list

and i think there's another one but I can't remember off hand

A: You can use // for single line comments, or /** */ for multi-line comments.
You'd also be wise to make use of #pragma mark to further organize your code. See here: http://cocoasamurai.blogspot.com/2006/09/tip-pragma-mark-organizing-your-source.html
There are also tools like Doxygen: hhttp://www.doxygen.nl

A: The answer about Doxygen was right on back when it was written, but since then Appledoc has come a long way.  It can now generate documentation that actually integrates with the popup dialogs that looks very close to the official documentation.
I would highly advise folks to use Appledoc going forward instead of Doxygen.
http://gentlebytes.com/appledoc/
PS - Doxygen is still a great product, and can be used for other things.  It's just not the best for iOS projects anymore.


text:
Q: Why do Windows and Linux machines handle Spring application integration tests differently? (Pardon my choice of diction - I am inexperienced with Java / Spring / PowerMock / SoapUI).
I made a code change that leads to a database call, and now I have failing integration tests around the Spring application. The structure is similar to this:
// Integration tests class
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = MyConfigurationClass.class)
@WebIntegrationTest
@PrepareForTest({..., MyDbConnector.class, ...})   // MyDbConnector is a wrapper around JdbcTemplate

...

@Rule
public PowerMockRule powerMockRule = new PowerMockRule();

@Rule
public ExpectedException expectedException = ExpectedException.none();

...

@Before
public void setUp() {
    ...
    whenNew(MyDbConnector.class).withNoArguments().thenReturn(mock(MyDbConnector.class));
    ...
}

// MyConfigurationClass.java
@SpringBootApplication
@ComponentScan(basePackages = ...,
    excludeFilters = {
        @ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE, value = someClass.class),
        @ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE, value = someOtherClass.class)
    }
)
public final class MyConfigurationClass {}

Before my change, the build ran successfully on Linux and Windows.
After my change, the build runs successfully on Windows, but fails on Linux. The build on Linux appears to attempt to connect to the database by calling a method in MyDbConnector, but fails to execute the SQL query. Since MyDbConnector should be mocked out, it shouldn't even enter into the real method.
Why does the Windows maven build (seem to) mock out MyDbConnector successfully, while the Linux maven build does not? I have confirmed the test runs on both OS's.
Potentially important notes:

*

*I have two integration test classes, one that only tests against Spring, and one that uses WsdlProjectRunner to run SoapUI tests against Spring

*I tried the build on two different Linux machines. On one machine, only the SoapUI tests failed, but on another, SoapUI and non-SoapUI tests fail.

EDIT: with the help of a co-worker, instead of:
@PrepareForTest({..., MyDbConnector.class, ...})

I added:
@PrepareForTest({..., MyDbConnector.class, ClassThatUsesMyDbConnector.class, ...})

That solves our problem, but does not answer the question, so I'll leave it open.


text:
Q: xslt transformation to html encoding UTF-8 this is the xml:
<?xml version="1.0" encoding="UTF-8"?>
<title>中文字Chinese charactors 1234</title>

this is the xslt:
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:fn="http://www.w3.org/2005/xpath-functions">
    <xsl:output method="html" version="1.0" encoding="UTF-8" indent="yes"/>
    <xsl:template match="/">
    <xsl:value-of select="title"/>
    </xsl:template>
</xsl:stylesheet>

But the output seems encoding error as below:
銝剜��hinese charactors 1234

I make sure that the encoding is using "Unicode UTF-8"
The software i am using is Altova XMLSpy
Why is this happening and how to solve, thank you very much for your help. : )

A: Unfortunately, encoding errors always happen in the parts of the system that you don't bother to tell us about because you don't realise they are relevant.
First, check that the XSLT processor is doing serialization (not, for example, writing the result tree to a DOM) and that the serialization is to a binary output destination rather than a character destination. Then check the actual bytes in this binary destination. Eliminate all possibility that the error is in the way you are decoding these bytes while displaying them, rather than in the bytes themselves.


text:
Q: HortonWorks Hadoop Sandbox and Tableau I am attempting to connect Tableau to the HortonWorks Hadoop sandbox as described here:  http://hortonworks.com/kb/how-to-connect-tableau-to-hortonworks-sandbox/
Tableau is able to see the virtual server as a data source, and it accurately lists the available Schemas and Tables.
However, when attempting to select any table or preview it's data, it displays an error popup that 'An error has occurred while loading the data. No such table [default].[tablename]' where default is the schema and tablename is the name of the table I'm attempting to view.
Here is what comes back when I run ifconfig from the Terminal window in the vm sandbox.  Tableau is connecting to the vm via 192.168.50.128.
eth3      Link encap:Ethernet  HWaddr 00:0C:29:EB:B9:DC
          inet addr:192.168.50.128  Bcast:192.168.50.255  Mask:255.255.255.0
          inet6 addr: fe80::20c:29ff:feeb:b9dc/64 Scope:Link
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:42011 errors:0 dropped:0 overruns:0 frame:0
          TX packets:9750 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000
          RX bytes:15123871 (14.4 MiB)  TX bytes:4019795 (3.8 MiB)

lo        Link encap:Local Loopback
          inet addr:127.0.0.1  Mask:255.0.0.0
          inet6 addr: ::1/128 Scope:Host
          UP LOOPBACK RUNNING  MTU:65536  Metric:1
          RX packets:5185579 errors:0 dropped:0 overruns:0 frame:0
          TX packets:5185579 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:0
          RX bytes:2054785522 (1.9 GiB)  TX bytes:2054785522 (1.9 GiB)

The guide states Enter the IP address of the Sandbox VM (typically 192.168.56.101)  which is different.
Is this IP difference the source of the issue or is there something else I've overlooked?  Im assuming that since it can see the schema and tables that this wouldn't matter.

A: Turns out this was a permissions issue which I was able to resolve by following this guide:  http://diveintobigdata.blogspot.com/2015/10/error-occurred-executing-hive-query.html
However, everywhere I was told to input localhost, such as when accessing Ambari, I had to replace localhost with 192.168.50.128 which I mentioned above is the IP I saw when executing ifconfig in the terminal.
Also, in step 1 of the guide there should not be any spaces in the file paths that were provided.


text:
Q: Get the child object of a limit(1) query on firebase database I have this data

I do this query
firebase.database().ref(${path}/buy)
  .orderByChild('price').limitToFirst(1)
  .once('value')
  .then(snapshot => console.log(snapshot.val()))

And I get this result

Then the question is

Is there an easy way to access the price attribute of the one object whose key I don't know?
e.g. snapshot.first().price or snapshot.only().price

Simply put, I want to avoid this
var result = snapshot.val()
var key = Object.keys(result)[0]
var price = result[key].price

A: When you execute a query against the Firebase Database, there will potentially be multiple results. So the snapshot contains a list of those results. Even if there is only a single result, the snapshot will contain a list of one result.
In your callback you need to handle this list by using snapshot.forEach():
firebase.database().ref(${path}/buy)
  .orderByChild('price').limitToFirst(1)
  .once('value')
  .then(snapshot => {
      snapshot.forEach(function(child) {
          console.log(child.val());
          console.log(child.val().price);
      })
  })


text:
Q: Is .find() faster than basic descendant selecting method? Slide 30 in Paul Irish's blog mentioned:
$('#container').find('div.robotarm') is faster than $('#container div.robotarm')
Is this true?

A: Maybe in an earlier version of jQuery that was the case. However, the expression
$('#container div.robotarm')

is normalized through jQuery into
$('#container').find('div.robotarm')

So the only reason why $('#container div.robotarm') should be slower is because of function call overhead. But, that would really be a trivial difference.
If that call wasn't normalized, sizzle (Resigs css selector engine) would be used to lookup that element (right to left). That of course would be much slower.

A: Since you asked for opinion, it doesn't matter.
You can always come up with a case where one runs faster than the other in some browser under a certain configuration of the DOM. No need to split hairs.

A: This is only correct when searching by ID.
But when we search by tag name it returns different results in modern browsers where $('div').find('p') is slower than $('div p') because the latter uses querySelector().


text:
Q: What is a cross-platform way to get the home directory? I need to get the location of the home directory of the current logged-on user. Currently, I've been using the following on Linux:
os.getenv("HOME")

However, this does not work on Windows. What is the correct cross-platform way to do this ?

A: This can be done using pathlib, which is part of the standard library, and treats paths as objects with methods, instead of strings.

*

*Path.expanduser()

*Path.home()
from pathlib import Path

home: str = str(Path('~').expanduser())

A: I found that pathlib module also supports this.
from pathlib import Path
>>> Path.home()
WindowsPath('C:/Users/XXX')

A: You want to use os.path.expanduser.
This will ensure it works on all platforms:
from os.path import expanduser
home = expanduser("~")

If you're on Python 3.5+ you can use pathlib.Path.home():
from pathlib import Path
home = str(Path.home())

A: I know this is an old thread, but I recently needed this for a large scale project (Python 3.8). It had to work on any mainstream OS, so therefore I went with the solution @Max wrote in the comments.
Code:
import os
print(os.path.expanduser("~"))

Output Windows:
PS C:\Python> & C:/Python38/python.exe c:/Python/test.py
C:\Users\mXXXXX

Output Linux (Ubuntu):
rxxx@xx:/mnt/c/Python$ python3 test.py
/home/rxxx

I also tested it on Python 2.7.17 and that works too.

A: This doesn't really qualify for the question (it being tagged as cross-platform), but perhaps this could be useful for someone.
How to get the home directory for effective user (Linux specific).
Let's imagine that you are writing an installer script or some other solution that requires you to perform certain actions under certain local users. You would most likely accomplish this in your installer script by changing the effective user, but os.path.expanduser("~") will still return /root.
The argument needs to have the desired user name:
os.path.expanduser(f"~{USERNAME}/")

Note that the above works fine without changing EUID, but if the scenario previously described would apply, the example below shows how this could be used:
import os
import pwd
import grp

class Identity():

    def __init__(self, user: str, group: str = None):
        self.uid = pwd.getpwnam(user).pw_uid
        if not group:
            self.gid = pwd.getpwnam(user).pw_gid
        else:
            self.gid = grp.getgrnam(group).gr_gid

    def __enter__(self):
        self.original_uid = os.getuid()
        self.original_gid = os.getgid()
        os.setegid(self.uid)
        os.seteuid(self.gid)

    def __exit__(self, type, value, traceback):
        os.seteuid(self.original_uid)
        os.setegid(self.original_gid)

if __name__ == '__main__':

    with Identity("hedy", "lamarr"):
        homedir = os.path.expanduser(f"~{pwd.getpwuid(os.geteuid())[0]}/")
        with open(os.path.join(homedir, "install.log"), "w") as file:
            file.write("Your home directory contents have been altered")


text:
Q: Как вывести список всех переменных из другого файла (кода)? Например есть файл кода (text.py):
a = 5
b = 'hello'
c = True
def d ():
      f = 4
class x ():
       l = 4

Нужно открыть файл в другом коде и получить список всех переменных без аргументов
Вывод должен выглядеть так:
['a', 'b', 'c', 'f', 'l']

Пробовал сделать так:
example = open ('text.py')
members = [attr for attr in dir(example) if not callable(getattr(example, attr)) and not attr.startswith("__")]
print (members)

A: Если как в вашем варианте, то можно регулярками найти просто все присваивания:
import re

pattern = re.compile(r'\s*(\w+)\s*=')
result = set()
with open('text.py') as f:
    for line in f:
        m = re.match(pattern, line)
        if m:
            result.add(m[1])
print(result)
# {'b', 'a', 'c', 'l', 'f'}

Но, конечно, случаи могут быть сложнее и тогда такой вариант уже не прокатит.
Множество использовано на случай повторных присваиваний в ту же переменную.


text:
Q: Why are changes to my page layout not reflecting in Communities delayed? I've noticed a weird bug in which changes to my Page Layout used in Communities for say New Contact Records are delayed.
An example of this is I have a Phone number field which is displayed on the page but not required, when marking this as required in my page layout editor no changes are reflected in the Community page, this is after I have have done a hard refresh and even logged out and logged back in.
Then when I removed the field from the layout editor, and refreshed my community page the field now appears (when it shouldn't) and has the required marked on the field.
Can anyone explain this weird behaviour?


text:
Q: How do I SELECT dummy column dynamically if one or few columns do not exist in the table? The SQL query I am trying is like this:-

select
  (select count(*) from ABC where AAA is not null) as AAA,
  (select count(*) from ABC where BBB is not null) as BBB,
  (select count(*) from ABC where CCC is not null) as CCC,
  (select count(*) from ABC where DDD is not null) as DDD;

Now the problem is that the table ABC exists in several schemas and in each schema it has different structure. Say in schema S1, the table abc has only two columns - AAA and CCC. In schema S2 it has all the four columns - AAA, BBB, CCC, DDD. So, I have taken the super structure of the table and created my query as above. Now what I want is that if the table in certain schema has only two columns than also it should display the 'NOT NULL' count for all four columns, showing NA for the columns not present. How should I achieve this?
NOTE: There are 50+ such tables with non-uniform structure across different schemas. So, I have to edit the SQL again and again for around 250 schemas for several tables.

A: try the below. I am assuming that varchar(10) is big enough to hold your row count.
 SELECT
  ( SELECT CASE WHEN NOT exists (SELECT 1 FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'ABC' AND COLUMN_NAME = 'DDD') then 'NA' else CAST (COUNT(*) as varchar(10)) end
    FROM abc AS t1
    WHERE aaa  IS NOT NULL
  ) AS AAA,
    ( SELECT CASE WHEN NOT exists (SELECT 1 FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'ABC' AND COLUMN_NAME = 'DDD') then 'NA' else CAST (COUNT(*) as varchar(10)) end
    FROM abc AS t1
    WHERE bbb  IS NOT NULL
  ) AS BBB,
    ( SELECT CASE WHEN NOT exists (SELECT 1 FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'ABC' AND COLUMN_NAME = 'DDD') then 'NA' else CAST (COUNT(*) as varchar(10)) end
    FROM abc AS t1
    WHERE CCC  IS NOT NULL
  ) AS CCC,
    ( SELECT CASE WHEN NOT exists (SELECT 1 FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'ABC' AND COLUMN_NAME = 'DDD') then 'NA' else CAST (COUNT(*) as varchar(10)) end
    FROM abc AS t1
    WHERE DDD  IS NOT NULL
  ) AS DDD
FROM
  ( SELECT 1 AS AAA,1 as BBB, 1 as CCC, 1 as DDD
  ) AS dummy ;

A: Note: This answer is based on JamieA's answer, but it required several changes to make it work on Oracle and I didn't want to totally edit his answer
This one works on Oracle.
SELECT
  case when exists(select 1 from user_tab_columns
                 where table_name='ABC' and column_name='AAA')
       then (select to_char(count(*)) FROM ABC WHERE AAA IS NOT NULL )
       else 'NA' end  AS AAA,
  case when exists(select 1 from user_tab_columns
                 where table_name='ABC' and column_name='BBB')
       then (select to_char(count(*)) FROM ABC WHERE BBB IS NOT NULL )
       else 'NA' end  AS BBB,
  case when exists(select 1 from user_tab_columns
                 where table_name='ABC' and column_name='CCC')
       then (select to_char(count(*)) FROM ABC WHERE CCC IS NOT NULL )
       else 'NA' end  AS CCC,
  case when exists(select 1 from user_tab_columns
                 where table_name='ABC' and column_name='DDD')
       then (select to_char(count(*)) FROM ABC WHERE DDD IS NOT NULL )
       else 'NA' end  AS DDD
FROM
  ( SELECT 1 AS AAA, 1 as BBB, 1 as CCC, 1 as DDD from dual
  );


text:
Q: How to fetch Package DDL in Oracle 8i I want to fetch a Package DDL in Oracle 8i.
8i doesn't support DBMS_METADATA.get_ddl.
Can it be done using export?

A: DBMS_METADATA.GET_DDL is not mandatory to view the source of a package.
You can use DBA_SOURCE/ALL_SOURCE: https://docs.oracle.com/cd/A87860_01/doc/server.817/a76961/ch277.htm#101236
select text from dba_source
where owner = 'OWNER_OF_PACKAGE'
and name = 'NAME_OF_PACKAGE' order by type, line;

A: You are right, you can use export to get the source code. You export into a dumpfile and the you import  the dumpfile with the SHOW=Y option. When you use this option the dumpfile is not imported into the database but the commands that the import would use will be written to logfile of the import.
You cannot export only a package but whole schema or the whole database.
export parameters:
# export schema SCOTT, do not export table data or table statistics:
OWNER=SCOTT
ROWS=NO
STATISTICS=NONE

# define the log file and the dump file
LOG=/tmp/exp_schema.log
FILE=/tmp/schema.dmp

You can store this parameters in a file, e,g, /tmp/exp_schema.par and then execute
exp system/manager paefile=/tmp/exp_schema.par

for import you can use the following parameters
# SHOW=Y causes the program to write the commands to the logdile
FULL=Y
SHOW=Y

# define the log file and the dump file
LOG=/tmp/imp_schema.log
FILE=/tmp/schema.dmp

You can use the following parameters in export or import parameter
file to avoid the generation of code for constraints,indexes, grants or triggers.
GRANTS=N
INDEXES=N
TRIGGERS=N  # valid only for export
CONSTRAINTS=N

The importlogfile will contain the source code of all packages, function and procedures of schema SCOTT.
Maybe you have to edit the extracted code and remove some line breaks that were added by the import program.
Source:
Oracle8i Utilities
Release 2 (8.1.6)
Part Number A76955-01
https://docs.oracle.com/cd/A87860_01/doc/index.htm


text:
Q: Which model to consider in Geodjango? The initial one or the one generated by ogrinspect? I have made models initially for my application as given in https://docs.djangoproject.com/en/1.8/ref/contrib/gis/tutorial/
After which i did ogrinspect and it generated a model. The difference between the model initially and the one ogrinspect generated was geometry field.
Initially model has
mpoly = models.MultiPolygonField()
objects = models.GeoManager()

And the one which ogrinspect generated has
geom = models.MultiPolygonField(srid=4326)
objects = models.GeoManager()

SO which model should i want to consider? whether i should replace the existing model with one which was generated by ogrinspect and do migrate or no need of replacing?

A: I would say it depends on the coordinate system of your input data. If your input data is a shapefile for instance, you can look in its .prj file, determine (with that handy service) that the SRID should be XYZ, and then you can pass that value as an --srid XYZ option to python manage.py ogrinspect, which will then generate the proper models.MultiPolygonField(srid=XYZ) geometry object, with the right coordinate system.


text:
Q: What do you call a government official who cannot be fired? In Austria there are government officials who cannot be fired. Usually, they get this status after serving a certain amount of time.
In German this practice is called Pragmatisierung and seems to be specific to Austria.
I am looking for a close-enough English equivalent.
Example of usage in a sentence (XXXX is the adjective I am looking for):

A XXXX government official cannot be laid off.

The only word that comes to mind is tenured. The problem is that tenured seems to be specific to academia, whereas Pragmatisierung is not industry-specific (all sorts of civil servants, not only teachers, can get this status).

A: As is often the case with languages, some words are impossible to translate exactly into others, and there are also some words that describe specific phenomena for which there is no equivalent word in another language. To my knowledge, there isn't an English word that specifically describes a government official who cannot be fired. The closest word that comes to mind is indeed tenure, but that (as you correctly stated) is usually used in the field of academia.
In the example that you gave, you could try saying: "A permanent government official cannot be laid off." You could also describe the government official's position rather than the government official himself. For example, you could say that the official has a "life-long job" or is hired "for life", etc.

A: While the OP suggested and discarded tenure, it may be employed in areas other than academics.
From Dictionary.com (definition 4):

status granted to an employee, usually after a probationary period, indicating that the position or employment is permanent.

An example specific to government employees enjoying a permanent position would be federal judges. Federal judges enjoy lifetime tenure.
From "He Won't Be Smiling: How Federal Judges Could Be Donald Trump's Worst Nightmare"

As Alexander Hamilton argued in Federalist 78, the Framers granted federal judges life tenure to protect them from undue political influence...

Even with tenure, a judge may be impeached for misconduct, such as taking bribes. I suspect that Austrian civil service law of 1979 (from which the term Pragmatisierung was derived) has a similar guard against gross misconduct.


text:
Q: Mascarar valor no input Gostaria de fazer o seguinte, o usuario digita 1, no input teria o valor ,01, ai ele digita 2, apareceria ,12, ai ele digita 3, apareceria 1,23, assim por diante. Tenho o input da seguinte maneira:
 <input type="text" class="form-control"  id ="produto_preco_unitario" name="produto_preco_unitario"
                         value="" placeholder="Preço por Unidade" required/>

A:

var mask = {
 money: function() {
    var el = this
    ,exec = function(v) {
    v = v.replace(/\D/g,"");
    v = new String(Number(v));
    var len = v.length;
    if (1== len)
    v = v.replace(/(\d)/,"0.0$1");
    else if (2 == len)
    v = v.replace(/(\d)/,"0.$1");
    else if (len > 2) {
    v = v.replace(/(\d{2})$/,'.$1');
    }
    return v;
    };

    setTimeout(function(){
    el.value = exec(el.value);
    },1);
 }

}

$(function(){
 $('input').bind('keypress',mask.money)
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-maskmoney/3.0.2/jquery.maskMoney.min.js"></script>
 <input type="text" class="form-control"  id ="produto_preco_unitario" name="produto_preco_unitario"
                     value="" placeholder="Preço por Unidade" required/>

Você também pode usar com separador de milhar

$(function () { //ready
    $("#produto_preco_unitario").maskMoney();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-maskmoney/3.0.2/jquery.maskMoney.min.js"></script>

<input type="text" id="produto_preco_unitario" value="" />

O arquivo pega no github jquery.maskMoney.js
Se quiser trocar a moeda para o formato português (decimal virgula e separador de milhar ponto) faça assim:

$(function () { //ready
    $("#produto_preco_unitario").maskMoney({thousands: ".", decimal: ","});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-maskmoney/3.0.2/jquery.maskMoney.min.js"></script>

<input type="text" id="produto_preco_unitario" value="" />


text:
Q: How effective is the honeypot technique against spam? By "honeypot", I mean more or less this practice:
#Register form
<style>
    .hideme{
        display:none;
        visibility: hidden;
    }
</style>
<form action="register.php">
    Your email: <input type="text" name="u-email" />
    Choose a password: <input type="text" name="passwd" />
    <div class="hideme">
        Please, leave this field blank: <input type="text" name="email" />  #the comment is for text-browser users
    </div>
    <input type="submit" value="Register" autocomplete=off />
</form>

//register.php
<?php
if($_POST['email'] != ''){
    die("You spammer!");
}
//otherwise, do the form validation and go on.
?>

more info here.
Obviously, the real fields are named with random hashes, and the honeypot fields can have different names (email, user, website, homepage, etc..) that a spambot usually fills in.
I love this technique because it doesn't cause the user to be annoyed by CAPTCHA.
Do any of you have some experience with this technique? Is it effective?

A: I've used the honeypot captcha on three forms since about 2010, and it's been stunningly effective with no modifications until very recently. We've just made some changes that we think will stop most of the spambots, at least until they get more sophisticated. In broad strokes, here's the way we've set it up:
One input field on each form is hidden (display:none specified in the CSS class attribute) with a default value of "". For screen readers and such, the hidden input label makes it clear that the field must be left empty. Having no length at all by default, we use code server-side (ColdFusion in our case, but it could be any language) to stop the form submission if anything at all is in that field. When we interrupt the submission that way, we give the same user feedback as if it was successful ("Thank you for your comment" or something similar), so there is no outward indication of failure.
But over time, the bots wised up and the simplest of our forms was getting hammered with spam. The forms with front-end validation held up well, and I suppose that's because they also don't accept just any old text input, but require an email address to be structured like an email address, and so on. The one form that proved vulnerable had only a text input for comments and two optional inputs for contact information (phone number and email); importantly, I think, none of those inputs included front-end validation.
It will be easy enough to add that validation, and we'll do that soon. For now, though, we've added what others have suggested in the way of a "time trap." We set a time variable when the page loads and compare that timestamp to the time the form is submitted. At the moment we're allowing submission after 10 seconds on the page, though some people have suggested three seconds. We'll make adustments as needed. I want to see what effect this alone has on the spam traffic before adding the front-end validation.
So the quick summary of my experience is this: The honeypot works pretty well as it was originally conceived. (I don't recall where I found it first, but this post is very similar to the first I saw about it more than a decade ago.) It seems even more effective with the addition of client-side validation enabled by HTML5. And we think it will be even better with the server-side limits we've now imposed on those too-hasty submissions.
Lastly, I'll mention that solutions like reCaptcha are off the table for us. We spent significant time developing a web app using Google's map API, and it worked great until Google changed their API without warning and without transition advice. We won't marry the same abusive spouse twice.

A: It works relatively well, however, if the bot creator caters to your page they will see that (or even have a routine setup to check) and will most likely modify their bot accordingly.
My preference is to use reCaptcha. But the above will stop some bots.

A: Old question, but I thought I'd chime in, as I've been maintaining a module for Drupal (Honeypot), which uses the Honeypot spam prevention method alongside a time-based protection (users can't submit form in less than X seconds, and X increases exponentially with each consecutive failed submission). Using these two methods, I have heard of many, many sites (examples) that have eliminated almost all automated spam.
I have had better success with Honeypot + timestamp than I have with any CAPTCHA-based solution, because not only am I blocking most spammers, I'm also not punishing my users.

A: With below technique, I block 100% of spams.

*

*honeypot with display:none.
if failed, run extra script to collect IP address and write it in .htaccess file on deny from line.

*count number of URL on comment field.
if failed, warn only because this can be human.

*measure the time to post.
if less than 5 sec, show error message and let them try again because human can write pretty fast with auto-filling plugin.

*trim htaccess file dailly with crontab so deny lines won't go over 30 lines (adjust accordingly).

Deny access with IP address is very effective because bots keep trying to sneak in with same IPs (if they change IP then I put that new IP on htaccess so no problem). I trim .htaccess file daily with crontab automatically so the file won't be too big. I adjust the number of IP to block so same bot with same IP will be blocked for about a week or so. I noticed that same IP is used by bot for 3 days attacking several times.
The first #1 trick blocks about 99% and #2 blocks about 1% and the bot won't go through those 2 so #3 might not be necessary.


text:
Q: FontAwesome for checkbox I am trying to use FontAwesome for checkbox - so in unchecked state - it will display Trash icon, and in checked state, it will display the same icon but in red color.
I added the font-awesome.min.css and the fonts.
HTML:

   <input type="checkbox" id="checkbox-delete-6053923167078">

CSS:
.delete-checkbox input[type="checkbox"] {
    display: none;
}

.delete-checkbox span:before {
    font-family: "FontAwesome";
    font-style: normal;
    width: 1em;
    height: 1em;
    content: '\f014';
    margin-right: .3em;
}

.delete-checkbox input[type="checkbox"]:checked ~ span:before {
    color: red;
}

I do see in the result the trash icon, however, it's not clickable and when I click on it, it doesn't turn red.
How can I do it?

A: Try this:
http://jsbin.com/sanoya/edit?html,css,output
The problem is that when you use display: none; you are essentially removing the element from the DOM, and the element is therefore not clickable.

A: You can use JavaScript if you like
Replace your  with the following:

Or, if you are using jQuery, you can use this:

A: There's no need to use JavaScript to achieve what you're looking for. Your markup was almost fine. You should use a  tag, instead of a  tag and also, you should have used  in your CSS. Doing so, you would have end up with a markup like this

  <input type="checkbox" id="checkbox-delete-6053923167078">

and with CSS like this
.delete-checkbox input[type="checkbox"] {
  display: none;
}

.delete-checkbox label:before {
  font-family: "FontAwesome";
  font-style: normal;
  width: 1em;
  height: 1em;
  content: '\f014';
  margin-right: .3em;
}

.delete-checkbox input[type="checkbox"]:checked ~ label:before {
  color: red;
}

As you can see, I've only changed your  with the  tag.
With this, you are totally able to do what you're looking for, without using and JavaScript code.
Fiddle


text:
Q: Storing checkbox values in order that they are clicked in PHP I have a form that has 4 checkboxes and I want to be able to save the clicked checkboxes in the database but in the order, they are clicked. So for example, if I click the checkboxes in the order, 1, 3, 4, 2, it should save in the db in that order. At the moment, it just saved it in the default order despite me doing a selection in a different order. Is there any way to accomplish this?
My form:
<?php
// Initialize the session
session_start();
// Store the submitted data sent
// via POST method, stored
// Temporarily in $_POST structure.
$_SESSION['system_battery_runout']
    = $_POST['system_battery_runout'];
?>
<!DOCTYPE html>

    <title>Rank form</title>

Which Appliances Do You Use The Most?

        <form action="insert.php" method="post">

<input  type="checkbox" style="height:20px; width:20px;" name="rank_appliances[]" value="Fridge" /> Fridge

<input  type="checkbox" style="height:20px; width:20px;" name="rank_appliances[]" value="Stove" /> Stove

<input  type="checkbox" style="height:20px; width:20px;" name="rank_appliances[]" value="TV" /> TV

<input  type="checkbox" style="height:20px; width:20px;" name="rank_appliances[]" value="Water Tank" /> Water Tank

            <input type="submit" value="Submit" style="float: right;" >
        </form>

insert.php:
<?php
session_start();
?>
<!DOCTYPE html>

    <title>Insert Page</title>

        <?php

        // serverfullname => localhost
        // userfullname => root
        // password => empty
        // database fullname => staff
        $conn = mysqli_connect("localhost", "root", "", "survey");
        // Check connection
        if ($conn === false) {
            die("ERROR: Could not connect. "
                . mysqli_connect_error());
        }
        $system_battery_runout = $_SESSION['system_battery_runout'];
        $rank_appliances = $_POST['rank_appliances'];
        $checkboxvalue = implode(",", $rank_appliances);

        $sql = $conn->prepare("INSERT INTO cus_survey( system_battery_runout,rank_appliances)  VALUES (?, ?)");
        $sql->bind_param('ss', $system_battery_runout, $checkboxvalue);

        if (mysqli_stmt_execute($sql)) {
            echo "
Your survey was captured successfully. Thank You!";
        } else {
            echo "
Sorry, something went wrong
 ";
        }

        // Close connection
        mysqli_close($conn);
        ?>

A: A new, hidden field, can be populated easily using Javascript and will yield the clicked order when the form is submitted.

let tmp=[];
let hidden=document.querySelector('input[name="rank_sequence"]');

document.querySelectorAll('input[name="rank_appliances[]"]').forEach( input=>input.addEventListener('click',function(e){
  /* Add the clicked value if checked or remove if unchecked */
  if( this.checked )tmp.push( this.value );
  else{
    if( tmp.includes( this.value ) )tmp.splice( tmp.indexOf( this.value ), 1 );
  }
  //add to the hidden input value
  hidden.value=tmp.join(',');
  console.info(hidden.value);
}));

Which Appliances Do You Use The Most?

  <form action="insert.php" method="post">

    <input type="checkbox" style="height:20px; width:20px;" name="rank_appliances[]" value="Fridge" /> Fridge

    <input type="checkbox" style="height:20px; width:20px;" name="rank_appliances[]" value="Stove" /> Stove

    <input type="checkbox" style="height:20px; width:20px;" name="rank_appliances[]" value="TV" /> TV

    <input type="checkbox" style="height:20px; width:20px;" name="rank_appliances[]" value="Water Tank" /> Water Tank

    <input type="submit" value="Submit" style="float: right;">
    <input type='hidden' name='rank_sequence' />
  </form>

Perhaps to process the new input element you could do the following (thoough untested)
if( $_SERVER['REQUEST_METHOD']=='POST' && isset(
    $_SESSION['system_battery_runout'],
    $_POST['rank_sequence']
)){

    $conn = new mysqli("localhost", "root", "", "survey");
    $stmt=$conn->prepare('insert into `cus_survey` ( `system_battery_runout`, `rank_appliances` ) values (?, ?)');
    $stmt->bind_param('ss', $_SESSION['system_battery_runout'], $_POST['rank_sequence'] );
    $stmt->execute();

    $msg=( $stmt->affected_rows==1 ) ? 'Your survey was captured successfully. Thank You!' : 'Sorry, something went wrong';
    $stmt->close();
    $conn->close();

    printf('
%s
',$msg);

}


text:
Q: Create a macro for heading LNCS class requires 3rd-level heading to be "Run-in Heading in Bold. Text follows" at 10 point, bold
It seems that there is no existing macro for that, so I have written:
\newcommand{\headingthree}[1]{\noindent\textbf{#1}}

I also use \paragraph, I realize that \paragraph automatically adds a line above the text, but \headingthree doesn't.
Does anyone know how to make my \headingthree automatically add space above the text as a \paragraph does?
PS: the 3rd-level heading:

A: With the help of the titlesec package you can redefine one of the existing sectional unit commands to produce the desired layout; in the following example I redefined \subsubsection to have a run-in title:
\documentclass{article}
\usepackage{titlesec}
\usepackage{lipsum}

\titleformat{\subsubsection}[runin]
  {\normalfont\normalsize\bfseries}{\thesubsubsection}{1em}{}
\titlespacing*{\subsubsection}{0pt}{3.25ex plus 1ex minus .2ex}{1em}

\begin{document}

\section{Test section}
\lipsum[2]
\subsection{Test subsection}
\lipsum[2]
\subsubsection{Test subsubsection}
\lipsum[2]

\end{document}

Apparently the question has been answered; however, looking at the image that appears in the question, the following re-definitions of \section, \subsection, \subsubsection and \paragraph will produce sectioning units with the given specifications for the first four levels shown, in a document with the default 10pt size:
\documentclass{article}
\usepackage{titlesec}
\usepackage{lipsum}

\titleformat{\section}
  {\normalfont\large\selectfont\bfseries}{\thesection}{1em}{}
\titleformat{\subsection}
  {\normalfont\normalsize\selectfont\bfseries}{\thesubsection}{1em}{}
\titleformat{\subsubsection}[runin]
  {\normalfont\normalsize\bfseries}{}{0em}{}[.]
\titleformat{\paragraph}[runin]
{\normalfont\normalsize\itshape}{}{0em}{}[.]

\setcounter{tocdepth}{2}% don't include subsubsections in ToC

\begin{document}
\tableofcontents
\section{Test section}
\lipsum[2]
\subsection{Test subsection}
\lipsum[2]
\subsubsection{Test subsubsection}
\lipsum[2]
\paragraph{Test paragraph}
\lipsum[2]

\end{document}

A: The class provides \subsubsection that does exactly what you need:
\documentclass{llncs}

\usepackage{lipsum}

\begin{document}

\mainmatter              % start of the contributions

\title{A title}
\author{A. N. Thor}
%
\institute{Nowhere University, Princeton NJ 08544, USA,\\
\email{thor@nowhere.edu}}

\maketitle              % typeset the title of the contribution

\begin{abstract}
A very short  abstract.
\end{abstract}

\section{A section}
\lipsum[2]

\subsection{A subsection}
\lipsum[2]

\subsubsection{A subsubsection}
\lipsum[2]

\paragraph{Ghi}
\lipsum[2]

\end{document}


text:
Q: Firebase security rules based on currently existing values I'm trying to implement a rule in my firebase DB that dis-allows a user to update a posts likes value if it doesn't already exists in their fanned data. Consider this file structure.

Notice how there is a full dictionary of values. Given conditions in my app, users have the ability to write to the likes value in this dictionary. In the event that this dictionary of data Does not already exist, I want to prevent users from writing to the likes value so this doesn't happen.

This is the security rule I have currently in place but I am not sure how I can solve this problem.

I have already looked at the documentation and watched David East's video on securing your Firebase DB but I am still lost.