text:
Q: Converting Distance using C# Program Problem: I am trying to convert from one type of distance to the next after the user inputs the data. The user must select from one list to convert to the other list in distance. For example, selecting inches in one list to convert to yards in another list.
My code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Distance_Converter
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        private void ConvertButton_click(object sender, EventArgs e)
        {
            //int Inches = 1;
            //int Feet = 12;
            //int Yards = 36;
            int distance_to_convert;
            string lengthOption1;
            string lengthOption2;
            int inches_feet;
            int inches_yard;

            lengthOption1 = FromListBox.SelectedItem.ToString();
            lengthOption2 = ToListBox.SelectedItem.ToString();
            distance_to_convert = int.Parse(distancetoconvertTextBox.Text);

            if ((FromListBox.SelectedIndex) != -1 && (ToListBox.SelectedIndex) != -1)
            {
                switch (lengthOption1)
                {
                    case "Inches":
                        if (lengthOption2 == "Inches")
                        {
                            //object distancetoconvert = null;
                            ConvertedDistanceTextBox = distance_to_convert.ToString();
                        }
                        else if (lengthOption2 == "Feet")
                        {
                            inches_feet = distance_to_convert / 12;
                            ConvertedDistanceTextBox = inches_feet.ToString();
                        }
                        else if (lengthOption2 == "Yards")
                        {
                            inches_yard = distance_to_convert / 36;
                            ConvertedDistanceTextBox = inches_yard.ToString();
                        }
                        break;
                    case "Feet":
                        if (lengthOption2 == "Inches")
                        {
                            int feet_inches = distance_to_convert * 12;
                            ConvertedDistanceTextBox = feet_inches.ToString();
                        }
                        else if (lengthOption2 == "Feet")
                        {
                            ConvertedDistanceTextBox = distance_to_convert.ToString(); ;
                        }
                        else if (lengthOption2 == "Yards")
                        {
                            int feet_yard = distance_to_convert / 3;
                            ConvertedDistanceTextBox = feet_yard.ToString();
                        }
                        break;

                    case "Yards":
                        if (lengthOption2 == "Inches")
                        {
                            int Yards_inches = distance_to_convert * 36;
                            ConvertedDistanceTextBox = Yards_inches.ToString();
                        }
                        else if (lengthOption2 == "Feet")
                        {
                            int Yards_feet = distance_to_convert * 3;
                            ConvertedDistanceTextBox = Yards_feet.ToString();
                        }
                        else if (lengthOption2 == "Yards")
                        {
                            ConvertedDistanceTextBox = distance_to_convert.ToString(); ;
                        }
                        break;
                }
            }

        }
        private void Exitbutton_click(object sender, EventArgs e)
        {
            this.Close();
        }
    }
}

My dilemma: The code looks correct in every sense. However, when I try to convert from int to string on multiple occasions the IDE gives me a red line. The code won't compile and creates build errors. I am thinking that I will have to create a separate class to convert from int to string.
The error states: "Error    CS0029  Cannot implicitly convert type 'string' to 'System.Windows.Forms.TextBox' "
It appears on line - 42, 47, 52, or any line that begins with ConvertedDistanceTextBox = .
My apologies, I am new to coding and I am trying to learn.  And I am relatively new to stackoverflow.

A: You should set your string values to the text property of your textbox
ConvertedDistanceTextBox.Text = inches_yard.ToString();


text:
Q: Is there a possibility of there ever being a PHP.NET? Sorry if this is a silly and/or stupid question but... Will there ever be, or would it even be possible to have a PHP.NET? Or have I got the wrong end of the stick?
It seemed to me that one of the main points of .NET was that you could write your code in one of a bunch of the .NET languages and have it compile into CLR. Could this happen with PHP, or is there something about PHP that makes this impossible? Or is there more political reasons?

A: Someone has actually already begun working on just such a thing
http://www.codeplex.com/Phalanger
http://www.php-compiler.net/doku.php

A: As an aside:
I don't believe .Net support for PHP would be a great idea.
I use PHP every day of my life. It's not because I like the language (it's a collection of mismatched functions with very little OO support), but rather because it's the best tool for the job.
PHP has a lightweight feel and one can do almost anything in a few easy lines. It's string handling is effortless, and support is ubiquitous. Array handling is great, too.
I feel that if PHP joined the .Net CLR I would not be tempted to switch over to use it. If one wanted to work with .Net one would do better to use a nicer, better structured language, such as C#.

A: I would say that it is unlikely as that there is ASP.net, but I would not say never because of Python.NET or IronPython. There is already one attempt called Phalanger. From the looks of the official wiki, its a serious development effort.

A: Actually it exists. It's not called PHP.NET, but Phalanger(http://phalanger.codeplex.com). It compiles PHP code into MSIL instructions.
It allows to run PHP application in so called legacy mode (and you can benefit from a faster running time since it's compiled), and if you want to use CLR features that are not present in PHP you can turn on PHP/CLR compiler extensions.
There is also so called Pure mode where PHP langauge is modified to behave more like C# or Visual Basic.
I think combining PHP and .NET is great idea, since you can make the best of both worlds. From PHP it would fast development and deployment process, steep learning curve and there are lots of great PHP open-source applications. On the .NET side, verifiable ISO standartized environment, peformance, managed secure code, advanced development tools,...

A: Sure, there's a possibility. Python runs in the CLR, after all.
Side note: PHP is now a one-click install for IIS, so if you're waiting to bring PHP into your Microsoft stack, go ahead and give it a try. MS is even working on a PHP bytecode cache for Windows.

A: Once this is in I don't see why not.
http://en.wikipedia.org/wiki/Dynamic_Language_Runtime

A: The CLR is essentially a virtual machine, so things are compiled to it essentially the same way C code is compiled to x86 or PowerPC or arm or whatever.
There is an implementation of python that compiles to .NET assemblies, there's also COBOL, and a few others. No technical reason PHP couldn't be done the same and executed by the CLR in IIS.

A: .NET is a framework that is based on a number of technologies such as CLR and provides an extensive collection well-organized class libraries that are suitable for almost all conceivable functions that are used in Web applications. In addition, it allows you to easily create components that extend the framework.
Although PHP has similar properties, such as PEAR libraries, PHP and ASP.NET are not really identical, because the .NET framework ab ovo on an OOP paradigm and OOP-based approaches, and PHP is not. This difference is most evident in the way, is how to access classes and objects in PHP and ASP.NET.

A: You could give a try to the jsc project which will convert MSIL to php source for you.
This will enable you to write C# code in visual studio and run it on an inexpensive php server.

A: The two are totally different, they are in competition with each other. Both will try to be good at their ends. So i dont think there is going to be anything as such in the future. However, you can use PHP inside of Visual Studio, there are plugins available for that.
Thanks

A: PHP have got suspiciously pally with Windows... it doesn't seem impossible
And besides PHP.NET

A: Well PHP is good as is already. Even if it does become PHP.NET I doubt it will be done by Microsoft.

A: you could develop php on windows to use windows functions, and ultimately call on .NET objects. I believe apache now allows php to call on native windows calls/functions and .NET functions/classes/objects, provided you have the right settings turned on.
as for .NET adapting php syntax, i think some people are trying to do this, aside from the existing attempts.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to check url is working in Batch I'm trying to check URL status using bat file
    <# : batch portion
@echo off & setlocal

set "URL=http://l:8080/LevelTwoChargerStartTransaction?chgStationRef=T0001&rfId=0.1.0.255.0.0.0.0."
powershell -noprofile "iex (${%~f0} | out-string)"

goto :EOF

: end batch / begin PowerShell hybrid chimera #>

$request = [Net.WebRequest]::Create($env:URL)
echo $request
$response = $request.GetResponse()
echo $response
$stream = $response.GetResponseStream()
echo $stream
$reader = new-object IO.StreamReader($stream)
echo $reader
[void]$reader.ReadToEnd()

and i need to get status of the URL how can i do this using batch-file or any other way to do this?


text:
Q: Cannot block the form submission with Ajax response fired by onSubmit attribute. This question is a bit different from the ones already answered...
What I'm looking to do is run a function, autoHide(), that calls a PHP file, artistdo.php, that executes a MySQL query, on form submit and if it returns true (the query succeeds), the form doesn't submit.
What I'm getting is that the MySQL query isn't running and even if I remove the query and place return true in the artistdo.php page, the return false in the ajax doesn't stop the form submission but it does cause the alert("Success"); to be called, however, if I put return false within the autoHide() function but outside the AJAX, the form correctly doesn't submit. Here's what I have so far:
The form page:
<head>
    function autoHide() {
        $.ajax({
            'url': '/artistdo.php',
            'type': 'GET',
            'dataType': 'json',
            'data': {
                cmd: 'autoHideProduct'
            },
            'success': function () {
                alert("Success");
                return false;
            }
        });
    }
</head>

<body>
  <form action="http://off-site/form.php" method="post"
        onSubmit="return autoHide()">
    <input type="submit" value="submit"
           onMouseOver="this.style.cursor='pointer'">
  </form>

And the artistdo.php page (This is a simplified version for the sake of easy reading) :
if($get['cmd'] == 'autoHideProduct') {
    $query = mysql_query("UPDATE products SET house='0'");

    if ($query) {
        return true;
    } else {
        return false;
    }

So, if I completely remove the entire MySQL query from the artistdo.php page and replace it with nothing but return true;, the form still submits, which makes me think the problem is in the AJAX since, the artistdo.php page is definitely returning true and the alert("Success"); is being called.
If I move the return true to outside the AJAX call, the form correctly doesn't submit.
I hope this makes sense...
Thanks for any help!

A: You could use the .data() method to associate metadata with the form that will allow you to know whether you should submit it or not:
<head>
    <script type="text/javascript">
        $(function() {
            $('#myform').submit(function() {
                if ($(this).data('shouldSubmit')) {
                    return true;
                }

                $.ajax({
                    url: '/artistdo.php',
                    type: 'GET',
                    dataType: 'json',
                    context: this,
                    data: { cmd: 'autoHideProduct' },
                    success: function (result) {
                        if (result) {
                            $(this)
                                .data('shouldSubmit', true)
                                .submit();
                        }
                    }
                });

                return false;
            });
        });
    </script>
</head>

<body>
    <form action="http://off-site/form.php" method="post" id="myform">
        <!-- Form fields -->
        <input type="submit" value="submit" onMouseOver="this.style.cursor='pointer'">
    </form>
</body>

A: if I understood you correctly, this may be of some help
$('form').submit(function (event)
{
    event.preventDefault();
    //handle the rest of the logic
}

This will stop the form submission, u should call your function and submit the form if the return is true.

A: The first problem given your current code structure is that the call to $.ajax is asynchronous which means that it gets executed and then the browser moves on to the next statement and lets the $.ajax call finish "in the background".  This is why when you put the return false statement after the $.ajax call the form doesn't submit as opposed to putting the return false inside the success function of the $.ajax call.
I don't think what you want to do is really possible unless you create a global variables of some kind.  Is it possible for you to change how you are doing the form?

A: I think the problem is in this line
    if($get['cmd'] == 'autoHideProduct') {

it should be like
    if($_GET['cmd'] == 'autoHideProduct') {


text:
Q: Advice on setup for virtualization and gaming I am seeking advice on how to best manage my workstation.
My current goal is to learn about cybersecurity forensics and incident response.
I have learned that open vswitch supports port mirroring but only works on kvm-based virtualization.
At the same time I have 2 decent gpus that I want to do some gaming from time to time and also watch some movies, if I'm not mistaken, linux has poor support for 4k video acceleration.
My initial plan was to install proxmox and do gpu pass-through but so far I've been unsuccessful.
The nvidia code 43 is my nemesis.
I would appreciate if you guys could take the time to help me..
Regards,
Alex

A: You are mistaken in thinking that Linux is in any way deficient when it come to handling 4K resolutions. As somebody running 5K and 8K monitors on my Linux systems, I can assure you it works perfectly well. Especially if you are using Nvidia GPUs, as you seem to be.
To defeat the code 43 error in your Windows VM, you need to hide the fact that the virtual machine is virtual from the Nvidia driver. Nvidia do this asinine thing in their driver where it refuses to initialize a GeForce GPU if it detects a VM (but it initializes a Quadro or a Tesla just fine). I seem to recall that on proxmox you need to set the cpu: host,hidden=1 or something similar.


text:
Q: 8GB of 10GB disk on GCP VM taken by google sdk? Hello I have a GCP VM which is out of disk space (a 10 GB disk). I am using ncdu to figure out where all the space is being used.
--- / ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
.   4.3 GiB [##########] /snap
.   3.2 GiB [#######   ] /var
    2.1 GiB [####      ] /usr
.   1.7 GiB [###       ] /home
......

--- /snap ---------------------------------------------------------------------------------------------------
                         /..
    2.7 GiB [##########] /google-cloud-sdk
  624.5 MiB [##        ] /lxd
. 404.5 MiB [#         ] /core20
  356.8 MiB [#         ] /snapd
. 338.5 MiB [#         ] /core18
    4.0 KiB [          ] /bin
    4.0 KiB [          ]  README

It seems that 2.7GB is taken up by the google-cloud-sdk
and within /var/lib/snapd/snaps:
--- /var/lib/snapd/snaps ------------------------------------------------------------------------------------
                         /..
  334.8 MiB [##########]  google-cloud-sdk_310.snap
  308.6 MiB [######### ]  google-cloud-sdk_308.snap
  279.5 MiB [########  ]  google-cloud-sdk_312.snap.partial

Are these snapshot files? Can I delete them?
There are several other big folders that I don't know what they do but these are the big ones.
It's super frustrating that I've run out of space and my app has only used 2 of the 10GB. Any advice on what I can do to clean all this up would be much appreciated!

A:
Are these snapshot files? Can I delete them?

They are snap packages. You can remove them if you want. man snap will tell you how to interact with them.
snap remove <packagename> will uninstall it.
Furthermore, they take up less space than seen by du, as the content is stored in a compressed filesystem image in /var/lib/snapd. /snap is the mountpoint of the compressed filesystem.


text:
Q: Facebook Graph api 2.2 - App scoped user id uniqueness I have a database full of user Ids as primary keys prior to the upgrade to app scoped Ids.
After upgrade , could a new app scoped id ever match a previous user id ?
The only confirmation I can see on the FB developer documents is that the accounts that have approved apps prior upgrade would continue to work with user Ids.

A: No they can't. All ids are unique


text:
Q: Magento: Same price but different tax for oversea customers I'm configuring a Magento site for international sales. My requirement is to calculate tax based on the geographical location of the user but the final price of the product will remain same.
Tax is applicable to local customers only. Overseas customers will get tax-free product. Whatever be the tax amount, the final price will be fixed for all the customers.
An example:
I want to sell a Item A for $100.
Our local Tax is 10%.

*

*So local customers pay  $90.91 + $9.09 of tax

*Oversea customers will pay $100 + $0 of tax.

Is there anyway to configure this in Magento?
Because after having tried in Magento many times, I can only make

*

*local customers paying  $90.91 + $9.09 of tax,

*but overseas customer always pay $90.91 + $0 of tax (not $100).

A: Well, suppose all displaying price including Tax: 10% for local, free tax for overseas (decided by shipping address)
Create one Tax Zone & Rate rule for your country, like Austrlia with 10% Tax.
The key set is the "Enable Cross-Border Price Consistency" (Dashboard > System > Configuration > Sales > Tax > Calculation Settings > Enable Cross Border Trade )
When set it as Yes
Notes: Merchants operating across regions and geographies can show their customers a single price. Pricing is clean and uncluttered regardless of tax structures and rates that vary from country to country.
- Local customers pay $90.91 + $9.09 of tax
- Oversea customers will pay $100 + $0 of tax.

When set it as No
- Local customers paying $90.91 + $9.09 of tax,
- Overseas customer will pay $90.91 + $0 of tax (not $100).


text:
Q: Asymptotic behaviour of Fourier transform: $|F[f]|=|\lambda^{-k}F[f^{(k)}]|$ for absolutely continuous $f$ I read in Kolmogorov-Fomin's (p. 429 here) that if function $f:\mathbb{R}\to\mathbb{C}$ is such that $f^{(k-1)}$ [the $(k-1)$-th order derivative] on any finite interval and if $f,...,f^{(k)}\in L_1(-\infty,\infty)$ [i.e. they are Lebesgue-summable on $\mathbb{R}$], then$$F[f^{(k)}]=(i\lambda)^k F[f]$$where $F[f]$ is the Fourier transform defined by $F[f](\lambda)=\int_{\mathbb{R}} f(t)e^{-i\lambda t}d\mu_t$, where $\mu_t$ is the linear Lebesgue measure on $\mathbb{R}$.
I know, from the proof given in the same page, that such an equality holds for $k=1$ (lemma (3)). Provided that $f$ is absolutely continuous on any finite interval, induction guarantees that $F[f^{(k)}]=(i\lambda)^k F[f]$, as far as I understand. I do not think we may drop the hypothesis of the absolutely continuity of $f$.
Then the book, talking as if such a statement held in general, in another lemma bearing another number, (4), says that if $f^{(k)}\in L_1(-\infty,\infty)$ then $$\lim_{|\lambda|\to\infty}|F[f]|=\lim_{|\lambda|\to\infty}\frac{|F[f^{(k)}]|}{|\lambda|^k}=0.$$I think it is still intended that $f,...,f^{(k-1)}\in L_1(-\infty,\infty)$ and $f$ is absolutely continuous on any finite interval: am I right? I do not think that the hypothesis may be dropped.
This asymptotic estimate is then used to prove the following lemma (5), which says that if $f''$ exists and belongs to $L_1(-\infty, \infty)$, then $F[f]$ is [Lebesgue] absolutely integrable, but, again, I think that we must consider it under the hypothesis that $f$ is absolutely continuous on any finite interval and $f,f'\in L_1(-\infty,\infty)$. Is not that so? I should admit that this much celebrated textbook is not so easy for me to do exegesis on...
Thank you so much!!!

A: The asymptotic estimate $|F[f](\lambda)|\to 0$ holds under much weaker conditions. I can't read Kolmogorov-Fomin, so I don't know what they're claiming, but here's a proof assuming only that $f$ is in $L^1(-\infty,\infty)$.
The idea is to approximate $f$. First, we know how to show that $F[g'](\lambda) = i\lambda F[g](\lambda)$ if $g$ is $C^\infty$ and compactly supported. So for $g\in C_c^\infty$ we have
$$
|F[g](\lambda)| = \frac{|F[g'](\lambda)|}{|\lambda|}\to 0
$$
as $\lambda\to\infty$.
Since $C_c^\infty$ is dense in $L^1$ (w.r.t $L^1$-norm), given $\varepsilon>0$ we may find $g\in C_c^\infty$ with $\Vert f-g \Vert_{L^1}<\varepsilon$. Then
$$
\left|\int_{-\infty}^\infty f(x)e^{-i\lambda x}~dx\right| \leq \left|\int_{-\infty}^\infty (f(x)-g(x))e^{-i\lambda x}~dx\right| + \left|\int_{-\infty}^\infty g(x)e^{-i\lambda x}~dx\right|.
$$
So we have the bounds
$$
\left|F[f](\lambda)\right| \leq \Vert f-g \Vert_{L^1} + \left|F[g](\lambda)\right| < \varepsilon + \left|F[g](\lambda)\right|.
$$
As $|\lambda|\to\infty$ the second term goes to $0$, and since $\varepsilon>0$ was arbitrary this shows that $|F[f](\lambda)|\to 0$ as $|\lambda|\to\infty$.
Now you can do this for any number of derivatives on $g$ since $g$ is compactly supported, which gives you many more asymptotic estimates in terms of $g$ and its derivatives. Notice that we did not even use the derivative of $f$ in this proof.
On the other hand the identity $i\lambda F[f](\lambda) = F[f'](\lambda)$ is of course going to need some more regularity on $f$ than just integrability.


text:
Q: How to find original toolbar shadow in Android SDK? I am using a toolbar with an elevation of 4dp. The shadow below the toolbar isn't generated on devices older than v21. I can, of course, approximate the shadow with custom drawable but where is the exact code or drawable (XML or 9-patch) in android SDK that produces shadow under toolbar on 21 and newer devices?

A: Why do you need that file exactly?
You may just add shadow by putting it in the view with content that is under your toolbar.
@drawable/mShadow
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
   android:shape="rectangle">

<gradient android:startColor="@android:color/transparent"
          android:endColor="#88333333"
          android:angle="90"/>

</shape>


text:
Q: Python: why I can import a package in python but not in jupyter? I installed a pacakge called mgwr
pip3 install mgwr

If I do
python3
Python 3.6.8 (v3.6.8:3c6b436a57, Dec 24 2018, 02:10:22)
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.

>>> import mgwr

it works fine.
However, if I try
jupyter notebook

and I call it from the notebook it returns
ImportError: No module named mgwr

A: It's probably due to the fact that they're not running on the same environment. I've generally been successful in this general procedure:
1. Create a virtual environment
$ pip install virtualenv
$ cd project_folder
$ virtualenv my_venv

This will create the my_venv environment. Activate it with source my_venv/bin/activate and install the desired packages.
2. Add the virtual environment just created to jupyter notebook with
$ pip install ipykernel
$ ipython kernel install --user --name=my_venv

Now when you open your jupyter notebook and create a new notebook you should see the my_venv kernel as well.


text:
Q: How to measures script execution and *parsing* time? As far as I know, scripts are downloaded and executed synchronously in javascript.
Hence if we write the following code:
<script type='text/javascript'>console.time('core')</script>
<script type='text/javascript' src="guicore.js"></script>
<script type='text/javascript'>console.timeEnd('core')</script>

we'll see in console total time for download, parse and execute js.
How we can exclude parsing time? Just add similar file, but with all code commented out. More or less, this technique should work.
The problem is this just doesn't work =)
I optimized that code, reduce execution time from 90ms to 25ms, but see the same ~100±10ms time for Chrome and ~160±15ms for Firefox.
Ok, I know I could use profiler, but the question is: "how to measure js parsing time correctly" and what did I measured btw. Research.reverse-engineering is very fun, but maybe there's someone who knows that field in depth.

A: You cannot accurately measure script parse time independent of execution time using web APIs alone. Different browsers have different strategies for when they do parsing, and some of them will parse progressively as the script is executed, or even do "partial parsing" in cases where it's assumed a block of code is unlikely to immediately be executed (e.g. a function that is not an IIFE, see some details in the optimize-js README).
Using separate <script> tags is the most accurate way to at least capture both parsing and execution time. The only modification I would make to your snippet is this:
<script>
  performance.mark('start');
</script>
<script src="myscript.js"></script>
<script>
  performance.mark('end');
  performance.measure('total', 'start', 'end');
</script>

Note the use of the high-precision User Timing API which, as an added bonus, will show visualizations in the Chrome/Edge/IE dev tools (and tools like Windows Performance Analyzer and WebPageTest if you're so inclined).
Technically the 3rd <script> is not necessary, as you can just append the mark/measure to the end of the 2nd script. But the 1st <script> is certainly necessary to capture all parse time. You can verify in the dev tools that the marks/measures encompass all initial parsing and execution time.

A: I know this is kind of an old question but I came across it while looking for a solution to this myself. You can use the dev tools in the browser of your choice to look at this but if you'd like to do it in code this is the method I ended up using.
The scriptLoadParseDuration function below will take a URL to a .js file, place it into a <script> element, and log the load/parse duration to the console.
Keep in mind that this will execute the <script> you are profiling within the current DOM context. So in the example below: jQuery is still accessible in the global scope even though the script was removed. The script could be extended to do all of this in an <iframe> to isolate it though.

function scriptLoadParseDuration(url) {
  var start;
  var script = document.createElement('script');

  // <script> must be attached to the document to actually load the file
  document.querySelector('html').appendChild(script);

  // Calculate load/parse duration once script has loaded
  script.addEventListener('load', function scriptLoad() {
    // Calculate load/parse duration
    console.log('Duration: ' + (Date.now() - start) + 'ms');

    // Remove <script> from document
    script.parentElement.removeChild(script);
  }, false);

  // Get current time in milliseconds
  start = Date.now();

  // Setting the `src` starts the loading. Math.random is used to make sure it is an uncached request
  script.src = url + '?' + Math.floor(Math.random() * 9e9);
}

var url = 'https://code.jquery.com/jquery-3.0.0.min.js';

scriptLoadParseDuration(url);

Here is an example showing that jQuery is still in the global scope after the <script> removal.

function scriptLoadParseDuration(url) {
  var start;
  var script = document.createElement('script');

  console.log('`jQuery` before attaching: ' + typeof jQuery);

  // <script> must be attached to the document to actually load the file
  document.querySelector('html').appendChild(script);

  // Calculate load/parse duration once script has loaded
  script.addEventListener('load', function scriptLoad() {
    // Calculate load/parse duration
    console.log('Duration: ' + (Date.now() - start) + 'ms');

    console.log('`jQuery` once attached: ' + typeof jQuery);
    // Remove <script> from document
    script.parentElement.removeChild(script);
    console.log('`jQuery` after detach: ' + typeof jQuery);
  }, false);

  // Get current time in milliseconds
  start = Date.now();

  // Setting the `src` starts the loading. Math.random is used to make sure it is an uncached request
  script.src = url + '?' + Math.floor(Math.random() * 9e9);
}

var url = 'https://code.jquery.com/jquery-3.0.0.min.js';

scriptLoadParseDuration(url);

A: Open up Chrome and open the developer tools, the go to the "Timeline" tab. If you press the record button (filled in circle, bottom left) then reload the page it'll give you a fairly detailed timeline, broken down into specific types of activity (Send Request, Parse, Evaluate), timed down to the microsecond.

A: Very old question with a relatively new answer.
Date.now() returns a timestamp with millisecond accuracy. For an application to run at 60FPS, it must update the frame every 16ms. Our millisecond meter may not be accurate enough.
Introducing the Performace API in modern JS browsers, this allows for floating-point timestamps accurate to the microsecond.
Instead of Date.now() use window.performance.now() for measurements, there's a good guide on using the Performance API on HTML5Rocks.

A: Chrome DevTools actually has a hidden flag that shows V8 Parse and Compile time!
https://developers.google.com/web/fundamentals/performance/optimizing-content-efficiency/javascript-startup-optimization#parsecompile
Outcome looks like this:

A quick guide is also available in the doc in the blue section below:

After you enable the feature, you can profile a page and then click on "Bottom-Up" tab on the Performance tab in Chrome DevTools, and then make sure you "Group by Activity", and you should see the Compile and Parse time now.
Enjoy!


text:
Q: how to deal with changing ips of docker compose containers? I've setup an app where a nodejs backend has to communicate with a rasa chatbot backend through a react frontend. All services are running through the same docker-compose. Being a docker beginner there are some things I'm not sure about:
communication between host and container is done using the container's ip

*

*browser opening the local react server running on localhost:3000 or 172.22.0.1:3000

*browser sending a request to the express backend on localhost:4000 172.22.0.2:4000
however communication between two docker containers is done is the container's name:

*

*rasa server conmmunicating with the rasa custom action server through http://action_server:5055/webhooks

*rasa custom action server communicating with the express backend through http://backend_name:4000/users/
my problem is that when I need to contact the rasa backend from my react front end I need to put the rasa docker container's ip which (sometimes) changes upon docker-compose reinitialization. To workaround this I do a docker inspect -f '{{range.NetworkSettings.Networks}}{{.IPAddress}}{{end}}' app_rasa_1 to get the ip and manually change it into the react frontend.
is there a way to avoid changing the ip alltogether and using the container name (or an alias/link) or what would be a way to automate the change of the container's ip in the react frontend (are environment variables updated via a script an option?)

A: Completely ignore the container-private IP addresses.  They're implementation details that have several practical problems, including (as you note) them changing when a container is recreated.  (They're also unreachable on non-Linux hosts, or if the browser isn't on the same host as the containers.)
You show the correct patterns in your question.  For calls between containers, use the container names as host names (this setup is described more in Networking in Compose.  For calls from outside containers, including from browser-based applications, use the host's DNS name or IP address and the first number from the ports: you publish.
If the browser application needs to contact a back-end server, it needs a path to do this.  This could be via published ports:, or one of your other components could proxy the request to the service (maybe using the express-http-proxy middleware).
A dedicated container that only proxies to other backend services is also a useful pattern (Docker Nginx Proxy: how to route traffic to different container using path and not hostname includes some examples), particularly since this will let you use path-only URLs like /api or /rasa in your browser application.  If the React application is served from http://localhost:8080/, and the main backend is http://localhost:8080/api, then you can just make HTTP requests to /api and they will be interpreted relative to the page's URL.  This avoids the hostname problem completely, so long as your reverse proxy has path-based routes to every container you need to directly contact.


text:
Q: Where can I find site community blogs? At one point, all sites had blogs, although this was later discontinued for the majority of sites. I've also heard that some stacks still run their own blogs!
Where can I find these site blogs?
Return to FAQ index

A: Unofficial Site Blogs

*

*An Eye on the Universe (Astronomy)

*Language Learning Blog

*One Minute Reviews (Literature)

*The Retrocomputing Blog

*Science Fiction & Fantasy Community Blog

*TeX Talk

*Universe Factory (Worldbuilding)

*CGCC Blog
Blog Overflow Archives

*

*Ask Different Community Blog

*Arqade Community Blog (previously Gaming Stack Exchange)

*Aviation Community Blog

*Stack Exchange Bicycles Blog

*Eschewmenical (Christianity)

*Stack Exchange Stats Blog

*Database Administrators Community Blog

*Home Improvement Blog

*English Language & Usage Community Blog

*Geographic Information Systems Blog

*Islam Community Blog

*Mathematica Community Blog

*Mathematics Community Blog

*Photography Community Blog

*Seasoned Advice Community Blog

*IT Security Community Blog

*The Stack Exchange Sysadmin Blog

*Programmers Community Blog

*Super User Community Blog

*CS Theory Community Blog


text:
Q: Перстал работать код. В чем может быть ошибка? Файл semantic.txt - текстовой файл с кириллицей и латиницей, представляющий из себя 1тыс строк текста на кириллице. Задача кода - вывести 15 случайных строк из текстового файла, предварительно перемешав строки. Нижеприведенный код еще месяц назад работал нормально. Но, сейчас почему-то перестал работать. В чем может быть причина?
<?php
$arr = file('https://site.ru/themes/semantic.txt');
shuffle($arr);
$res = array_slice($arr, 0, 15);
foreach($res as $str){
  echo htmlspecialchars($str);
}
?>

A: Не могу предположить, что у вас там, но тем не менее, у меня работает как вы описали. Выводит 15 строк. Cкорее всего, кодировка файла изменена, попробуйте так:
<?php
$arr = file('http://localhost/semantic.txt');
shuffle($arr);
$res = array_slice($arr, 0, 15);
foreach($res as $str){
    $tempStr = mb_convert_encoding($str, 'UTF-8', mb_detect_encoding($str));
    echo htmlspecialchars($tempStr, ENT_NOQUOTES, 'UTF-8');
}
?>


text:
Q: AngularJS "Controller Undefined error" while displaying the scope value in .php extension file while displaying the scope value in file with ".php" extension gives an error of undefined controller, while it displays the scope value properly.
Sample Code:

      {{name}}

The above code, shows the value of name in browser correctly , but in console gives the following error
"angular.min.js:103 Error: [ng:areq] http://errors.angularjs.org/1.3.11/ng/areq?p0=DemoCtrl&p1=not%20a%20function%2C%20got%20undefined"
What is wrong with the code? The angular version used is 1.3.11


text:
Q: NServiceBus generic message handlers not found using conventions unobtrusive mode I am using dotnetcore2.1 app with aspnetcore 2.1.1.
Also I'm using the Community.NServiceBus.WebHost for hosting in that version as suggested in the documentation.
I am trying to have a clean architecture not to depend directly on NServiceBus, therefore I'm using adapters and unobtrusive mode for my commands. I am getting the following exception and immediate retries attempts.
System.InvalidOperationException: No handlers could be found for message type: WebApi.Models.Commands.ProcessBlob

This is how I register NServiceBus with this custom extension
public static IServiceCollection AddNServiceBus(this IServiceCollection services, IConfiguration configuration)
{
    var endpointName = configuration.GetValue<string>("NServiceBus:EndpointName");
    var connectionString = configuration.GetValue<string>("NServiceBus:ConnectionString");

    var endpointConfiguration = new EndpointConfiguration(endpointName);
    endpointConfiguration.SendFailedMessagesTo("error");
    endpointConfiguration.EnableInstallers();
    var conventions = endpointConfiguration.Conventions();
    conventions.DefiningMessagesAs(type => type.Namespace != null && type.Namespace.Contains(".Commands"));

    //var transport = endpointConfiguration.UseTransport<AzureServiceBusTransport>();
    //transport.ConnectionString(connectionString);
    endpointConfiguration.UseTransport<LearningTransport>();
    services.AddNServiceBus(endpointConfiguration);

    services.AddTransient<ICommandBus, CommandBusAdapter>();

    services.AddTransient<ICommandHandler<ProcessBlob>, ProcessBlobHandler>();

    return services;
}

Then at Startup.cs
public void ConfigureServices(IServiceCollection services)
{
    services
        .AddNServiceBus(Configuration)
        .AddMvc()
        .SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
}

I've got the following adapter for sending commands
public class CommandBusAdapter
    : ICommandBus
{
    private readonly IMessageSession _messageSession;

    public CommandBusAdapter(IMessageSession messageSession)
    {
        _messageSession = messageSession;
    }

    public Task Send<TCommand>(TCommand command)
        where TCommand : class
    {
        return _messageSession.SendLocal(command);
    }
}

and this is my generic message handler adapter that I use to handle ANY command and use a service locator to determine the specific command handler to delegate.
public class CommandHandlerAdapter<TCommand>
    : IHandleMessages<TCommand>
    where TCommand : class
{
    private readonly IServiceProvider _serviceProvider;

    public CommandHandlerAdapter(IServiceProvider serviceProvider)
    {
        _serviceProvider = serviceProvider;
    }

    public Task Handle(TCommand message, IMessageHandlerContext context)
    {
        var commandHandlerType = typeof(ICommandHandler<TCommand>);
        var commandHandler = (ICommandHandler<TCommand>)_serviceProvider.GetService(commandHandlerType);
        return commandHandler.Handle(message);
    }
}

As you can see, the command handler adapter is not registered (I would expect NServiceBus to detect it and register it automatically even if it's generic).
I use a convention where the command messages are any DTO under a namespace that contains .Commands
Am I trying something impossible or is there any workaround that allows me to keep using this generic command handler adapter approach?

UPDATE 1: In other words, the following handler works fine without any additional registration.
public class CommandHandlerAdapter
    : IHandleMessages<ProcessBlob>
{
    private readonly ICommandHandler<ProcessBlob> _processBlobHandler;

    public CommandHandlerAdapter(ICommandHandler<ProcessBlob> processBlobHandler)
    {
        _processBlobHandler = processBlobHandler;
    }

    public Task Handle(ProcessBlob processBlob, IMessageHandlerContext context)
    {
        return _processBlobHandler.Handle(processBlob);
    }
}

But I want a way to have this command handler adapter generic, because it does the same for every command (gets the instance of the specific command handler and delegates on it to handle the message)


text:
Q: Ho do you change directory and run a command in ansible? Hi  I am struggling to understand why this code is saying that the directory does not exist
on the system I see
root@Production:~# ls -l /home/azureuser/directory-with-stuff/

and can see that the path exists
however, in my ansible code, the stat tells me that the directory does not exist
the code is as follows
Project_add\roles\common\tasks
main.yml
Developer_project_setup.yml

vars
main.yml

in the Developer_project_setup.yml which runs via an include in the main.yml
- name: Running make libs to build libraries
  command: make libs
  args:
    chdir: "{ file_path_home }"
  when: infra_problem_dir_check.stat.exists

- name: Running make clean for static tarballls
  command:  make clean all
  args:
    chdir: "{ file_path_home }"
  when: infra_problem_dir_check.stat.exists

within the vars.yml file
file_path_home: /home/azureuser/directory-with-stuff

I have also included a stat to check but this also returns false to my astonishment
- stat:
    path: "{ file_path_home }"
  register: infra_problem_dir_check

I have also used the following to try and debug and the results are interesting in the sense that i can see the folder
- name: checking working directory
  command: pwd
  register: test
- debug: msg={{ test.stdout }}

- name: checking working directory contents
  command: ls -l
  register: test
- debug: msg={{ test.stdout }}

so when I run the playbook I get
TASK [Project_add/roles/common : stat] **************************************************************************************************************************************************************************************************************************************************************************************
ok: [client_Host_9d63] => {"changed": false, "stat": {"exists": false}}

TASK [Project_add/roles/common : checking working directory contents] *******************************************************************************************************************************************************************************************************************************************************
changed: [client_Host_9d63] => {"changed": true, "cmd": ["ls", "-l"], "delta": "0:00:00.003163", "end": "2020-03-11 23:00:50.782252", "rc": 0, "start": "2020-03-11 23:00:50.779089", "stderr": "", "stderr_lines": [], "stdout": "total 4\ndrwxr-xr-x 7 azureuser azureuser 4096 Mar  9 20:14 directory-with-stuff", "stdout_lines": ["total 4", "drwxr-xr-x 7 azureuser azureuser 4096 Mar  9 20:14 directory-with-stuff"]}

TASK [Project_add/roles/common : debug] *************************************************************************************************************************************************************************************************************************************************************************************
ok: [client_Host_9d63] => {
    "msg": "total 4\ndrwxr-xr-x 7 azureuser azureuser 4096 Mar  9 20:14 directory-with-stuff"
}

TASK [Project_add/roles/common : Running make libs to build libraries] ******************************************************************************************************************************************************************************************************************************************************
skipping: [client_Host_9d63] => {"changed": false, "skip_reason": "Conditional result was False"}

TASK [Project_add/roles/common : Running make clean for static tarballls] ***************************************************************************************************************************************************************************************************************************************************
skipping: [client_Host_9d63] => {"changed": false, "skip_reason": "Conditional result was False"}

No idea why it says it says the folder doesn't exist, can anyone shed light on what I'm doing wrong?

A: I think its syntax issue. Use double instead of single.i.e '{{' instead of '{"
args:
    chdir: "{{ file_path_home }}"

- stat:
    path: "{{ file_path_home }}"
  register: infra_problem_dir_check


text:
Q: How to split a string along a line in C? I've been following the Cherno's opengl series in c++ recently and wanted to give it a try in c. One thing I have been having a problem with is reading in the contents of the shader files so I can compile them. While I can read in the whole file, in the videos, it is recommended to use one file for both the vertex and fragment shaders. I need a way to break the file into two separate strings, one for the vertex shader, and one for the fragment shader. To help with this, at the top of each shader I added "#shader vertex" and "#shader fragment" to know when I need to split, as was recommended in the video. However, I don't really know how to go about this in c as the video was in c++ using fstream rather than c's file api.
It would be best to be able to read the string or file line by line to check if the markers are found and then write the contents / copy from the buffer to either the vertex or fragment shader strings as needed.
So far I have this
static char* FileToString(const char* filePath)
{
    //Load .shader file into two separate strings (one for vertex and one for fragment)
    FILE* source = fopen(filePath, "r");
    if(source == NULL)
    {
        printf("Failed to open %s!\n", filePath);
    }

    char* buffer = 0;
    long length;
    fseek(source, 0, SEEK_END);

    length = ftell(source);

    fseek(source, 0, SEEK_SET);
    buffer = (char*)malloc(length);

    if(buffer)
    {
        fread(buffer, 1, length, source);
    }

    fclose(source);

    return buffer;
}

Thanks for any help!

A: assuming vertex is first, do this after you read the whole file:
char *vertex = buffer + sizeof("#shader vertex") - 1;
char *fragment = strstr(vertex, "#shader fragment");
*fragment = '\0';
fragment += sizeof("#shader fragment") - 1;

this is the easiest way, after that you get 2 pointers, each pointing to a string containing your data. Assuming the data can be read as text. If it's binary data that can contain 0's, your approach of adding text will not easily work


text:
Q: Javascript. Escape 'form' tag in concat I want to add variable into my js code
var x = 1;
$(phrases).append('<form:input path="bla + ' x ' + bla" ...);

but I am getting:

NumberFormatException: For input string: "+x+"

If I am using just input  it is working
var x = 1;
$(phrases).append('<input path="bla + ' x ' + bla" ...);

Why this is happening?

A: <form:input> is server-side Spring code. You can't generate it using client side JavaScript. It is too late for that, the code has already left the server.
You need to work with the HTML DOM, not Spring.


text:
Q: Stellaris LM3S8962 Port E Interrupt I am new to Stellaris LM3S8962. I want to inquire about how to write 4 separate ISRs to handle interrupts originated from 4 buttons Up, Down, Left, Right. I have tried but my code always fell into FaultISR.
Thanks!

A: https://www.dropbox.com/s/5j5il9kt324o943/Lab%202.rar?dl=0
The link above is my project.
It works fine, but when I add the following statements to the Startup task it would fall into FaultISR
// Configure the UART
SysCtlPeripheralEnable(SYSCTL_PERIPH_UART0);
SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOA);
// Enable processor interrupts.
IntMasterEnable();
// Set GPIO A0 and A1 as UART pins.
GPIOPinTypeUART(GPIO_PORTA_BASE, GPIO_PIN_0 | GPIO_PIN_1);
// Configure the UART for 9600, 8-N-1 operation.
UARTConfigSetExpClk(UART0_BASE, SysCtlClockGet(), 9600,
                        (UART_CONFIG_WLEN_8 | UART_CONFIG_STOP_ONE |
                         UART_CONFIG_PAR_NONE));
// Enable the UART interrupt.
IntEnable(INT_UART0);
UARTIntEnable(UART0_BASE, UART_INT_RX | UART_INT_RT);


text:
Q: How i can do like this? Send request to webpack, if response was 404, then request to webpack "/inidex.html":? How i can do like this? Send request to webpack, if response was 404, then request to webpack "/inidex.html":
server {
  listen 80;

  location @webpack_dev_server {
    proxy_pass http://localhost:3000;
    proxy_set_header Host $host;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection "upgrade";
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
  }

  location / {
    try_files @webpack_dev_server @webpack_dev_server/index.html =404;
  }
}

How to configure webpack historyApiFallback I know, the question is how to configure nginx to check for the existence of a "file" on another server =)
How i can check "if another server return 404, then try request to another server another_server/index.html? its possible with nginx?


text:
Q: Randomly show paired elements Is there a way to pair elements with the same class without wrapping

1

2

3

4

5

6

then randomly show paired element on page refresh/load
so the output would be 1 2 or 3 4 or 5 6
FIDDLE here

A: You can use that :
var pairs = $('.pair1, .pair2, .pair3');

var random = Math.floor(Math.random() * pairs.length / 2)+1;
var output = pairs.filter('.pair'+random)

output.show();

Since you have pairs, you'll need to divid the length by 2.
Then, when you have your random number, you get the pair number.
http://jsfiddle.net/tQ5ZP/2/

A: Try,
var pairs = ['.pair1', '.pair2', '.pair3'];
var div = $("div[class^='pair']");

var random = Math.floor(Math.random() * pairs.length);
var output = div.filter(pairs[random]);

output.show();

DEMO

A: Working demo
var pairs = ['.pair1','.pair2','.pair3']; // Create an array of strings

var random = Math.floor(Math.random() * pairs.length);
var output = pairs[random]; // choose a string at a random index in your array

$(output).show(); // use random string as selector

Or, if you have an arbitrary number of pairs you could construct your array on the fly with something like this:
Working demo
var pairs = [];

$('div').each(function() {
    var theClass = $(this).attr('class');
    pairs.push('.' + theClass);
});

var random = Math.floor(Math.random() * pairs.length);
var output = pairs[random];

$(output).show();


text:
Q: Clickable icon with link I have an icon list made of social media but they're only clickable on the letter of the icon, I want it to be clickable on any spot but I have to click on the "F" of facebook:

On the facebook icon, I have to click literally on the "F", it doesn't work if I click on the blue spot, how can I fix this? Here's my code:

A: A possible workaround will be using css. anchor is inline element and it only wraps the icon. We need anchor to cover whole area in li
using css
ul li a{
    display:inline-block;
    width:100%;
    height:100%;
}

A:

li{
 border:1px solid red;
 display: inline-block;
}
.fa{
 padding:15px;
 padding-bottom: 15px;
 padding-top:15px;

}
a{
 display: block;
}

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">

A: I would use inherit for de with and height of the li items. I used flexbox to align everything in the center. When hyperlinks are created for the other icons, you can remove the flexbox settings for li.

li {
  width: 50px;
  height: 50px;
  background-color: pink;
  border: thin solid black;
  list-style: none;
  display: flex;
  justify-content: center;
  align-items: center;
}

li>a {
  width: inherit;
  height: inherit;
  display: flex;
  justify-content: center;
  align-items: center;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" />


text: Q: SSAS to BI Tools via web service or Direct? I am building a application that has data in MSSQL, which is then transformed in SSAS cubes. My end goal is to expose the SSAS cubes to any BI tool including any custom built web app. Should I expose my SSAS cubes directly or have a interface in between that expose the SSAS cubes via REST Services. Please advise. There is authentication that i need to take care about.


text:
Q: Variational Calculus on unbounded domains reference I've been studying Variational Calculs from Differential Equations and Variational Calculus by L. Elsgoltz. Everything is ok, but the whole theory is developed bounded intervals of the real numbers, so I'm asking for a reference book where I can study the theory on unbounded intervals or even unbounded domains of $\mathbb{R}^n$. Can one adaptated the same proofs of the bounded case, but now using Dominated convergence theorem to interchange the sign integral and the derivative? It would require stronger hypothesis, but I think it would work.
Thanks in advance!


text:
Q: SSIS underlying connection was closed: An unexpected error occurred on a send I am trying to make a call to an API within a SSIS package. I am able to use the same code in a regular unit test class and everything works as expected. I tried some of the recommendations I've seen in stack overflow but no luck.
It fails at the GetRequestStream()
Error: The underlying connection was closed: An unexpected error occurred on a send.
Inner Error Message: Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host.
Code:
            var request = (HttpWebRequest)WebRequest.Create(requestURL);
            var muaRequest = new MUARequest
            {
                designationType = "MUAP"
            };
            var data = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(muaRequest));

            request.Method = "POST";
            request.ContentType = "application/json";
            request.ContentLength = data.Length;
            request.Timeout = Timeout.Infinite;
            request.KeepAlive = false;
            request.ProtocolVersion = HttpVersion.Version10;
            ServicePointManager.Expect100Continue = true;
            System.Net.ServicePointManager.SecurityProtocol = System.Net.ServicePointManager.SecurityProtocol | System.Net.SecurityProtocolType.Tls12;
            using (var stream = request.GetRequestStream())
            {
                stream.Write(data, 0, data.Length);
            }

            //var response = (HttpWebResponse)request.GetResponse();
            using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
            {
                if (response.StatusCode == HttpStatusCode.OK)
                {
                    using (var responseStream = response.GetResponseStream())
                    {
                        using (var reader = new StreamReader(responseStream))
                        {
                            var content = reader.ReadToEnd();
                            results = JsonConvert.DeserializeObject<Results>(content);
                        }
                    }
                }
                else
                {
                    results.ErrorCode = "Http Request Failed.";
                }
            }

A: The declaration of the security protocol needs to be called before the creation of the web request. After that it works


text:
Q: How to randomly generate objects from multiple arrays with user input in PHP? I am attempting to create a generater where the user inputs how many items to generate. For each time, a number from 1 to 100 is generated. Depending on the result, an item is randomly selected from one of three arrays. It should loop as needed and then display the results. I have partial code below as I tried to follow the logic.
<form action='random.php' method='POST' id='random'>

        Number of items:
        <input type='text' name='randitem'>
        <button type="submit"Generate</button>

<?php

$roll = rand(1, 100);

    if $roll < 50

        $commonItem = array(citem1, citem2, citem3);

    if $roll => 50 and < 95

        $uncommonItem = array(uitem1, uitem2, uitem3);

    if $roll => 95

        $rareItem = array(ritem1, ritem2, ritem3);
?>

A: Here's an idea, where you can randomly choose an item from each array based on which array to choose from (also random, per your sample code):
<?php
    $commonItems = array('citem1', 'citem2', 'citem3');
    $uncommonItems = array('uitem1', 'uitem2', 'uitem3');
    $rareItems = array('ritem1', 'ritem2', 'ritem3');
    $roll = rand(1,100);

    if ($roll < 50) {

         $size = count($commonItems) - 1;
         $index = rand(0,$size);
         $item = $commonItems[$index];

    } elseif ($roll >= 50 && $roll < 95) {

         $size = count($uncommonItems) - 1;
         $index = rand(0,$size);
         $item = $uncommonItems[$index];

    } else {

         $size = count($rareItems) - 1;
         $index = rand(0,$size);
         $item = $rareItems[$index];

    }

    echo $item;
?>

Here's a refactored version with a function that handles the repetitive functionality in the if statements:
<?php
    $commonItems = array('citem1', 'citem2', 'citem3');
    $uncommonItems = array('uitem1', 'uitem2', 'uitem3');
    $rareItems = array('ritem1', 'ritem2', 'ritem3');

    function getItem($itemArray) {
         $size = count($itemArray) - 1;
         $index = rand(0,$size);
         return $itemArray[$index];
    }

    $roll = rand(1,100);
    if ($roll < 50) {
        $item = getItem[$commonItems];
    } elseif ($roll >= 50 && $roll < 95) {
        $item = getItem[$uncommonItems];
    } else {
        $item = getItem[$rareItems];
    }

    echo $item;
?>

EDIT: I missed the part about how you input a number of items, so here's that
    // Check to see if form was submitted with something in randitem
    if (isset($_POST['randitem'])) {

        $commonItems = array('citem1', 'citem2', 'citem3');
        $uncommonItems = array('uitem1', 'uitem2', 'uitem3');
        $rareItems = array('ritem1', 'ritem2', 'ritem3');

        function getItem($itemArray) {
            $size = count($itemArray) - 1;
            $index = rand(0,$size);
            return $itemArray[$index];
        }

        // loop number of times set in form
        foreach ($i = 0; $i < $_POST['randitem']; $i++) {

            $roll = rand(1,100);
            if ($roll < 50) {
                $item = getItem[$commonItems];
            } elseif ($roll >= 50 && $roll < 95) {
                $item = getItem[$uncommonItems];
            } else {
                $item = getItem[$rareItems];
            }

            echo $item . "
"; // will print each item on its own line
        }
    }
?>

Note: this will do nothing if the form is submitted without a number, so consider changing the input type to "number" or doing some other validation to the form to ensure that only a number is sent to the PHP


text:
Q: Struggling to make a bar graph on 'R' I'm trying to make a really basic bar graph on 'R' and can't seem to get it to work. The data is just made up data for a proposal for an experiment we are going to do for my Animal Physiology paper at University. I just want a bar graph to show the number of days it take Drosophila larvae to hatch under different conditions.
Condition 1: 11 days
Condition 2: 11 days
Condition 3: 11 days
Condition 4: 10 days
Condition 5: 8 days
Condition 6: I don't expect to go anywhere so just do it as no days or something.

So I started by importing the data into Rcmdr.
Then I loaded the sciplot package and put in the code:
bargraph.CI (Treatment, Days, data = Bargraph,
           xlab = "Condition", ylab = "Number of days")

And it came up with this error:
Warning in arrows(xvals, if (lc) CI.L else mn.data, xvals, if (uc) CI.H else mn.data,  :
  zero-length arrow is of indeterminate angle and so skipped
Warning in arrows(xvals, if (lc) CI.L else mn.data, xvals, if (uc) CI.H else mn.data,  :
  zero-length arrow is of indeterminate angle and so skipped
Warning in arrows(xvals, if (lc) CI.L else mn.data, xvals, if (uc) CI.H else mn.data,  :
  zero-length arrow is of indeterminate angle and so skipped
Warning in arrows(xvals, if (lc) CI.L else mn.data, xvals, if (uc) CI.H else mn.data,  :
  zero-length arrow is of indeterminate angle and so skipped
Warning in arrows(xvals, if (lc) CI.L else mn.data, xvals, if (uc) CI.H else mn.data,  :
  zero-length arrow is of indeterminate angle and so skipped
Warning in arrows(xvals, if (lc) CI.L else mn.data, xvals, if (uc) CI.H else mn.data,  :
  zero-length arrow is of indeterminate angle and so skipped

A: I've had a similar problem when using plotmeans() to get confidence intervals about a mean. I've fixed the problem by reducing the point size by using windows(pointsize=1) to create a graphic device with a small point size, which effectively increases the resolution so small bars can now be plotted.
Unfortunately this makes all your other text too small, so you need to use functions like title() and axis(), with arguments like line, tck and their relevant cex arguments to adjust them.
You might also just try a larger device e.g. windows(width=20, height=20), but this won't always work.


text:
Q: Escape characters inside $_POST I'm trying to solve this issue for an hour and i have no more solutions.
I need to form a sql statement using some variables and i think i need to escape the quotes inside $_POST because i get an error (Parse error: syntax error, unexpected '"')
Help!!
Thanks
$counter=$_POST["counter"];

$x=1;
$p="('','$code','$procedure0','$check0')";

while($x<$counter)
{
$p.=",('','$code','$_POST["check".$x]','$_POST["procedure".$x]')";
$x++;
};

...

$sql="INSERT INTO `proceduri` VALUES $p;";

A: Please notice that your $_POST array is inside the query. Correct syntax:
for ($x = 0; $x < $counter; $x++) {
    if ($x)
        $p .= ',';

    $p.="('','$code','" . htmlspecialchars($_POST["check".$x], ENT_QUOTES) . "','" . htmlspecialchars($_POST["procedure".$x], ENT_QUOTES) . "')";
}

I have added htmlspecialchars func to sanitize variables before sending them to SQL server - this will prevent some possible SQL injection. Please read this to do it best way:
How can I prevent SQL injection in PHP?

A: $counter = $_POST["counter"];

$x = 1;
$p = "('','$code','$procedure0','$check0')";

while($x<$counter) {
    $p.= ",('','$code','{$_POST["check".$x]}','{$_POST["procedure".$x]}')";
    $x++;
};

...

$sql="INSERT INTO `proceduri` VALUES $p;";

While this might work, please consider using a parameterized approach.


text:
Q: AWS APIGateway - Display resources (endpoints) for HTTP API from AWS console When I create REST API via APIGateway, I have a beautiful dashboard to allows me to see different endpoints:

Problem:
When I create HTTP API via APIGateway, I can't see my different endpoints like below:

My need and my goal:
I want to document my API resources in order to generate a swagger and to be able to make requests directly in the swagger.
I don't want to use S3 solution.
I used Cloudfront to make a required authentication before accessing swagger.
Thank's in advance :)
EDIT: @eli6, the problem is:
When I click on Routes, I have only this:

A: On the menu to the left on the HTTP API view, you can click on "Routes" to see the different endpoints, or on "Export" to export their definition in the OpenAPI 3 format. OpenAPI 3 can be imported and used with the Swagger tools.


text:
Q: What is the value of "a" if the area of triangle is 9.
What is the value of "a" if the area of triangle is 9.

I know it looks easy but I find different answers for "a".I hope someone could help me.

A: Well, we have a function that looks like:
$$\text{y}\left(x\right)=\text{a}\cdot x+\text{b}\tag1$$
For the area we can write:
$$\mathcal{A}=\int_0^{x_1}\text{y}\left(x\right)\space\text{d}x=\int_0^{x_1}\left(\text{a}\cdot x+\text{b}\right)\space\text{d}x=\frac{x_1\cdot\left(\text{a}\cdot x_1+2\cdot\text{b}\right)}{2}=9\tag2$$
So, for $x_1$ you get:
$$x_1=\frac{-\text{b}\pm\sqrt{18\cdot\text{a}+\text{b}^2}}{\text{a}}\tag3$$
Now, you can set up a system of equations using:

*

*When $x=0$:
$$\text{y}\left(0\right)=\text{a}\cdot0+\text{b}=\text{b}\tag4$$

*When $x=x_1$:
$$\text{y}\left(x_1\right)=\text{a}\cdot x_1+\text{b}=\text{a}\cdot\frac{-\text{b}\pm\sqrt{18\cdot\text{a}+\text{b}^2}}{\text{a}}+\text{b}=\pm\sqrt{18\cdot\text{a}+\text{b}^2}\tag5$$


text:
Q: Why doesn't icon show after ellipses inside a table row? I have the following scenario:

 long text

I am able to see ellipses when the window size is small but the icon never shows with the ellipses.
When the window is maximized it should expand the text or display full text along with icon on right, immediately after text.
For example
A small window displayed like:

Text text text text text text text text text text text text text...[ICON]
text text text text text text text text text[ICON]

When Maximized - no ellipses

Text text text text text text text text text text text text text text [ICON]
text text text text text text text text text[ICON]


text:
Q: sed nested group and backreferences Now I have one simple file I wanna sed on:
~ cat sample
##tag##
xxxxxxx
xxxxxxx
##tag##

What I expect is to remove the ##tag## line on pair and leave the middle stuff alone. I can do this (except there's one empty line at bottom):
~ sed -r 'N;N;N; s/##tag##\n((.*\n)*)##tag##/\1/' sample
xxxxxxx
xxxxxxx

But the tag line is not always as neat as I want, there's another file:
~ cat sample2
##tag###dklxjexx
xxxxxxx
xxxxxxx
asdf##tag###xosy

I know you got my point, still I wanna remove the tag line:
~ sed -r 'N;N;N; s/##tag.*\n((.*\n)*).*tag##/\1/' sample2

But I got nothing print! How come??
I'm really looking forward for this q, Thanks for your time and forgive my poor English :)
enter image description here
so is . matches \n? How's above img come?

A: Try using [^\n]* instead of .*:
sed -r 'N;N;N; s/[^\n]*##tag[^\n]*\n(.*)\n[^\n]*tag##.*/\1/' sample2

Also, you need to take account of additional characters before/after the '###tag##' marker.

A: This might work for you (GNU sed):
sed '/##tag##/,//{//d}' file

To keep details on the tag lines as well, use:
sed '/##tag##/,//{s///}' file


text:
Q: Boost value depending on number of common terms Assuming we have index called users and each of them have hobbies stored as array of strings like :["basketball", "games"].
We want to fetch users with common hobbies, although we want to boost users with more than one mutual hobby.   Let's say if it is 1 common hobby, then boost value should be 1, if it is 2 common hobbies then boost should be 3 and if it is 3 common hobbies or more it should be 5.
Is it possible with terms_set query? Should it be somehow wrapped with function_score?
      terms_set: {
        hobbies: {
          terms: userDoingQuery.hobbies,
          minimum_should_match_script: {
            source: ???,
          },
          boost: ???,
        },
      },


text:
Q: Can we prevent Azure LogicApp trigger from firing when deploying I've created a script to create new LogicApps using PowerShell and deploy them to my Azure ResourceGroup. It uses a schedule recurrence and calls an action on these specific triggers.
The script works and gets the job done (I get to create and update my LogicApp). My issue however is that the LogicApp is triggered every time I do an update in addition of using the recurrence trigger.
Among things I've tried, I've attempted to disable, update then re-enable, but sadly it just triggers as soon as it is enabled back.
The reason around this is I want to run the action on specific time only, and it doesn't match the moment I'm deploying it.
Is there a way to prevent the Logic App from triggering?
If it helps, I am using the New-AzResourceGroupDeployment cmdlet. I've browsed the documentation but there doesn't seem to be any mention as to whether I want to run it immediately or not.

A: If you set the Start time parameter, that should resolve your issue:


text:
Q: getchar does not stop when using scanf I have a difficulty understanding getchar(). In the following program getchar works as expected:
#include <stdio.h>

int main()
{
    printf("Type Enter to continue...");
    getchar();
    return 0;
}

However, in the following program, getchar does not create a delay and the program ends:
#include <stdio.h>

int main()
{
    char command[100];
    scanf("%s", command );
    printf("Type Enter to continue...");
    getchar();
    return 0;
}

I have the following weired workaround, which works, but I don't understand why:
#include <stdio.h>

int main()
{
    char command[100];
    int i;
    scanf("%s", command );
    printf("Type Enter to continue...");
    while ( getchar() != '\n') {
      i=0;
    }
    getchar();
    return 0;
}

So my questions are:
  1. What is scanf doing?  Why does scanf do this ?
  2. Why is my work around working?
  3. What is a good way to emulate the following Python code:
raw_input("Type Enter to continue")

A: Whitespace is a delimiter for 5y3 %s format specifier, and newline is regarded as whitespace, so it remains buffered. Console input is normally line oriented, so a subsequent call to getchar() will return immediately because a 'line' remains buffered.
scanf("%s", command );
while( getchar() != '\n' ){ /* flush to end of input line */ }

Equally if you use getchar() or %c to get a single character you normally need to flush the line, but in this case the character entered may itself be a newline so you need a slightly different solution:
scanf("%c", ch );
while( ch != '\n' && getchar() != '\n' ){ /* flush to end of input line */ }

similarly for getchar():
ch = getchar();
while( ch != '\n' && getchar() != '\n' ){ /* flush to end of input line */ }

The sensible thing to do of course is to wrap these solutions into stand-alone specialised input functions that you can reuse and also use as a place to put common input validation and error checking code (as in Daniel Fischer's answer which sensibly checks for EOF - you would normally want to avoid having to duplicate those checks and error handling everywhere).

A: I'd rather first use fgets and then use sscanf to parse the input. I have been doing this stuff like this for a long time and the behaviour has been more predictable than using plain scanf.

A: The input is only sent to the program after you typed a newline, but
scanf("%s", command );

leaves the newline in the input buffer, since the %s(1) format stops when the first whitespace character is encountered after some non-whitespace, getchar() then returns that newline immediately and doesn't need to wait for further input.
Your workaround works because it clears the newline from the input buffer before calling getchar() once more.
To emulate the behaviour, clear the input buffer before printing the message,
scanf("%s", command);
int c;
do {
    c = getchar();
}while(c != '\n' && c != EOF);
if (c == EOF) {
    // input stream ended, do something about it, exit perhaps
} else {
    printf("Type Enter to continue\n");
    getchar();
}

(1) Note that using %s in scanf is very unsafe, you should restrict the input to what your buffer can hold with a field-width, scanf("%99s", command) will read at most 99 (sizeof(command) - 1)) characters into command, leaving space for the 0-terminator.

A: after taking command input flush the stdin.
fflush(stdin);

but flushing a input stream results in undefined behavior (though Microsoft's C library defines the behaviour as an extension).

A: Well, I have something easier: add another getchar() ... problem solved!!


text:
Q: Websocket ClientEnpoint disconnect I am using Wildfly 8.1 and I implemented a Websocket Server endpoint which works very well.
I can push and receive data without a problem. (Javascript clients)
Now I also need a client in java to connect to another system.
My Client looks like this:
@ClientEndpoint
public class WebsocketClient {
    public WebsocketClient() {
    }

    @OnOpen
    public void onOpen(Session session) {
        try {
            System.out.println("Sending test message to endpoint: " + new Date());
            session.getBasicRemote().sendText(name);
        } catch (IOException ex) {
            log.error(ex.getMessage(), ex);
        }
    }

    @OnMessage
    public void onMessage(String message, Session session) {
        log.info("Received: " + message);
    }

    @OnClose
    public void onClose(Session session, CloseReason closeReason) {
        log.info("Disconnected: " + closeReason));
    }

}

try {
    WebSocketContainer container = ContainerProvider.getWebSocketContainer();
    String url = "ws://localhost:8080/test/wss/websocket_socket";
    container.connectToServer(BlockchainWebsocketClient.class, URI.create(url));
} catch (DeploymentException | IOException e) {
    e.printStackTrace();
}

The connect works, but I wonder how do I disconnect? The WebSocketContainer has no methods for that. How can I control the connect/disconnect/reconnect?
best regards,
m

A: container.connectToServer(...)

returns javax.websocket.Session instance, you can use it for calling session.close() if you want - that should disconnect current client session from server endpoint.
Reconnect is not part of JSR 356 - Java API for WebSocket, so you must implement it by yourself or you some proprietary feature (Tyrus - other JSR 356 implementation - has something called "ReconnectHandler", WildFly might have something as well).


text:
Q: load selective css using jquery by querying width and height of the browser I am currently using this script to load the correct CSS depending on the screen width. It works fine. However I have issues when trying to load the correct script by querying both width and height. The script is as below. Can someone correct me where I am going wrong?
Thanks in advance.
function adjustStyle(width) {
    width = parseInt(width);
    height = $(window).height();
    if (width < 1010) {
        $("#size-stylesheet").attr("href", "css/style_1024.css");
    } else if ((width < 1281) && (height > 780)) {
        $("#size-stylesheet").attr("href", "css/style_1280.css");
    } else if ((width < 1281) && (height < 800)) {
        $("#size-stylesheet").attr("href", "css/style_1280mac.css");
    } else if (width < 1370) {
        $("#size-stylesheet").attr("href", "css/style_1366.css");
    } else if (width < 1450) {
        $("#size-stylesheet").attr("href", "css/style_mac1.css");
    } else if (width < 1610) {
        $("#size-stylesheet").attr("href", "css/style_1600.css");
    } else {
        $("#size-stylesheet").attr("href", "css/style_FHD.css");
    }
}

$(function() {
    adjustStyle($(this).width());
    $(window).resize(function() {
        adjustStyle($(this).width());
    });
});

A: You are passing width parameter to your function but not height so this problem is coming.

I have edited the code, hope it works!!

function adjustStyle(width, height) {
    width = parseInt(width);
    height = parseInt(height);
    if (width < 1010) {
        $("#size-stylesheet").attr("href", "css/style_1024.css");
    } else if ((width < 1281) && (height > 780)) {
        $("#size-stylesheet").attr("href", "css/style_1280.css");
    } else if ((width < 1281) && (height < 800)) {
        $("#size-stylesheet").attr("href", "css/style_1280mac.css");
    } else if (width < 1370) {
        $("#size-stylesheet").attr("href", "css/style_1366.css");
    } else if (width < 1450) {
        $("#size-stylesheet").attr("href", "css/style_mac1.css");
    } else if (width < 1610) {
        $("#size-stylesheet").attr("href", "css/style_1600.css");
    } else {
        $("#size-stylesheet").attr("href", "css/style_FHD.css");
    }
}

$(function() {
    adjustStyle($(this).width(), $(this).height());
    $(window).resize(function() {
        adjustStyle($(this).width(), $(this).height());
    });
});

A: Do it this way. The code given below is working....
<!DOCTYPE html>
<html>
<head>
<title>question1</title>
<link id="size-stylesheet" rel="stylesheet" type="text/css" href="style3.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js">
</script>
<script>

$(window).ready(function(){

if($(window).width()<1281 && $(window).height()>780)
{
    $("#size-stylesheet").attr("href","style1.css");
}
else if($(window).width()<1281 && $(window).height()<800)
{
    $("#size-stylesheet").attr("href","style2.css");
}
else
{
    $("#size-stylesheet").attr("href","style3.css");
}

});

$( window ).resize(function() {

if($(window).width()<1281 && $(window).height()>780)
{
    $("#size-stylesheet").attr("href","style1.css");
}
else if($(window).width()<1281 && $(window).height()<800)
{
    $("#size-stylesheet").attr("href","style2.css");
}
else
{
    $("#size-stylesheet").attr("href","style3.css");
}
});

</script>

<body>
<div>
this is a webpage
</div>
</body>
</head>
</html>


text:
Q: Finding the area of some specific graph color in a 3D graph I have a graph (and its raw data) as shown below.

The axis in the graph is in cm.
I want to know the area of deep blue area in this graph (the answer should be like 20 sq.cm. or something like that).
Is there any way to find it?

A: If you're sure that you literally mean only the deepest shade of blue, then that corresponds to the minimum of your data. You can find that with minval = min(mydata(:));.
Once you have the minimum value, select points that are equal to that value with minvals = mydata == minval;. Note that this will only collect elements that are exactly equal to your deepest blue, in a floating point sense. If you didn't literally mean only the deepest shade of blue, you might want to consider selecting all points that are within some threshold of the minimum value instead. Finally count them with total = sum(minvals(:));.
Then multiply the number of points by a value representing the area of each point in cm2.


text:
Q: Google server putty connect 'Disconnected: No supported authentication methods available (server sent: publickey) I'm trying to connect to my Debian Google Compute Engine server through PuTTy (I've tried other alternatives too) but when I do I get the error "Disconnected: No supported authentication methods available (server sent: publickey)

The google server came without a username and password, only a url to automatically login to their own terminal.

A: Please follow this guide: https://gist.github.com/feczo/7282a6e00181fde4281b
with pictures.
In short:
Using Puttygen, click 'Generate' move the mouse around as instructed and wait

*

*Enter your desired username

*Enter your password

*Save the private key
Copy the entire content of the 'Public key for pasting into OpenSSH authorized_keys file' window. Make sure to copy every single character from the beginning to the very end!
Go to the Create instances page in the Google Cloud Platform Console and in the advanced options link paste the contents of your public key.
Note the IP address of the instance once it is complete.
Open putty, from the left hand menu go to Connection / SSH / Auth and define the key file location which was saved.
From the left hand menu go to Connection / Data and define the same username

*

*Enter the IP address of your instance

*name the connection below saved Sessions as 'GCE' click on 'Save'

*double click the 'GCE' entry you just created

*accept the identy of the host

Now login with the password you specified earlier and run
sudo su - and you are all set.

A: You need to use an SSH key to login to your instance.
The GCE documentation explains the process here.

A: I had the same problem but got it working by changing enable-oslogin from TRUE to FALSE in google cloud.
from:

to:

A: I had the same issue and just figured it out !!
Assuming that you already went and created private/public key added your public key on the remote server ... type in username@remotehost.com and THEN go to   Connection -> SSH -> Auth  and click Browse to locate your private key. After you choose it will populate the input field. After that click OPEN ...
So the important thing here is the order... make sure you first enter parameters for the host and then locate your private key.

A: I got this error because I had forgotten to add my username behind the key in the GCE metadata section. For instance, you are meant to add an entry into the metadata section which looks like this:
sshKeys    username:key

I forgot the username: part and thus when I tried to login with that username, I got the no supported auth methods error.
Or, to turn off the ssh key requirement entirely, check out my other answer.

A: I had PuTTY working and then one day got this error.
Solution: I had revised the folder path name containing my certificates (private keys), and this caused Pageant to lose track of the certificates and so was empty.
Once I re-installed the certificate into Pageant then Putty started working again.

A: Turn on Password Authentication
By default, you need to use keys to ssh into your google compute engine machine, but you can turn on password authentication if you do not need that level of security.

Tip: Use the Open in browser window SSH option from your cloud console to gain access to the machine. Then switch to the root user with sudo su - root to make the configuration changes below.

*

*Edit the /etc/ssh/sshd_config file.

*Change PasswordAuthentication and ChallengeResponseAuthentication to yes.

*Restart ssh /etc/init.d/ssh restart.

A: Apparently running sudo chmod -R a+rw on your home folder causes this to happen as well.

A: This problem mainly caused by your connected username not have the access to the shell in GCE. So you use the following steps to solve this issue.
gcloud auth list

If you are using the correct login. please follow the below steps. otherwise use
gcloud auth revoke --all
gcloud auth login [your-iam-user]

and you get the token or it automatically detect the token.
gcloud compute --project "{projectid}" ssh --zone "{zone_name}" "{instance_name}" .

if you dont know this above line click to compute engine-> ssh dropdown arrow-> view google command-> copy that code and use it
Now it update your metadata and it is available in your computer's folder Users->username
~/.ssh/google_compute_engine.ppk
~/.ssh/google_compute_engine.pub

Then you create a new ppk file using puttygen and you give the username, which you want like my_work_space. Then
save the publickey and privatekey in a folder.
Next step: Copy the public key data from puttygen and create new ssh key in gcloud metadata
cloud console ->compute engine->metadata->ssh key->add new item->paste the key and save it

and now return your shell commandline tool then enter
sudo chown -R my_work_space /home/my_work_space

now you connect this private key using sftp to anywhere. and it opens the files without showing the permission errors
:) happy hours.

A: If the private key has been generated with ssh-keygen in Linux it needs to be converted with puttygen because Putty does not support openssh keys.
Start puttygen, and click on Conversions - Import key, then click Browse and select the private key generated with openssh, then click on Save private key.
Use your new key to connect.

A: I faced the same issue and solve after several trial and error.
In the /etc/ssh/ssh_config, set

*

*PubkeyAuthentication yes

*AuthorizedKeysFile .ssh/authorized_keys

*PasswordAuthentication no

*AuthenticationMethods publickey
then, open putty.
In the "Saved Sessions", enter the server IP, go through the path Connection->SSH->Auth->Browse on the left panel to search your private key and open it.
Last but not least, go back to Session of putty on the left panel and you can see the server IP address is still in the field, "Saved Sessions", then click "Save", which is the critical step.
It will let the user login without password any more.
Have fun,

A: Download "PuttyGEN" get publickey and privatekey
use gcloud SSH edit and paste your publickey located in /home/USER/.ssh/authorized_keys
sudo vim ~/.ssh/authorized_keys
Tap the i key to paste publicKEY.
To save, tap  Esc, :, w, q, Enter.
Edit the /etc/ssh/sshd_config file.
sudo vim /etc/ssh/sshd_config

Change
PasswordAuthentication no
[...]
ChallengeResponseAuthentication to no.
[...]
UsePAM no
[...]
Restart ssh
/etc/init.d/ssh restart.
the rest config your putty as tutorial
NB:choose the pageant add keys and start session would be better

A: Electricity went down and got this error. Solution was to double click your .ppk (Putty Private Key) and enter your password.

A: PasswordAuthentication and ChallengeResponseAuthentication default set to NO in rhel7.
Change them to NO and restart sshd.

A: Similar problem - same error message. I got the same message when trying to clone something from bitbucket with ssh. The problem was in my ssh configuration configured in the mercurial.ini: I used the wrong bitbucket username. After I corrected the user name things worked.

A: For me these was my problem, solution from https://unix.stackexchange.com/questions/282908/server-refused-public-key-signature-despite-accepting-key-putty
"Looking at the log /var/log/secure showed that it was just downright refused. I'm somewhat new to centos since I'm mainly a debian kind of guy, so I was unaware of /var/log/secure
After checking this and doing a bit of searching, it turns out PermitRootLogin no needs to be PermitRootLogin without-password if you want to specifically use just keys for root login. That did the trick. Thanks everyone for contributing."

A: I had the same error message and discovered that my mistake was in the username I used with putty.  Apparently GCE SSH Keys listing would change your username characters in some of the listing.  In my case, the underscore was changed to period.  i.e: my_username becomes my.username
I inadvertently copied the wrong username from the listing and got the same error message.

A: I know this is an old question, but I had the same problem and solved it thanks to this answer.
I use Putty regularly and have never had any problems. I use and have always used public key authentication. Today I could not connect again to my server, without changing any settings.
Then I saw the answer and remembered that I inadvertently ran chmod 777 . in my user's home directory. I connected from somewhere else and simply ran chmod 755 ~. Everything was back to normal instantly, I didn't even have to restart sshd.
I hope I saved some time from someone


text:
Q: facing issue dealing with collections in jaxb moxy unmarshalling due to getter method getting invoked twice I am using jaxb moxy unmarshalling, and my java object has some logic in getter methods to set values in Array. so facing issue in unmarshalling, as the getter method is invoked twice by jaxb framework while unmarshalling. is there any way to avoid this getter method being called twice? can some thing be set in binding xml to avoid this getter call for null check?

A: You could specify @XmlAcessorType(XmlAccessType.FIELD) so that MOXy (or and JAXB implementation) uses the field directly instead of the property (get/set methods).  With this access type you will want to put the annotations on the fields.
For More Information

*

*http://blog.bdoughan.com/2011/06/using-jaxbs-xmlaccessortype-to.html


text:
Q: Commands like 1; and 2c1; on shell I am developing a simple "tar-like" archiving C program. It works by writing all files, directories and file contents in a text file, and it can extract them in the same way (it creates empty files, and then fill them with archive content).
When I have to archive text files or PDFs, it works well.
With audio files such as MP3s, at the end of extraction, i have these lines on shell:
1;2c1;2c1;2c1;2c1;2c1;2c1;2c1;2c1;2c1;2c1;2c1;2c1;2c1;2c1;2c1;2c1;2c1;2c1;2c1;2c1;2c1;2c1;
2c1;2c1;2c1;2c1;2c1;2c1;2c1;2c1;2c1;2c1;2c1;2c1;2c1;2c1;2c1;2c1;2c1;2c1;2c1;2c1;2c1;2c1;2c1;
2c1;2c1;2c1;2c1;2c1;2c1;2c1;2c1;2c1;2c1;2c1;2c1;2c1;2c1;2c1;2c1;2c1;2c1;2c1;2c;1;1;112;112;
1;0x1;2c1;2c1;2c1;2c1;2c1;2c1;2c1;2c1;2c1;2c1;2c1;2c1;2c1;2c;1;1;112;112;1;0x1;2c1;2c1;2c1;
2c1;2c1;2c1;2c1;2c1;2c1;2c1;2c1;2c1;2c1;2c1;2c1;2c1;2c1;2c1;2c1;2c1;2c1;2c1;2c1;2c1;2c1;2c1;
2c1;2c1;2c1;2c1;2c1;2c1;2c1;2c1;2c1;2c1;2c1;2c1;2c1;2c1;2c1;2c

I don't know why program writes this on shell, and why it does like this only with audio tracks. By executing them, I noticed that only 1;commands are executed, and 2c1;commands are unknown.
Can you help me find out why?
This is code i wrote for extracting part:
void crea_file(FILE *f)                                             // crea i file estratti dall'archivio
{
    int contatore = 0;
    char x[4096];
    bool listTrovata = false;
    while (fscanf(f, " %s", x) == 1) {
        if(strcmp(x, "%LIST%")==0 && listTrovata==false)
        {
            listTrovata= true;
            puts("trovato il primo \n");
            continue;
        }
        else if (strcmp(x, "%LIST%")==0 && listTrovata)
        {
            long position;
            position = ftell(f);
            printf("trovato il secondo \n");
            printf("LIST trovato alla posizione %ld", position);
            fseek(f, 0, SEEK_END);
            break;
        }
        else if (listTrovata)
        {
            contatore++;
            char* file;                         // stringa contenente il percorso da aprire (verrà creato in seguito)
            file = collega(getcwd(NULL, 0), x);
            creat(file, PERMS);
            printf("sto cercando l'inizio e la fine di content, passando un contatore %d \n", contatore);
            trovaInizioFine(contatore);
            printf("ora scrivo il file trovato");
            scriviFile(file);
            //inserisco funzione che parte da inizio e scrive carattere per carattere nel file destinazione. se la posizione di ftell è uguale a fine, allora esci.
        }
    }
    printf("esco \n");
}

void trovaInizioFine(int cont)                                      // trova il carattere di inizio e di fine del file nella sezione %CONTENT%
{
    FILE* contenuto;
    char * path;
    char x[4096];
    int i =1;
    path = collegaSlash(getcwd(NULL, 0), nome);

    contenuto = fopen(path, "r");
    while (fscanf(contenuto, "%s", x) == 1)
    {
        if(strcmp(x, "%CONTENT%")==0 && i == ((cont*2)-1) )
        {
            inizio = ftell(contenuto);
            puts("trovato il primo \n");
            //puts(x);
            printf("CONTENT trovato alla posizione %d \n", inizio);
            i++;
        }
        else if(strcmp(x, "%CONTENT%")==0 && i == ((cont*2)) )
        {
            fine = ftell(contenuto);
            daleggere = fine-9;
            puts("trovato il primo \n");
            printf("CONTENT trovato alla posizione %d \n", fine);
            break;
            i++;
        }
        else if(strcmp(x, "%CONTENT%")==0)
        {
            i++;
        }

        printf("giro numero %d \n", i);
    }

    printf("esco da trova Inizio File  \n");
    fclose(contenuto);

}

void scriviFile(const char * arrivo)                                //scrive i file creati in precedenza
{
    FILE * partenza;
    FILE * target;
    int c;
    int spazio = 'a';
    int i = 0;
    int pos;
    char * path;
    path = collegaSlash(getcwd(NULL, 0), nome);
    partenza = fopen(path, "r");
    fseek(partenza, inizio, SEEK_SET);
    target = fopen(arrivo, "w");                                            //apro il file
    if (target) {                                                               //se è aperto
        while ((c = fgetc(partenza)) != EOF && ftell(partenza)<=fine-10) {                                  //e il carattere preso non eccede la fine del file
            fputc(c, target);
            fputc(c, stdout);
            pos = ftell(partenza);
            if(pos==fine)
            {
                break;
            }
                                                                            //scrivo lo stesso carattere in out (file in uscita)
        }                                                                   //

        fclose(target);                                                     //chiudo il file
        fclose(partenza);
    }
    else
    {
        printf("errore di scrittura del file \n");
    }

}

my archive has 3 section: %LIST%, %DIRS% and %CONTENT%.
crea_file reads %LIST% section and creates empty files in current directory.
TrovaInizioFine reads %CONTENT% section and saves 2 indexes: one at beginning of file content, and one at its end.
scrivifile fills empty file with archive content.

A: Without any code to look at, this is quite hard.
Still, one thing you say makes me suspect problems:

It works by writing all files, directories and file contents in a text file

You can't treat arbitrary binary data as text, in most cases. The C libraries might to end-of-line translation, which will destroy binary data. You must use binary files for arbitrary data, or take care to "protect" the data so that it really survives being treated as text.
Go binary.


text:
Q: Git branching stategy for feature branches and common code I've been using the git branching strategy outlined here http://nvie.com/posts/a-successful-git-branching-model/
So far its been working really well for me.
The question I often find my self asking is while working on a feature branch I'll end up needing to implement code that is relevant to the entire project. What is the best way to handle these situations?
a) Check out the main development branch, commit the change and rebase the feature branch off of develop.
b) Make the change on the feature branch, then merge back into develop so that other feature branches can have access to that code.
c) Create a new branch for the common code and merge that into Develop as well as any feature branches that need to use it.
Here's another question. How often do you merge a feature branch back into the main development branch? Do you wait until the feature is completely done then merge it and delete it? Or do you merge back into develop several times throughout its lifetime any time that it's stable?

A: I like option a/, but the reality is, when you are doing commits after commits, you only realize that some of them are actually common code much later in the process.
When that happens on a feature branch (that usually hasn't been pushed yet and shared with), I prefer doing an interactive rebase, re-ordering the commits for common code first, and then merging the master branch to the feature branch for those n first commits (fast-forward merge).
From there, I can rebase onto master any other branch that have to benefit from those new common features.
Merging back a feature branch only makes sense if the state of that feature branch must be visible for others (because you want to push master while keeping feature branch private to your repo).
If the rest of the development:

*

*can proceed without needing any part of what is in the feature branch

*can proceed without modifying some common set of files (which would imply a much harder merge the longer you wait between master and feature branches)

, then I prefer merging feature branch later.


text:
Q: Make databound input textbox updateable with AngularJS I have a form with a bunch of labels and textboxes, my controller retrieves data and displays it in those controls:
 ID: {{pageData.ID}}

 Title: {{pageData.title}}

 <input type="text" name="notes" placeholder="Notes" value="{{pageData.notes}}" />

 <input type="button" name="btnProcess" class="action-button" value="Process" ng-click="Process()" />

The display of the data works fine, but notes field is optional and in most cases is empty. I want to update the field ona  button-click.
Here is the code from my controller that pulls data into PageData:
$http.get(window.baseApiUrl + '/GetPageData').
        then(function (result) {
            $scope.pageData = result.data;
        });

Now the issue is that for grabbing the value of notes textbox from my controller, I need ng-model but if I add ng-model to my textbox, I no longer able to see the values from the database for those records that do have notes.
Is there a workaround?

A: If I understand what you want correctly...
In your html change the ng-model of your text box:
<input type="text" name="notes" placeholder="Notes" ng-model="pageData.notes" />

In your controller on your process function:
$scope.process = function() {
  //if you need data persisted to the database you'll call some api
  //endpoint here to send pageData to the server
  $http.put(window.baseApiUrl + '/UpdatePageData', $scope.pageData).
    then(function () {
        console.log("data persisted");
    });
}

EDIT: Use ng-model to 2-way bind to pageData.notes.  This will display the value of pageData.note after your $http.get() and will also allow you to update the value of pageData.notes for you to post back to the server.


text:
Q: Historic (and current) borders of Miami, FL I am working from Australia and am new to US mapping and Census data.
I am looking for historic boundaries of Miami (FL) from maybe 100-200 years ago.
Also current boundaries would be great - what does census.gov data mean when they refer to "Miami"? - the goal is to show spatial growth as well as population growth over time to compare Miami to Australian cities.

A: I just read an article about a new... app? created by the USGS, called the Historical Topographic Map Explorer. You can search or pan, click on the map, and it will show a timeline at the bottom listing the date of all available maps. The oldest for Miami seems to be 1950 though.
Another source mentioned in several answers elsewhere on this site is the National Historical Geographic Information System.
Contacting the city directly, either GIS or perhaps a historic preservation department, may yield some data. Often current boundaries are available from either the city or county directly on their websites.
I'm not clear on your sub-question of 'what do they mean'. It depends on in what context I imagine. There is the actual city as well as the metropolitan area which would include other cities. And as cities expand over time, they often engulf and absorb surrounding towns and cities, so it would depend on when you ask as much as where.