text:
Q: Проблема со спринг-бутом Не могли бы вы, пожалуйста, подсказать, я изучал spring boot, и в ходе проекта мне понадобилось собрать данные с одного контроллера, и обработать их относительно присланных данных другого контроллера внутри основного файла "ExampleApplication". Только возникла проблема, как достать эти значения, ведь сами классы контроллеров создаются внутри метода "run".
Вот код:
ExampleApplication.java
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;

@SpringBootApplication
@ComponentScan({"com.example.StudyGrid.controller"})
public class ExampleApplication {

    public static void main(String[] args) {
        SpringApplication.run(StudyGridApplication.class, args);
    }

}

FirstController.java
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

@Controller
public class MainController {

    @RequestMapping("/welcome")
    public String welcomepage() {
        return "home";
    }

    @GetMapping("/")
    public String home(Model model) {
        model.addAttribute("title","Главная страница");
        return "home";
    }
    @GetMapping("/signup")
    public String error(Model model) {
        model.addAttribute("title","Регистрация");
        return "reg";
    }
    @GetMapping("/error")
    public String error2(Model model) {
        model.addAttribute("title","Главная страница");
        return "error";
    }

    @PostMapping("/signup")
    public String signup(@RequestParam(name="name", required=false, defaultValue="World") String name) {
        return "";
    }

}

Второй контроллер такой же.

A: SpringApplication.run() - возвращает ApplicationContext контекст.Так как аннотация @Controller наследует аннотацию @Component, то контроллеры будут опубликованы в контексте.


text:
Q: How to force classifier on transitive dependencies? I have dependencies:

*

*A

*B (that also depends on A).

Now, I want to use specifier on A, lets say: A-foo. However, B still depends on A and as a result, I get both A-foo and A included in the target artifact.
Is there a way to force classifier on certain dependency?
Why?
The reason why I need this is the following.
My A is a Java library built on Java8 but packaged as Multi-Release Jar which means it contains additional classes for when jar is run on Java9.
Unfortunately, some old tools and servers are not aware of MR Jars and this makes them not working.
For that reason I have A-foo version of my library, that is without any extra classes, so old server can run it.
However, if user is using library B that depends on my A, he will simply get the MRJar version of A and it will fail again. I want to be able to prevent this somehow.

A: An artifact with a classifier is a different artifact, not just a different version of the same artifact. It cannot replace - neither technically nor logically - the original artifact, meaning: Even if you would find a way around it technically, it goes against Maven logic.
If you describe in more detail which problem you want to solve, one can probably find a "Maven way" to do it.

A: In Gradle this is possible with the following code:
compile ('org.jodd:jodd-core:4.1.4:jre9') {
    force = true
}
compile ('org.jodd:jodd-joy:4.1.4') {
    exclude group: 'org.jodd', module:'jodd-core'
}

This means:

*

*force classifier usage of a library;

*excluded transitive non-classifier dependencies of a library

redpajama_set_name: RedPajamaStackExchange


text:
Q: Reference error function javascript I have the following javascript:
$(document).ready(function () {
        // convert bytes into friendly format
        function bytesToSize(bytes) {
            var sizes = ['Bytes', 'KB', 'MB'];
            if (bytes == 0) return 'n/a';
            var i = parseInt(Math.floor(Math.log(bytes) / Math.log(1024)));
            return (bytes / Math.pow(1024, i)).toFixed(1) + ' ' + sizes[i];
        };

        // check for selected crop region
        function checkForm() {
            if (parseInt($('#w').val())) return true;
            $('.error').html('Please select a crop region and then press Upload').show();
            return false;
        };

        // update info by cropping (onChange and onSelect events handler)
        function updateInfo(e) {
            $('#x1').val(e.x);
            $('#y1').val(e.y);
            $('#x2').val(e.x2);
            $('#y2').val(e.y2);
            $('#w').val(e.w);
            $('#h').val(e.h);
        };

        // clear info by cropping (onRelease event handler)
        function clearInfo() {
            $('.info #w').val('');
            $('.info #h').val('');
        };

        // Create variables (in this scope) to hold the Jcrop API and image size
        var jcrop_api, boundx, boundy;

        function fileSelectHandler() {

            // get selected file
            var oFile = $('#image_file')[0].files[0];

            // hide all errors
            $('.error').hide();

            // check for image type (jpg and png are allowed)
            var rFilter = /^(image\/jpeg|image\/png)$/i;
            if (!rFilter.test(oFile.type)) {
                $('.error').html('Please select a valid image file (jpg and png are allowed)').show();
                return;
            }

            // check for file size
            if (oFile.size > 250 * 1024) {
                $('.error').html('You have selected too big file, please select a one smaller image file').show();
                return;
            }

            // preview element
            var oImage = document.getElementById('preview');

            // prepare HTML5 FileReader
            var oReader = new FileReader();
            oReader.onload = function (e) {

                // e.target.result contains the DataURL which we can use as a source of the image
                oImage.src = e.target.result;
                oImage.onload = function () { // onload event handler

                    // display step 2
                    $('.step2').fadeIn(500);

                    // display some basic image info
                    var sResultFileSize = bytesToSize(oFile.size);
                    $('#filesize').val(sResultFileSize);
                    $('#filetype').val(oFile.type);
                    $('#filedim').val(oImage.naturalWidth + ' x ' + oImage.naturalHeight);

                    // destroy Jcrop if it is existed
                    if (typeof jcrop_api != 'undefined') {
                        jcrop_api.destroy();
                        jcrop_api = null;
                        $('#preview').width(oImage.naturalWidth);
                        $('#preview').height(oImage.naturalHeight);
                    }

                    setTimeout(function () {
                        // initialize Jcrop
                        $('#preview').Jcrop({
                            minSize: [32, 32], // min crop size
                            aspectRatio: 1, // keep aspect ratio 1:1
                            bgFade: true, // use fade effect
                            bgOpacity: .3, // fade opacity
                            onChange: updateInfo,
                            onSelect: updateInfo,
                            onRelease: clearInfo
                        }, function () {

                            // use the Jcrop API to get the real image size
                            var bounds = this.getBounds();
                            boundx = bounds[0];
                            boundy = bounds[1];

                            // Store the Jcrop API in the jcrop_api variable
                            jcrop_api = this;
                        });
                    }, 3000);

                };
            };

            // read selected file as DataURL
            oReader.readAsDataURL(oFile);
        }
    });

Here is my HTML:

                                    <button type="button" class="close" data-dismiss="modal">×</button>

Upload profilepicture

                                        <form id="upload_form" enctype="multipart/form-data" method="post" action="upload.php" onsubmit="return checkForm()">

                                            <input type="hidden" id="x1" name="x1" />
                                            <input type="hidden" id="y1" name="y1" />
                                            <input type="hidden" id="x2" name="x2" />
                                            <input type="hidden" id="y2" name="y2" />

Step1: Please select image file

<input type="file" name="image_file" id="image_file" onchange="fileSelectHandler()" />

Step2: Please select a crop region

                                                    File size <input type="text" id="filesize" name="filesize" />
                                                    Type <input type="text" id="filetype" name="filetype" />
                                                    Image dimension <input type="text" id="filedim" name="filedim" />
                                                    W <input type="text" id="w" name="w" />
                                                    H <input type="text" id="h" name="h" />

                                                <input type="submit" value="Upload" />

                                        </form>

When I run this, I get the following error:

Uncaught ReferenceError: fileSelectHandler is not defined

I do not understand why. As I can see, the function Is already implemented? So Why do I get this reference error?

A: You don't need any of those functions to be in document.onReady.
Any function declared in the document.ready scope must also be called from within it. If not, they lose that scope when the ready() method exits. So it does not exist in the scope you are trying to call it from, hence your error.
Define as follows:

    function bytesToSize(bytes) {
      var sizes = ['Bytes', 'KB', 'MB'];
      if (bytes == 0) return 'n/a';
      var i = parseInt(Math.floor(Math.log(bytes) / Math.log(1024)));
      return (bytes / Math.pow(1024, i)).toFixed(1) + ' ' + sizes[i];
    };

     // check for selected crop region
    function checkForm() {
      if (parseInt($('#w').val())) return true;
      $('.error').html('Please select a crop region and then press Upload').show();
      return false;
    };

     // update info by cropping (onChange and onSelect events handler)
    function updateInfo(e) {
      $('#x1').val(e.x);
      $('#y1').val(e.y);
      $('#x2').val(e.x2);
      $('#y2').val(e.y2);
      $('#w').val(e.w);
      $('#h').val(e.h);
    };

     // clear info by cropping (onRelease event handler)
    function clearInfo() {
      $('.info #w').val('');
      $('.info #h').val('');
    };

     // Create variables (in this scope) to hold the Jcrop API and image size
    var jcrop_api, boundx, boundy;

    function fileSelectHandler(e) {

      alert("I'm here!");

      // get selected file
      var oFile = $('#image_file')[0].files[0];

      // hide all errors
      $('.error').hide();

      // check for image type (jpg and png are allowed)
      var rFilter = /^(image\/jpeg|image\/png)$/i;
      if (!rFilter.test(oFile.type)) {
        $('.error').html('Please select a valid image file (jpg and png are allowed)').show();
        return;
      }

      // check for file size
      if (oFile.size > 250 * 1024) {
        $('.error').html('You have selected too big file, please select a one smaller image file').show();
        return;
      }

      // preview element
      var oImage = document.getElementById('preview');

      // prepare HTML5 FileReader
      var oReader = new FileReader();
      oReader.onload = function(e) {

        // e.target.result contains the DataURL which we can use as a source of the image
        oImage.src = e.target.result;
        oImage.onload = function() { // onload event handler

          // display step 2
          $('.step2').fadeIn(500);

          // display some basic image info
          var sResultFileSize = bytesToSize(oFile.size);
          $('#filesize').val(sResultFileSize);
          $('#filetype').val(oFile.type);
          $('#filedim').val(oImage.naturalWidth + ' x ' + oImage.naturalHeight);

          // destroy Jcrop if it is existed
          if (typeof jcrop_api != 'undefined') {
            jcrop_api.destroy();
            jcrop_api = null;
            $('#preview').width(oImage.naturalWidth);
            $('#preview').height(oImage.naturalHeight);
          }

          setTimeout(function() {
            // initialize Jcrop
            $('#preview').Jcrop({
              minSize: [32, 32], // min crop size
              aspectRatio: 1, // keep aspect ratio 1:1
              bgFade: true, // use fade effect
              bgOpacity: .3, // fade opacity
              onChange: updateInfo,
              onSelect: updateInfo,
              onRelease: clearInfo
            }, function() {

              // use the Jcrop API to get the real image size
              var bounds = this.getBounds();
              boundx = bounds[0];
              boundy = bounds[1];

              // Store the Jcrop API in the jcrop_api variable
              jcrop_api = this;
            });
          }, 3000);

        };
      };

      // read selected file as DataURL
      oReader.readAsDataURL(oFile);
    }

    $(document).ready(function() {
      // convert bytes into friendly format

    });

        <button type="button" class="close" data-dismiss="modal">×</button>

Upload profilepicture

          <form id="upload_form" enctype="multipart/form-data" method="post" action="upload.php" onsubmit="return checkForm()">

            <input type="hidden" id="x1" name="x1" />
            <input type="hidden" id="y1" name="y1" />
            <input type="hidden" id="x2" name="x2" />
            <input type="hidden" id="y2" name="y2" />

Step1: Please select image file

              <input type="file" name="image_file" id="image_file" onchange="fileSelectHandler()" />

Step2: Please select a crop region

                File size
                <input type="text" id="filesize" name="filesize" />
                Type
                <input type="text" id="filetype" name="filetype" />
                Image dimension
                <input type="text" id="filedim" name="filedim" />
                W
                <input type="text" id="w" name="w" />
                H
                <input type="text" id="h" name="h" />

              <input type="submit" value="Upload" />

          </form>

A: That is because your function fileSelectHandler() is defined inside of another function. Try to move it out of "$(document).ready(function () {..." block


text:
Q: jQuery scrollTop with "else if" statement doesn't work I'm trying to addClass and removeClass to a div based on top scrolling with jquery.
I created these two variables:
var mainHeight = $('#main-image').height()/1.10;
var footHeight = $('body').height() - $('footer').height();

And this is the script that doesn't works:
$(window).scroll(function(){

    if ($(window).scrollTop() > mainHeight) {
        $('#box_centrale').removeClass('chat-bottom, chat-top');

    } else if ($(window).scrollTop() > footHeight) {
        $('#box_centrale').removeClass('chat-bottom');
        $('#box_centrale').addClass('chat-top');

    } else {
        $('#box_centrale').removeClass('chat-top');
        $('#box_centrale').addClass('chat-bottom');
    }
});

The "if" and "else" statement works but "else if" statement doesn't work...
Have you any idea why does not work?
(I apologize for my English)

A: I solved! There was an error in the second variable, missing parentheses to the operation. I decide to create a jsfiddle with an example of what I wanted to do, hoping that it will help someone in the future.
Thank you all
Here the link:
JSFiddle
$(document).ready(function(e) {

var mainHeight = $('#header').height()/2;
var footHeight = ($('body').height() - $('#footer').height() - 290);

$(window).scroll(function(){
    if ($(window).scrollTop() < mainHeight) {
        $('#fixed-box').css({
            "bottom" : "calc(100% - 310px)",
        });

    } else if ($(window).scrollTop() > footHeight) {
        $('#fixed-box').css({
            "bottom" : "calc(260px)",
        });

    } else {
        $('#fixed-box').css({
            "bottom" : "calc(50% - 25px)",
        });
    }
});

});


text:
Q: Written equivalent to "soundbite" Wikitionary describes soundbite as:

a short extract from a recorded interview or speech, chosen for its succinctness or concision.

What would be an equivalent word for a written medium, as opposed to audio?
I've used several phrases over the years to describe these but nothing as succinct as soundbite.
Example usage:

That blog was full of wordbites that expressed the thoughts I had.

What this would mean is roughly one of the following 3 or a mix of them:

*

*That blog was full of phrases which put very clearly the nuanced thoughts I've had on the subject but haven't been able to express very well.

*That blog was full of phrases which read really well and communicate the ideas very clearly, which I also had.

*That blog was full of quotable phrases which I'd rather use instead of explaining my thoughts in my own words

A: Snippet works well in this case:

[Merriam-Webster]
: a small part, piece, or thing
especially : a brief quotable passage
// snippets from the author's newest novel
// read them a snippet of his latest poem

In the example sentence in the question:

That blog was full of snippets that expressed the thoughts I had.

A: Not as idiomatic, but apothegm has the intended meaning:

apothegm: a short clever saying that is intended to express a general truth [Cambridge English
  Dictionary

.........

apothegm: a short, witty, instructive saying [Wiktionary]

.........

*

*I am reminded of the absolutely necessary apothegm written somewhere by Camus: 'Classicism is nothing but [R]omanticism with the excess removed.' [Suicides and Jazzers, Hayden Carruth]

The example sentence illustrates that apothegms may be non-verbal, and (at least at the time of penning) not widely used enough to be considered fixed expressions.
(It is quite possible that 'soundbite' itself is considered to have broadened enough in meaning to include written examples that will or could well be be read aloud.)


text:
Q: How I can disable scrollable ViewPager2? I need disable scrolling. I use in fragment for ViewPager bottom sheet. When I try close bottom sheet I scroll ViewPager. I try disable touch, clickable and enabled(in xml).
Code:
viewPager2.setAdapter(new ShortAdapter(getActivity().getApplicationContext(), R.layout.shortvidos, R.id.name, listItems, getParentFragmentManager()));
                        viewPager2.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() {
                            @Override
                            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
                                if(ms != null) {
                                    ms.cancel(true);
                                }
                                super.onPageScrolled(position, positionOffset, positionOffsetPixels);
                                SeekBar prog = getView().findViewById(R.id.seekBar2);
                                prog.setVisibility(View.VISIBLE);
                                mProgressBari = getView().findViewById(R.id.seekBar2);
                                vois = getView().findViewById(R.id.videoView);
                                ms = new MyAsync();
                                ms.execute();
prog.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
    if(fromUser){
        if(vois != null){
            try{
                int dira = vois.getDuration();
                vois.seekTo(progress * dira / 100);
            } catch (IllegalStateException e) {
                e.printStackTrace();
            }
        }
    }
}

@Override
public void onStartTrackingTouch(SeekBar seekBar) {

}

@Override
public void onStopTrackingTouch(SeekBar seekBar) {

}
});
                            }
                        });


text:
Q: Помогите пожалуйста внедрить php-код в javascript и отправить его в обработчик Добрый день!
Помогите пожалуйста внедрить php-код в javascript и отправить его в обработчик
Есть код

.ychreditel {
 display: block;
}
<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="UTF-8">
 <title>Document</title>
 <link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
 <script language='JavaScript' type="text/javascript">
  var obrabotchik = '<?php require ("obrabotchik.php"); ?>'
  var i = 2;
  function ff(){
    document.getElementById('form_inner').innerHTML = document.getElementById('form_inner').innerHTML +
  "<select name='country" + i + "' class='ychreditel'>"+ obrabotchik +"</select>";
  i++;
  }

</script>

 <form name='form' id='form' action='fff.php' method='post'>
  <span name='form_inner' id='form_inner'>
   <select name='country1' class='ychreditel'><?require ('obrabotchik.php');?></select>
  </span>
  <input type='button' value='Добавить учредителя' onclick="ff()">
  <input name='frm_sbm' type='submit' value='Submit request' />
 </form>
</body>
</html>

При нажатии на кнопку Добавить учредителя должен добавиться select  с содержимым файла obrabotchik.php
Файл
require ('obrabotchik.php'); содержит код (код сокращен)
echo = "
<option> Австралия</option>
<option> Австрия</option>
<option> Азербайджан</option>
<option> Албания</option>
<option> Ангола</option>
<option> Андорра</option>
";

Пробовал объявить переменную js и присвоить ей значение php
var obrabotchik = '<?php require ("obrabotchik.php"); ?>'

В результате скрипт перестаёт работать
И подскажите пожалуйста как можно обработать новые select в fff.php
Спасибо!

A: Для этого примера jQuery нид.
$.ajax({
    url: 'obrabotchik.php',
    dataType: 'json',
    success: function (countriesList) {
        countriesList.forEach( function (country) {
            $('#country1').append("<option>" + country + "</option>");
        });
    }
});

И в php файле
echo json_encode("
<option> Австралия</option>
<option> Австрия</option>
<option> Азербайджан</option>
<option> Албания</option>
<option> Ангола</option>
<option> Андорра</option>
");

Ajax запрос закинуть в нужное событие, например, при загрузке страницы. Итого получим: страница загрузилась, JS сделал запрос на  obrabotchik.php и получил оттуда json со списком. После этого циклом прошелся по элементам и каждый добавил внутрь вашего select'a

A: XMLHttpRequest это API, который предоставляет клиенту функциональность для обмена данными между клиентом и сервером. Данный API предоставляет простой способ получения данных по ссылке без перезагрузки страницы. Это позволяет обновлять только часть веб-страницы не прерывая пользователя.  XMLHttpRequest используется в AJAX запросах и особенно в single-page приложениях.
XMLHttpRequest изначально был разработан Microsoft и позже заимствован Mozilla, Apple, и Google. Сейчас он стандартизирован WHATWG. Несмотря на свое название, XMLHttpRequest может быть использован для получения любых типов данных, не только XML, и поддерживает протоколы помимо HTTP (включая file и ftp).
Как работать с AJAX (XMLHttpRequest)
Чтобы начать работать с XMLHttpRequest, выполните этот код:
var xhr = new XMLHttpRequest();

Где xhr это переменная которой присвоили new XMLHttpRequest() буквально мы просто присвоили что она будет выполнять запросы XMLHttpRequest. В этом отрывке кода вы увидите ajax на примере
  var xhr = new XMLHttpRequest();
  xhr.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
     document.getElementById('form_inner').innerHTML = this.responseText;
    }
  };
  xhr.open("GET", "obrabotchik.php", true);
  xhr.send();

Разберем все по порядку

*

*Про строчку var xhr = new XMLHttpRequest(); я рассказывал выше

*Строчка xhr.onreadystatechange = function() { означает если так сказать XMLHttpRequest готов загрузить файл.

*Строчка if (this.readyState == 4 && this.status == 200) { означает что если все верно т.е readyState == 4 означает что файл загружен а status == 200 означает что никаких ошибок не найдено (например 404)

*Строчка document.getElementById('form_inner').innerHTML = this.responseText; здесь responseText это ответный текст от сервера т.е. что произошло после компиляции php-файла. в вашем случае это вот такой ответ

    <option> Австралия</option>
    <option> Австрия</option>
    <option> Азербайджан</option>
    <option> Албания</option>
    <option> Ангола</option>
    <option> Андорра</option>

*

*Строчка xhr.open("GET", "obrabotchik.php", true); Это значит какой вы открываете файл (в вашем случае файл obrabotchik.php) и GET это тип запроса, если будут отправляться пароли или большие тексты то лучше использовать POST. true означает что запрос асинхронный

*Строчка xhr.send(); Означает отправить запрос

Все что до заголовка "Как работать с AJAX (XMLHttpRequest)" было взято из MDN


text:
Q: Subtract one hour result I am pulling live data from a db2 server, I am building a Power bi report that shows by time each transaction made. There is a time difference between our server location so the result is one hour ahead. I am trying to subtract one hour from HVTIME (TIME). I can create a custom measure in Power Bi to do this but I am unable to add it to an Axis.
I have tried different SQL statements with no luck.
select

seri.htsern as Serial,
seri.htpart as PartNumber,
seri.htlotn as Batch,
seri.htqty as Quantity,
seri.htstkl as Bin,
seri.htbinl as Location,
serh.hvuser as ReceivedBy,
serh.hvtdat as RecievedDaten,
serh.hvtime as Time

from seri

left join serh on hvsern = htsern

where hvtdat between '2019/10/01' and current date
and hvtrnt = 'R'
and htplnt = 'GC'

The result I am looking for should be 10:04:53 under HVTIME (TIME).
enter image description here

A: Does this do what you want?
(serh.hvtime - 1 hour) as Time

You may find this article useful for date/time stuff in DB2.

A: Please try this code.
SELECT seri.htsern AS Serial
    ,seri.htpart AS PartNumber
    ,seri.htlotn AS Batch
    ,seri.htqty AS Quantity
    ,seri.htstkl AS Bin
    ,seri.htbinl AS Location
    ,serh.hvuser AS ReceivedBy
    ,serh.hvtdat AS RecievedDaten
    ,(serh.hvtime - 1 hour) AS TIME
FROM seri
LEFT JOIN serh ON hvsern = htsern
WHERE hvtdat BETWEEN '2019/10/01'
        AND CURRENT DATE
    AND hvtrnt = 'R'
    AND htplnt = 'GC'


text:
Q: Understanding the translation of a graph (horizontally) I have been having trouble understanding the translation of a graph. I understand the 'rule in the sense that the '$+$' shifts to the left and the '$-$' to the right when dealing with something like e.g. $f(x + 2) = f(x)$.
In the book I am using it has written that if $g(x) = f(x-c)$, where $c > 0$ then the value of $g$ at $x$ is the same as the value of $f$ at $x-c$.
So ...if $c = 2$ and my function for $g$ was $g(x) = x^2$ and I put in $x=3$ I'd get $9$. For $f(x-c)$ I don't quite understand this part. Am I wanting to put in the same $x$ (i.e. $x = 3$) which would give me $f(3-1) = f(1) = g(3) = 9$. When I do this it seems to work against how I thought it would go. To me this implies that in $g(x)$ when I input $3$ for $x$ I'd get a $y$ value of $9$. Then when I input $x=3$ in the function for '$f$' I'd end up with $f(1)$ provides me with $9$. It seems $g(1)$ is going back $2$ spaces to the left when compared to $f(3)$ in order to get the answer $9$ (based on $3-1 =2
$, from within the functions respective brackets)
Clearly I misunderstand something here.....

A: I personally think of it like this. Let's use the graphs of $f(x) = \sqrt{x}$ and $g(x) = \sqrt{x - 3}$.

In this picture, $f(x) = \sqrt{x}$ is in red. Now, when we look at $g(x) = \sqrt{x+3} = f(x+3)$, it's getting a head start, so it hits all the same $y$-values, but earlier than regular $\sqrt{x}$.
So, while $\sqrt{x} = 1$ when $x = 1$, the function $\sqrt{x+3} = 1$ when $x = -2$, which is $3$ units earlier than $f(x)$.

And this keeps happening! The function $f(x)$ is always $3$ units behind $g(x) = f(x + 3)$, if you think of the $x$-axis as time; the further to the left $g(x)$ is, the more of a head start it's got. So while $f(x) = 1$ when $x = 1$, the function $g(x)$ has already raced ahead, and $g(x) = 2$ when $x = 1$. It takes $f(x)$ an extra $3$ units to hit $f(x) = 2$, when $x = 4$.
That's what helps me understand the counter-intuitive horizontal shifts, anyway: it's going to take $f(x)$ longer than $f(x + 3)$ to reach the same spot in their journey. Being to the right on the $x$-axis means its taking longer (higher $x$-values) to get to the same spot.

A: You are correct in supposing that if you had some function $f(x)$, then if you let $c > 0$ and tried to plot $f(x-c)$, you would get the graph of $f(x)$ shifted $c$ to the right. So if $g(x) = f(x-c)$, then $g$ is the graph that results from shifting $f$ $c$ to the right.
The part where your confusion is forgivable is where you have a $g$ that is fixed, but you're trying to recover the original $f$. If as you suggest you fix $g(x) = x^2$, fix $c=2$ to get a handle on things, and define $f$ to be such that $g(x)=f(x-2)$, then $f$ must be the $x^2$-looking parabola whose vertex is at $(-2,0)$. (This is so because when you shift such a graph $2$ to the right, you get the $x^2$-looking parabola whose vertex is at $(0,0)$, i.e., $g$.)
Let's see this by plotting a few points:
$f(-5) = f(-3 - 2) = g(-3) = 9$
$f(-4) = f(-2 - 2) = g(-2) = 4$
$f(-3) = f(-1 - 2) = g(-1) = 1$
$f(-2) = f(0 - 2) = g(0) = 0$
$f(-1) = f(1 - 2) = g(1) = 1$
$f(0) = f(2 - 2) = g(2) = 4$
$f(1) = f(3 - 2) = g(3) = 9$
$f(2) = f(4-2) = g(4) = 16$
$f(3) = f(5 - 2) = g(5) = 25$
Notice how if you have to calculate values for $f$ in this scenario, you have to massage the input to $f$ a little bit to get it of the form into something that you do know to compute. The general description for this $f$ would be $f(x) = f((x+2)-2) = g(x+2) = (x+2)^2 = x^2 + 4x + 4$.
Usually, one starts with an $f$, and then shifts it around to obtain new graphs that obey the properties that they're interested in.

A: Original function: $g(x)= F(x-h)$ -used for horizontal translations only
If a positive number were used or plugged in for "$h$", then essentially it would become negative thus "$+$" equals left, to the negatives side or left. Similarly, if a negative number was used, then the two negatives would become a positive, so the graph would move to the positive side or right. This is why horizontal translations are counteractive.


text:
Q: How to accomplish the below PHP script in node.js. Here I am trying to bind the parameters of the insertOrganisation function. that is var=organisation, and var = parentId, to the values which am inserting into my sql database using the query below (insertQuery).
function insertOrganisation($organisation, $parentId) {

    // validate incoming parameters
    // I assume you are using PDO and have established a successful database connection
    $dbh = new PDO(......);
    $insertQuery = "INSERT INTO organization (org_name, parent_id) VALUES (:name, :parent_id) ON DUPLICATE KEY UPDATE parent_id = VALUES(parent_id)";
    $stmt = $dbh->prepare($insertQuery);
    $stmt->bindValue(':parent_id', $parentId, PDO::PARAM_INT);
    $stmt->bindValue(':name', $organisation->org_name, PDO::PARAM_STR);
    $stmt->execute();

Question is: How can i bind the parameters of the insertOrganisation() function, that is:  var = organisation, var = parentId to the values inserted by the query(insertQuery), that is (org_name, parent_id) in Node.js. Thanks in Advance

A:  var mysql = require('mysql');

 var con = mysql.createConnection({
     host: "localhost",
     user: "yourusername",
     password: "yourpassword",
     database: "mydb"
 });

con.connect(function(err) {
    if (err) throw err;
    console.log("Connected!");
    var sql = "INSERT INTO organization (parent_id, org_name) VALUES ?";
    var values = [
        [parentId, 'org_name'],
    ];
    con.query(sql, [values], function (err, result) {
        if (err) throw err;
        console.log("Number of records inserted: " + result.affectedRows);
   });
});


text:
Q: How do I programmatically mount zfs at boot? I encrypted my hard drive with zfs, running ubuntu 22.04.
I'm an idiot and forgot my password. However, I'm pretty confident that it is contained in a list of ~300 passwords that I know.
When I boot, I see a field to enter password, with text under it saying "Please unlock disk keystore-rpool"
Problem is, I only get 3 attempts at the password before the maximum number of attempts is reached. After I fail 3 times, I see a terminal with the error:
command: mount -o zfsutil -t zfs rpool/ROOT/ubuntu_{redacted} /root//
message: zfs_mount_at() failed: encryption key not loadedzfs_mount_at() failed: encryption key not loadedmount: mounting rpool/ROOT/ubuntu_{redacted} on /root// failed: Permission denied
Error: 2

Failed to mount rpool/ROOT/ubuntu_{redacted} on /root//.
Manually mount the filesystem and exit

And the user in the terminal is (initramfs).
When I try to run the zfs_mount_at() failed: encryption key not loaded command in this terminal, I immediately get the following same error as in the message above.
At this point I get stuck and am forced to hard reboot.
My question is: can I  write a script to programmatically try 3 passwords from the list, wait until I can try again (not sure how to set the wait part up, currently I have to manually hard reboot), and try the next 3, until the password succeeds?
Any help would be greatly appreciated here, the hard drive is pretty important, and I learned this lesson the hard way.


text:
Q: Why user.is_authenticated not working? django, LoginRequiredMixin I'm logged in.  why display NOT LOGIN! in html?
VIEWS

from django.contrib.auth.mixins import LoginRequiredMixin

class UserHomeView(LoginRequiredMixin, ListView):
    model = User
    template_name = 'users/users_index.html'
    paginate_by = 10
    context_object_name = 'user'

    def get_context_data(self, *, object_list=None, **kwargs):
        context = super().get_context_data(**kwargs)
        return context

HTML

{% if user.is_authenticated %}
LOGIN!
{% else %}
NOT LOGIN!
{% endif %}

setting.py
LOGIN_URL = '/users/login/'

A: try this {% if request.user.is_authenticated %}


text:
Q: Shared Element Listener Is I have defined a shared element animation (Going from Activity A to Activity B) using the following line of code (have defined appropriate values in my xml files - belive):
        ActivityOptionsCompat options = ActivityOptionsCompat.
            makeSceneTransitionAnimation(this, (View)sharedElement, "transitionName");

My question is, once this shared element is animated on Activity B, is there some sort of on finish listener for this shared element animation? I am asking this because I want to code a fade in animation for the rest of the content in Activity B, but want the fade in to occur only after the shared element animation has completed.

A: Of course, you can even change duration, add more transitions ...
To do in onCreate of Activity B:
Window window = getWindow();
TransitionSet set = new TransitionSet();
set.addTransition(new ChangeImageTransform());
set.addTransition(new ChangeBounds());
set.setDuration(duration);
set.addListener(yourTransitionListener);
window.setSharedElementEnterTransition(set);


text:
Q: installing gnome on my ubuntu 14.04LTS I'm trying to install the gnome desktop environment on my Ubuntu 14.04LTS using the command line:
$sudo apt-get install gnome-shell

but the terminal keeps saying:
"Some packages could not be installed. This may mean that you have
requested an impossible situation or if you are using the unstable
distribution that some required packages have not yet been created
or been moved out of Incoming.
The following information may help to resolve the situation:
The following packages have unmet dependencies:
 gnome-shell : Depends: gnome-settings-daemon (>= 3.4.0) but it is not going to be installed
               Recommends: gnome-control-center but it is not going to be installed
E: Unable to correct problems, you have held broken packages."

how do i fix this?

A: You can try this method of installation and you may not face any issue:

sudo add-apt-repository ppa:gnome3-team/gnome3-staging
sudo add-apt-repository ppa:gnome3-team/gnome3
sudo apt-get update
sudo apt-get dist-upgrade

To install all the GNOME 3 apps:

sudo apt-get install bijiben polari gnome-clocks gnome-weather
  gnome-maps gnome-music gnome-photos gnome-documents gnome-contacts
  epiphany-browser gnome-sushi gnome-boxes gnome-shell-extensions
  gnome-tweak-tool

copy paste these commands in terminal one-by-one.
NOTE:"The packages here have been deemed not ready for general use, they have known bugs and/or regressions, sometimes of a critical nature. Mostly things should run smoothly but be prepared to use ppa-purge, when you encounter issues"


text:
Q: How to detect overflow (or underflow) in Interlocked.Add I want to use an Interlocked.Add method because it's faster for int and long. I have following code for others types:
short x = Sum(source, range.Item1, range.Item2);
checked
{
    lock (syncRoot)
        result += x;
}

But I found that Interlocked doesn't handle overflows. How can I determine that overflow or underflow occured? x can be either positive or negative.
var x = Sum(source, range.Item1, range.Item2);
Interlocked.Add(ref result, x);
bool overflow = ...
if (overflow)
   throw new OverflowException();

I found following tip on MSDN but don't know how can I implement this check:

This method handles an overflow condition by wrapping: if the value at
  location1 is Int32.MaxValue and value is 1, the result is
  Int32.MinValue; if value is 2, the result is (Int32.MinValue + 1); and
  so on.No exception is thrown.

A: Interlocked.Add returns the new value. If the new value is smaller than the old value then overflow occurred. The problem is that you cannot obtain the old value this way.
You can use a CAS loop to atomically read the old value, check for overflow and atomically write the new value.
Note, that neither locks not interlocked operations scale at all. Interlocked ops are merely hardware locks. They are faster in absolute terms and do not suffer as much from contention. But doing this operation at a high frequency will not benefit from multiple CPUs at all.


text:
Q: "Cannot implicitly convert type void..." getting this error from async method When I try to run the code below I am getting an error that says "Cannot implicitly convert type void to "Program.trainDataResult".  I am just trying to return my trainDataResult object form the async method so I can use it with other methods in my app.  Any suggestions?  I am confused as to why the async method is returning void when I have specified that it should return the trainDataResult object wrapped in a task.
    using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Xml.Serialization;
using System.Xml;
using System.IO;

namespace ctaapijim
{
   public class Program
   {
       [XmlRoot(ElementName = "ctatt", DataType = "string", IsNullable = true)]
       public class trainDataResult
       {
           [XmlElement(ElementName = "tmst")]
           public string timeStamp { get; set; }

           [XmlElement(ElementName = "errCd")]
           public byte errorCode { get; set; }

           [XmlElement(ElementName = "errNm")]
           public string errorName { get; set; }

           [XmlElement(ElementName = "eta")]
           public trainData eta { get; set; }
       }

       [Serializable()]
       public class trainData
       {
           [XmlElement(ElementName = "staId")]
           public ushort stationId { get; set; }

           [XmlElement(ElementName = "stpId")]
           public ushort stopId { get; set; }

           [XmlElement(ElementName = "staNm")]
           public string stationName { get; set; }

           [XmlElement(ElementName = "stpDe")]
           public string stopDesc { get; set; }

           [XmlElement(ElementName = "rn")]
           public ushort runNum { get; set; }

           [XmlElement(ElementName = "rt")]
           public string routeName { get; set; }

           [XmlElement(ElementName = "destSt")]
           public ushort destStation { get; set; }

           [XmlElement(ElementName = "destNm")]
           public string destName { get; set; }

           [XmlElement(ElementName = "trDr")]
           public byte trainDir { get; set; }

           [XmlElement(ElementName = "prdt")]
           public string prdTime { get; set; }

           [XmlElement(ElementName = "arrT")]
           public string arrTime { get; set; }

           [XmlElement(ElementName = "isApp")]
           public ushort isApp { get; set; }

           [XmlElement(ElementName = "isSch")]
           public ushort isSch { get; set; }

           [XmlElement(ElementName = "isDly")]
           public ushort isDly { get; set; }

           [XmlElement(ElementName = "isFlt")]
           public ushort isFlt { get; set; }

           [XmlElement(ElementName = "flags")]
           public string flags { get; set; }

           [XmlElement(ElementName = "lat")]
           public double lat { get; set; }

           [XmlElement(ElementName = "lon")]
           public double lon { get; set; }

           [XmlElement(ElementName = "heading")]
           public ushort heading { get; set; }
      }

      private const string URL = "http://lapi.transitchicago.com/api/1.0/ttarrivals.aspx?key=d94463bf32094ac6bb1417cd8f850a23&mapid=41300&max=1";

      static void Main(string[] args)
      {
            trainDataResult td = RunAsync().Wait();
      }
      static async Task<trainDataResult> RunAsync()
      {
          using (var client = new HttpClient())
          {
              var response = await client.GetAsync(URL);
              if (response.IsSuccessStatusCode)
              {
                    //get data from CTA API
                  var xml = await response.Content.ReadAsStringAsync();
                  var ds = new XmlSerializer(typeof(trainDataResult), new XmlRootAttribute("ctatt"));
                  using (StringReader sr = new StringReader(xml))
                  {
                      using (XmlReader xr = XmlReader.Create(sr))
                      {
                          var trainDataResult = (trainDataResult)ds.Deserialize(xr);

                            return trainDataResult;
                            //calculate the difference in time between arrival time and current time
                           /* trainDataResult.eta.arrTime = trainDataResult.eta.arrTime.Substring(9);
                            TimeSpan trainTime = TimeSpan.Parse(trainDataResult.eta.arrTime);
                            var timeOfDay = DateTime.Now.TimeOfDay;
                            TimeSpan arrMins = (trainTime - timeOfDay);

                          Console.WriteLine("Station Name: {0}\nRoute Name: {1}\nArrival Time: {2}\nRun Number: {3}\nDirection: {4}", trainDataResult.eta.stationName, trainDataResult.eta.routeName, arrMins, trainDataResult.eta.runNum, trainDataResult.eta.stopDesc);
                          */
                      }
                  }
              }
              else
              {
                  Console.WriteLine("There was an error!");
              }
           }
        }
    }
}

A: You can't have a local variable with the same name as its type; the local variable will "hide" the name of the type.
Change the name of your class from trainDataResult to TrainDataResult, and the error should clear up.


text:
Q: Gated Clock in Clock Divider for a Square Wave I recently have been designing a clock divider for my system - which I redesigned, and now has an asynchronous reset, which generates a synchronous reset for the rest of the system. To do this, I followed the answers & advice to my own question and used a clock enable to toggle an output, thus generating clock with a 50% duty cycle (which is desired).
However, this has thrown up the error when generating the bitstream of
PhysDesignRules:372 - Gated clock. Clock net ... is sourced by a combinatorial pin. This is not good design practice. Use the CE pin to control the loading of data into the flip-flop.
Reading into this question about using the clock enable, it appears when creating a clock enable is correct, however, because I need a square wave (and not just a 1/200MHz pulse), and thus using the enable to toggle another signal, it appears in this question that this is an intentional gated clock.
So my questions are; is this gated clock warning significant? Both in simulation, and on an oscilloscope it appears to function correctly (so I'm inclined to ignore it), but am I storing problems for later? Is there a way of getting a very slow 50% duty cycle pulse without a gated clock?
I've put my code below!
Thanks very much (especially to the handful of people who have collectively given a lot of time to my recent non-stop questions)
David
library IEEE;
use IEEE.STD_LOGIC_1164.ALL;
use IEEE.NUMERIC_STD.ALL;
library UNISIM;
use UNISIM.VComponents.all;

ENTITY CLK_DIVIDER IS
    GENERIC(INPUT_FREQ : INTEGER;
            OUT1_FREQ  : INTEGER;
            OUT2_FREQ  : INTEGER
    );
    PORT(SYSCLK      : IN  STD_LOGIC;
         RESET_N     : IN  STD_LOGIC;
         RESET_N_OUT : OUT STD_LOGIC;
         OUT1        : OUT STD_LOGIC;
         OUT2        : OUT STD_LOGIC);
END CLK_DIVIDER;

architecture Behavioral of Clk_Divider is
    constant divider1 : integer   := INPUT_FREQ / OUT1_FREQ / 2;
    constant divider2 : integer   := INPUT_FREQ / OUT2_FREQ / 2;
    signal counter1   : integer   := 0;
    signal counter2   : integer   := 0;
    signal output1    : std_logic := '0';
    signal output2    : std_logic := '0';
    signal reset      : boolean;
begin
    reset_proc : process(RESET_N, SYSCLK)
        variable cycles        : integer := 0;
        variable reset_counter : integer := 0;
    begin
        if rising_edge(SYSCLK) then
            if cycles < 2 then
                if reset_counter >= divider1 then
                    cycles        := cycles + 1;
                    reset_counter := 0;
                else
                    reset_counter := reset_counter + 1;
                end if;
                reset <= true;
            else
                reset <= false;
            end if;
        end if;
        if RESET_N = '0' then
            cycles        := 0;
            reset_counter := 0;
            reset         <= true;
        end if;
    end process;

    output1_proc : process(SYSCLK)
    begin
        if rising_edge(SYSCLK) then
            if counter1 >= divider1 - 1 then
                output1  <= not output1;
                counter1 <= 0;
            else
                counter1 <= counter1 + 1;
            end if;
            if RESET_N = '0' then
                counter1 <= 0;
                output1  <= '1';
            end if;
        end if;
    end process;

    output2_proc : process(SYSCLK)
    begin
        if rising_edge(SYSCLK) then
            if counter2 >= divider2 - 1 then
                output2  <= not output2;
                counter2 <= 0;
            else
                counter2 <= counter2 + 1;
            end if;
            if RESET_N = '0' then
                counter2 <= 0;
                output2  <= '1';
            end if;
        end if;
    end process;

    OUT1        <= output1;
    OUT2        <= output2;
    RESET_N_OUT <= '0' when reset else '1';

end Behavioral;

A: The comments suggest, that the clock-divider is instantiated in a larger design.
If you want to use the generated clock there, you must add a BUFG between signal output2 and the output out2 like this:
out2_bufg : BUFG port map(I => output2, O => out2);

The component BUFG is defined in the library unisim.vcomponents. Same applies to output out1.
The BUFG ensures, that the generated clock is distributed using a clock-tree, so that the clock signal arrives at all destination flip-flops at the same time. This minimizes hold-time violations and gives more room for the setup of data signals.
If you still get the warning/error, then you combined the generated clock signal with another signal elsewhere in the larger design.

A: The reset_proc process is written with a elsif cycles > 1 then outside the clocked part, and with the condition derived from cycles which is also assigned as part of reset.  It is unclear what hardware is actually described here, but it makes the synthesis tool unhappy.
If you want to use RESET_N as asynchronous reset, then just make a simple if RESET_N = '0' then ... end if;, and assign whatever signals or variables required to be reset.  Other assignments should be moved to the clocked part.
NOTE: Code was changed after the above update... which may have removed the reason for the question.
Btw. RESET_N is used as asynchronous reset in the reset_proc, but as synchronous reset in the other processes, and this inconsistent use looks like there may be a potential problem with the reset scheme.


text:
Q: Count specific condition in 2d-array Given a 2D Array, count the number data at column 3 where it is the same.
For example,
 String[][] array = {
                    { "red", "value1", "alpha"  },
                    { "blue", "value2", "alpha"  },
                    { "green", "value3", "alpha"  },
                    { "black", "value4", "alpha" },
                    { "grey", "value1", "beta"  },
                    { "white", "value2", "beta"  },
            };

          int counter=0;
          for(String[] subArray : array)
              for(String string : subArray)
                  if(string.toLowerCase().equals("beta"))
                      counter++;

          System.out.println(counter);

The output of the counter for beta = 2 and alpha = 4.
Assuming I don't know what is the exact name of the data in column 3, how I count the conditions? if(string.toLowerCase().equals(???))
Any help will be appreciated!

A: It could be something like this using groupingBy in java 8:
 Arrays.stream(array)
       .collect(Collectors.groupingBy(arr -> arr[2], Collectors.counting()));

Result will:
{alpha=4, beta=2}

B.T.W If you want to ignore case, do it as:
Arrays.stream(array)
      .collect(Collectors.groupingBy(arr -> arr[2].toLowerCase(), Collectors.counting()));

A: Create a Map<String, int>
Look for the value of string.toLowerCase in the Map and if it is found increment the value of int else insert with the value of 1

A: There are many ways, but one way:

*

*Create a new multidimensional array of types string:int.

*Iteratethrough your array at the last index, and then check if it exists in your array you made.

*If it exists, inremement the int to int+1.

*If it does not exist, add it and add int=1


text:
Q: AngularJS filter triggers infinite $digest loop I want to use a filter expression like values | filter:value1 to hide or show a div, where values and value are both declared on the scope in the containing directive's link function.
This works as expected, except that it keeps firing off infinite digest loop errors.
See this jsbin for a demonstration: http://jsbin.com/nujineci/2/edit
What am I doing wrong? Why should these errors occur when no models are being updated by the filter?

A: May be because of using filter inside ng-show, filter gets executed in every digest cycle, and keeps checking your value is changed or not, if value is changed then it evaluates again and gives new result, otherwise it doesn't do anything (becaues angularJs uses "dirty-checking" method to find any change)
http://jsbin.com/nujineci/4/edit
check this link, i have modified
ng-show="g.values | filter:g.value1"

To
ng-show="g.values.indexOf(g.value1) != -1"

or ng-show="g.values.indexOf(g.value1) > -1" // this is same as above
indexOf returns index of item if exists in array, otherwise returns -1
I use this type of syntax, never had any problem with this

A: The answer to the problem is in the error description that Angular provides.

One common mistake is binding to a function which generates a new
  array every time it is called

This is basically what filter does, each time it returns new array:
// some more code
var filtered = [];
for ( var j = 0; j < array.length; j++) {
  var value = array[j];
  if (predicates.check(value)) {
    filtered.push(value);
  }
}
return filtered;

When Angular's digest loop runs for the first time it gets an array containing 'bar' and an empty array. Then Angular will run digest loop again to check if the model is stable. It will get new arrays (instances) and it will think that the model has changed. This will cause another digest loop, and so on.
You should check if your array contains values and ng-show on that. E.g.
Determine whether an array contains a value
Check out this modified jsbin: http://jsbin.com/nujineci/5/edit


text:
Q: Codeigniter form validation alpha So i have question with codeigniter. In form validation, alpha means only a, b, c and so on... But what i must do if in my language is alphabet that not aloved by alpha fomr validation? Codeigniter not letting my write that simbols.

A: Use a callback function that validates special characters in addition to a-z.


text:
Q: Tag on create AWS IAM Policy In a AWS shared account some of the Engineers not tagging the resources and they have Power user access. Is there any way restrict the IAM user cannot create any resource without tag.
I tried Tag on create IAM policy, its only working for EC2 and not power user access.
Thanks.

A: Firstly, try to avoid granting Power User access to typical users. It lets them do anything they want (except for IAM). You'll need to reduce their assigned permissions if you wish to limit what they are able to do.
It is possible to require tags on Amazon EC2 instances (which sounds like what you are doing already): AWS IAM Policy to Enforce Tagging
An alternate approach is to use AWS Config to look for resources that are not tagged and then either make a report, send a notification or (in extreme circumstances) delete the offending resources. The users will get upset, but they will learn their lesson!
(It would be fun instead to build a system that charges them personally for any resources they created but didn't tag appropriately!)


text:
Q: docker exec command not executing in sh file When running below command in command line(terminal) this gets executed fine:
$sudo docker exec -it 5570dc09b58 bash

But same results with :

FATA[0000] cannot enable tty mode on non tty input

Error when running in a shell script file.

A: Scripts may be forced to run in interactive mode with the -i option or with a #!/bin/bash -i header.
So adding shebang to the script with -i option should work:
#!/bin/bash -i

docker exec -it ed3d9e46b8ee date

Run the script as usual:
chmod +x run.sh
sudo ./run.sh

Output:
Thu Apr  2 14:06:00 UTC 2015

A: You are not running docker in a terminal, so you should remove -t from -it:
sudo docker exec -i 5570dc09b58 bash

See a more detailed answer here.

A: There are few images which do not support the interactive shell/bash.
Example - Docker image mockserver/mockserver
Docker Set Up


text:
Q: Change Wordpress Category Widget Placeholder Text? I have tried all the solutions on this site, but none seem to work, so starting a new thread.
I am trying to change the placeholder text on the Wordpress Category Widget. Currently it defaults to 'Select Category'.
I have tried adding below code to functions.php and I've also tried creating a specific plugin with this code, but hasn't worked. I also changed the widget's core code.
function ChangeSelectTitle($cat_args){
    $cat_args['show_option_none'] = __('My Category');
    return $cat_args;
}
add_filter('widget_categories_dropdown_args', 'ChangeSelectTitle');


text:
Q: Undefined property exception when trying to instantiate dependency from IOC container I'm trying to deepen my knowlade in laravel architecture.

*

*I have a search engine (elastic search for the sake of the example), but this search engine might change in the future. So im trying to write a container for this, so in case i'll change the engine in the future, i will have to change only the container. (I believe the termenology is factory design?)

*I have created a provider app/providers/DataFromSearchEngine.php that looks like this:
use Illuminate\Support\ServiceProvider;

class DataFromSearchEngine extends ServiceProvider {
   public function boot()
   {
    //
   }

   public function register()
  {
    $this->app->singleton('SearchEngine', function($app) {
       return new elasticSearch;
    });
  }

}

*Then i registered it in the providers array in config/app.php .
'providers' => [
    // providers...

    'App\Providers\DataFromSearchEngine'
],

*The next step is to call SearchEngine from my controller:
namespace App\Http\Controllers;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;

class SearchController extends Controller {

   protected $searchEngine;

   public function __construct() {
      $this->searchEngine = $this->app->make('SearchEngine');
   }

}

But all these yields: Undefined property: App\Http\Controllers\SearchController::$app
Can someone explain what i'm missing?

A: Instead of using $this->app try using app().
This is because non of the inherited controller classes, i.e. App\Http\Controllers\Controller or Illuminate\Routing\Controllers\Controller have an app property on them.
As a note you can use app('SearchEngine') which is the equivalent of app()->make('SearchEngine') as a shortcut to making your object.

A: I had this issue when trying to create a service provider. I registered my service provider in AppServiceProvider.php but was still getting this same error. The issue was that in my ServiceProvider I needed to add extends ServiceProvider to my class. Seems simple but is often forgotten.


text:
Q: Codeigniter - using set_value() to populate a form for editing (with no POST involved) I have a view containing a form. with input fields and radio buttons. This form needs to be populated with the data from database, so as to use it as an data editing form.
I have used the set_value() function for the form validation where the view is called from the same controller after the post. But how to use set_value function with out a POST? i.e. simply populate the values in a form in the view that's loaded. with say, an Array or object from database.

A: You try this code
set_value('<field_name>', @$field_from_db);

@ is used to skipps errors if field is not set

A: You can use it like this
set_value('myfield', isset($databaseData['myfield']) ? $databaseData['myfield'] : '');

$databaseData will contain the data from the database which you have loaded in the controller and passed to view
$data['databaseData']= $this->my_model->find($parameters);

$this->load->view('myformview',$data);


text:
Q: PhpStorm: Failed to parse validation script output PHP version not installed Debugger not Installed I'm on Windows 10 x64 and today I wanted to install a new version of XAMPP. What I did was to uninstall my current one and then remove PHP from the environment variables. After that, I downloaded XAMPP as usual and installed it along with Xdebug, the same way that has worked for me during the past two years.
When I opened PhpStorm and went to set the CLI interpreter I noticed that it said "PHP version: Not installed" and "Debugger: Not installed" (although I have the PHP executable set to C:\xampp\php\php.exe).
What I did after that was to try reinstalling PhpStorm, both with my current settings and then other settings. It didn't help.
Upon checking the PHP version in the command line it does say that I have the new version installed. I am also able to do a simple echo 'hello'; and have it printed in the browser on my localhost. I'm not sure what to make of that. However, debugging inside PhpStorm does not work despite seeing on my PHPinfo that Xdebug is installed.
After googling around I don't see much that is relevant to what I'm doing. It seems like everyone who faces this issue is using a remote interpreter and a mac.
Does someone know what to do about it with my settings or have any suggestions on how to get this solved?
Setup:

*

*Windows 10 Version 1903 for 64

*xampp-windows-x64-7.4.1-0-VC15-installer

*PhpStorm 2019.3.1

*PHP 7.4.1

*Zend Engine v3.4.0, with Xdebug v2.9.0

Error message:
Failed to parse validation script output

A: In my case Comodo Internet Security (CIS) was adding php.exe to blocked applications.
Unblocking it fixed the issue.
My config:

*

*PHP 7.4.5 64 NTS

*Windows 10 1909

*PhpStorm 2020.1


text:
Q: Testing anova hypothesis with contrasts in R and SPSS Using data and answers from this question I was trying to test the hypothesis $H_0:-3\mu_1-\mu_2+\mu_3+3\mu_4=0$
set.seed(42)
sample.data <- data.frame(IV=factor(rep(1:4, each=20)),
                          DV=rep(c(-3, -1, 1, 3), each=20) + rnorm(80))
library(car)
Anova(lm(DV ~ C(IV, c(-3, -1, 1, 3), 1), data=sample.data), type="III")

Anova Table (Type III tests)

Response: DV
                          Sum Sq Df  F value Pr(>F)
(Intercept)                 0.03  1   0.0278 0.8681
C(IV, c(-3, -1, 1, 3), 1) 407.08  1 347.9506 <2e-16 ***
Residuals                  91.25 78
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

But when I tried to verify my result with SPSS i got

So my question is why $F$ statistics are different? My guess is that I might have misspecified contrasts in R. I as well tried to set type="II", but as this is balanced sample the $F$'s are the same.
I also have an additional question, concerning $F$'s value of (Intercept) term in the output of R, is this a statistic for testing whether the intercept in the model is zero?

A: The SPSS model has four terms in it (intercept plus a linear contrast term plus two deviation terms).  The R model only has two (intercept plus linear contrast).  This means the residual term in SPSS is both smaller and has less df than the model in R.  Note that 88.596 + 2.658 = 91.25, so the two models have the same total sum of squares but are dividing it up differently.
To get the same output as SPSS, add any two contrasts that aren't linear and that result in the full basis for the four terms.
Here are quadratic and cubic contrasts:
> c1 <- c(-3, -1, 1, 3)
> c23 <- cbind(c(4, 1, 1, 4), c(-8, -1, 1, 8))
> m <- lm(DV ~ C(IV, c1, 1) + C(IV, c23, 2), data=sample.data)
> anova(m)
# Analysis of Variance Table

# Response: DV
#               Df Sum Sq Mean Sq  F value Pr(>F)
# C(IV, c1, 1)   1 407.08  407.08 349.1991 <2e-16 ***
# C(IV, c23, 2)  2   2.66    1.33   1.1399 0.3252
# Residuals     76  88.60    1.17

Here are dummy variables on the first and fourth levels.
> cxx <- cbind(c(1, 0, 0, 0), c(0, 0, 0, 1))
> m <- lm(DV ~ C(IV, c1, 1) + C(IV, cxx, 2), data=sample.data)
> anova(m)
# Analysis of Variance Table
#
# Response: DV
#               Df Sum Sq Mean Sq  F value Pr(>F)
# C(IV, c1, 1)   1 407.08  407.08 349.1991 <2e-16 ***
# C(IV, cxx, 2)  2   2.66    1.33   1.1399 0.3252
# Residuals     76  88.60    1.17

To get the same output for just the linear term, it's perhaps easier to treat IV as continuous and just add the polynomial terms.
> sample.data$IVn <- as.numeric(sample.data$IV)
> m <- lm(DV ~ IVn + I(IVn^2) + I(IVn^3), data=sample.data)
> anova(m)
# Analysis of Variance Table
#
# Response: DV
#           Df Sum Sq Mean Sq  F value Pr(>F)
# IVn        1 407.08  407.08 349.1991 <2e-16 ***
# I(IVn^2)   1   1.95    1.95   1.6723 0.1999
# I(IVn^3)   1   0.71    0.71   0.6075 0.4381
# Residuals 76  88.60    1.17

You could also fit it with polynomial contrasts, but I don't think it's easy to get the linear term only in an ANOVA table, but you could get the coefficients.  Notice that 18.687^2 = 349.2, so it's the same result as before, just presented differently.
> m <- lm(DV ~ C(IV, "contr.poly"), data=sample.data)
> summary(m)
#
# Call:
# lm(formula = DV ~ C(IV, "contr.poly"), data = sample.data)
#
# Residuals:
#     Min      1Q  Median      3Q     Max
# -2.9922 -0.5409  0.1351  0.6918  2.1662
#
# Coefficients:
#                       Estimate Std. Error t value Pr(>|t|)
# (Intercept)            0.02015    0.12071   0.167    0.868
# C(IV, "contr.poly").L  4.51152    0.24143  18.687   <2e-16 ***
# C(IV, "contr.poly").Q  0.31221    0.24143   1.293    0.200
# C(IV, "contr.poly").C -0.18818    0.24143  -0.779    0.438

The anova table combines all three terms.
> anova(m)
# Analysis of Variance Table
# Response: DV
#                     Df Sum Sq Mean Sq F value    Pr(>F)
# C(IV, "contr.poly")  3 409.73 136.578  117.16 < 2.2e-16 ***
# Residuals           76  88.60   1.166


text: Q: How to upload multiple XMLs in Tally Accounting Software? I am currently uploading single sales XML in Tally. I want to know how can i bulk upload multiple XML's at 1 time? I have to upload multiple XML's in a day and that takes a lot of my time.


text:
Q: Высота родителя флексбока не работает процентах Как сделать высоту родительского блока в процентах (На самом деле мне нужно padding-bottom в %)
Вот что я хочу сделать, но только высоту не фиксированную, а в процентах Демо

UPD
Решил я в общем свою проблему, дав главному блоку абсолютную позицию и обернув его в другой див, который и задает размеры demo


text:
Q: when datepicker class is used in input field, bootstrap datepicker (autoclose,endDate,startDate) doesn't work the following code is not working if I add datepicker in the input field class
JS
$(document).ready(function () {
  $("#ActionDateInput").datepicker({
    autoclose: true,
    endDate: new Date()
  });
});

HTML
<input type="text" id="ActionDateInput" class="datepicker form-control" placeholder="Date" name="date" autocomplete="off"/>

But if I remove datepicker from the class, it works.
HTML
<input type="text" id="ActionDateInput" class="form-control" placeholder="Date" name="date" autocomplete="off"/>

I want to keep the datepicker in the class for design purpose.  I used bootstrap-datepicker
<script src="${contextPath}/resources/asset/js/bootstrap-datepicker.js"></script>

A: The datepicker class is used by the bootstrap-datepicker plugin. If you download the plugin's sources, in the bootstrap-datepicker.css file you can see that there is styling applied to the mentioned class and on some children elements of it. That is why everything works fine when you either not use it or when you rename it.
Thus, I would strongly recommend you NOT to use the datepicker class since it is used
by the plugin internally.

A: Try it:
 $("#ActionDateInput").datepicker().datepicker("setEndDate",new Date());


text:
Q: How to call parents function from child in Javascript How can I call a parents function in the Child class with the current context (this) of the Child?
I tried to use Parent.testFunc.call(this); but I get an error (Cannot read property 'call' of undefined).
function extend(Child, Parent) {
    Child.prototype = Object.create(Parent.prototype);
    Child.prototype.constructor = Child;
}

var Parent = function(){
    this.test = function(){
        alert("worked");
    };
};

var Child = function(){
    Parent.call(this);

    //THIS GIVES THE ERROR **
    Parent.test.call(this);
};

extend(Child, Parent);

var child = new Child();

How can I call the parent function called test from the Child keeping the same context (this) ?

A: In that case, you'd just use
this.test();

...because the function is attached directly to the instance itself by the Parent function.
Example:

function extend(Child, Parent) {
    Child.prototype = Object.create(Parent.prototype);
    Child.prototype.constructor = Child;
}

var Parent = function(){
    this.test = function(){
        console.log("worked");
    };
};

var Child = function(){
    Parent.call(this);

    this.test(this);
};

extend(Child, Parent);

var child = new Child();

In general, it doesn't matter at what level the function was created, you can access it on this. The only hassle is when you have a function that's redefined. For instance, where Parent has test and then you also want Child to have its own version of test but want Child instances to also be able to call Parent's test (perhaps from Child's).
That's difficult to arrange when you create functions in the constructor as you're doing, but easier (though still verbose and awkward) when you put them on the prototype.
Just for completeness:

function extend(Child, Parent) {
    Child.prototype = Object.create(Parent.prototype);
    Child.prototype.constructor = Child;
}

var Parent = function(x){
    this.x = x;
};
Parent.prototype.test = function() {
    console.log("Parent's test, x = " + this.x);
};

var Child = function(x){
    Parent.call(this, x);

    this.test(this);
};
extend(Child, Parent);
Child.prototype.test = function() {
    Parent.prototype.test.call(this);
    console.log("Child's test, x = " + this.x);
};

var child = new Child(42);

And finally, that example is much simpler with ES2015+ class syntax:

class Parent {
    constructor(x) {
        this.x = x;
    }
    test() {
        console.log("Parent's test, x = " + this.x);
    }
};

class Child extends Parent {
    constructor(x) {
        super(x);
        this.test();
    }
    test() {
        super.test();
        console.log("Child's test, x = " + this.x);
    };
};

const child = new Child(42);

...which you can use now on cutting-edge browsers, and others with transpiling (perhaps with Babel).


text:
Q: Formato fecha JavaScript Estoy teniendo problemas al formatear la fecha.
Por cuestión de versión, no puedo definir un campo tipo date, así que debo definirlo tipo datetime y me agrega varios 0 al final.
Obtengo de un json esto:
Object {fecha_desde: "2017-01-01 00:00:00.000", fecha_hasta: "2017-04-30 00:00:00.000"}

Y mi intento es este:
<script>
          $(document).ready(function(){
            $('#cuatrimestre').on('change',function(){
                var cuatrimestre = $(this).val();
                $.ajax({
                    url : "getCuatri.php",
                    dataType: 'json',
                    type: 'POST',
                    async : false,
                    data : { cuatrimestre : cuatrimestre},
                    success : function(data) {
                        console.log(data)
                        //userData = JSON.parse(data);
                        var desde = String(data.fecha_desde).split('-');
                        var fechaDesde = desde[1] + '-' + desde[2] + '-' + desde[0];
                        $('#desde').val(fechaDesde);
                        var hasta = String(data.fecha_hasta).split('-');
                        var fechaHasta = hasta[1] + '-' + hasta[2] + '-' + hasta[0];
                        $('#hasta').val(fechaHasta);
                        //$('#hasta').val(data.fecha_hasta);
                    }
                });
            });
         });
        </script>

Pero obtengo esto:
01-01 00:00:00.000-2017
04-30 00:00:00.000-2017

En el modo test que tengo el campo de tipo date, me funciona perfecto.

A: Esto no funciona como esperas:
String(data.fecha_desde).split('-');

Ya que separará tres grupos, por eso se ve el tiempo junto con el mes:
mes / dia / año tiempo

Puedes convertir la fecha en texto a un objeto Date y luego el método toLocaleString para obtener solo el mes, día y año de la fecha. También puedes usar moment. El siguiente ejemplo usa ambas formas.
Ejemplo

let fechas = {
  desde: '2017-01-01 00:00:00.000',
  hasta: '2017-04-30 00:00:00.000'
};

let desde = parseDate(fechas.desde);
let hasta = moment(fechas.hasta).format('MM-DD-YYYY');

console.log('Desde:', desde);
console.log('Hasta (moment):', hasta);

function parseDate (isodate) {
  return (
    new Date(isodate)
      .toLocaleString('en-US', {
        month: '2-digit',
        day: '2-digit',
        year: 'numeric'
      })
      .replace(/\//g, '-')
  );
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.17.1/moment.min.js"></script>

A: Convierte el objeto a Date de esta manera
var desde = new Date(data.fecha_desde);

y para obtener el valor puedes usar .toLocaleDateString() que te devolverá la fecha en formato d/m/yyyy
Si quieres cambiar de formato en este caso dd/mm/yyyy habria que seleccionar una Zona en mi caso es-MX y después las opciones a considerar:
{year: 'numeric', month: '2-digit', day: '2-digit' }

para mas informacion sobre las opciones aqui
Te dejo tu ejemplo

var data = {fecha_desde: "2017-01-01 00:00:00.000", fecha_hasta: "2017-04-30 00:00:00.000"}

console.log(data)
//userData = JSON.parse(data);

var options = {year: 'numeric', month: '2-digit', day: '2-digit' };

var desde = new Date(data.fecha_desde);
console.log(desde.toLocaleDateString("es-MX", options))
$('#desde').val(desde);

var hasta = new Date(data.fecha_hasta);
console.log(hasta.toLocaleDateString("es-MX", options))
$('#hasta').val(hasta);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


text:
Q: How to return value of db calls from a asynchronous function I was looking for an answer and found this. Like in jquery there is when function. Using some guidelines to synchronize my asynchronous calls I am using async.js in Node
Here is the code.
async.forEach(dateInDateFormat, function(item, callback) {
        console.log(moment(item.startDate).toDate());
        var result = Trip.aggregate([{
            "$unwind": "$trips"
        }, {
            "$match": {
                "trips.startTime": {
                    "$gte": moment(item.startDate).toDate(),
                    "$lte": moment(item.endDate).toDate()
                }
            }
        }, {
            "$group": {
                "_id": {
                    "date": {
                        "$dayOfMonth": "$trips.startTime"
                    }
                },
                "distance": {
                    "$sum": "$trips.distance"
                }
            }
        }]);
        result.exec(function(err, doc) {
            console.log(doc);
        });
        console.log("Executing callback");
        callback();
    }, function(error) {
        console.log("Loop over");
    });

This is the output.
Executing callback
Loop over
[ { _id: { date: 23 }, distance: 0 },
{ _id: { date: 22 }, distance: 0 },
{ _id: { date: 21 }, distance: 0 } ]
[ { _id: { date: 29 }, distance: 210 },
  { _id: { date: 27 }, distance: 210 },
  { _id: { date: 26 }, distance: 210 },
  { _id: { date: 25 }, distance: 0 } ]
[]

As you can see. Executing callback and Loop over are executed before I get the data. I cannot send it back to my Angular Frontend using res.send().
One answer is you cannot return a value from a asynchronous function. You only return a callback. How do I do that in this case?
Or
How do I use the async.series([]) function. Because I used that also and even that is not giving me exact results.
Thanks
EDIT
Answer in short, the position of callback function matters. If you give it at wrong place don't expect write answers. Please see the code in the answer and comment thread for better explanation.

A: The callback is kind of magic and just indicates to async.foreach that a specific foreach execution has completed.  I am not familiar with the aggregate function or the exec, so I'm assuming that aggregate builds a query, and exec is executing that query asynchronously.
The forEach callback could be moved to the result.exec result.  This would indicate to async that the execution of that particular query is over.  When all executions are over the function passed as the second param to forEach will be executed. When it is executed, all functions have completed or an error has occurred, in which case you can send to res.
The overall flow:

*

*Create a list of data to operate on asyncronously

*Execute a function (2nd param to async.forEach) against each item in your list asyncronously.

*

*build aggregation query

*exeucte aggregation query asynchronously

*Indicated to  async.foreach that aggregate operation has been completed by calling callback function

*When callback has been called for each item in the array async will call the function that was passed as 3rd param to async.forEach.

*Return result to client because all tasks have been resolved.

async.forEach(dateInDateFormat, function(item, callback) {
        console.log(moment(item.startDate).toDate());
        var result = Trip.aggregate([{
            "$unwind": "$trips"
        }, {
            "$match": {
                "trips.startTime": {
                    "$gte": moment(item.startDate).toDate(),
                    "$lte": moment(item.endDate).toDate()
                }
            }
        }, {
            "$group": {
                "_id": {
                    "date": {
                        "$dayOfMonth": "$trips.startTime"
                    }
                },
                "distance": {
                    "$sum": "$trips.distance"
                }
            }
        }]);
        result.exec(function(err, doc) {
            console.log(doc);
            console.log("Executing callback");
            callback();
        });
    }, function(error) {
        // all tasks passed to forEach have been completed, or
        // an error has occurred
        res.send('COMPLETE');
        console.log("Loop over");
    });

It's crazy to me how a simple operation can have such a crazy programming flow :)


text:
Q: Invalid WebSocket frame: MASK must be clear I'm using the ws package to connect to the poloniex web socket, using the following code:
const WS = require('ws');

const ws = new WS('wss://api2.poloniex.com');
ws.on('open', () => {
    ws.send(JSON.stringify({
        command: 'subscribe',
        channel: 'USDT_BTC'
    }));
});
ws.on('message', (msg) => {
    console.log(JSON.parse(msg));
    ws.close(1000);
});
ws.on('close', (code) => {
    console.log(`closing with code ${code}`);
});
ws.on('error', (error) => {
    console.error(error);
});

Hovewer I get the following output:
RangeError: Invalid WebSocket frame: MASK must be clear
    at Receiver.getInfo (/home/clecio/Programming/test-poloniex/node_modules/ws/lib/receiver.js:299:14)
    at Receiver.startLoop (/home/clecio/Programming/test-poloniex/node_modules/ws/lib/receiver.js:136:22)
    at Receiver._write (/home/clecio/Programming/test-poloniex/node_modules/ws/lib/receiver.js:83:10)
    at writeOrBuffer (internal/streams/writable.js:358:12)
    at Receiver.Writable.write (internal/streams/writable.js:303:10)
    at TLSSocket.socketOnData (/home/clecio/Programming/test-poloniex/node_modules/ws/lib/websocket.js:1116:35)
    at TLSSocket.emit (events.js:400:28)
    at addChunk (internal/streams/readable.js:293:12)
    at readableAddChunk (internal/streams/readable.js:267:9)
    at TLSSocket.Readable.push (internal/streams/readable.js:206:10) {
  code: 'WS_ERR_UNEXPECTED_MASK',
  [Symbol(status-code)]: 1002
}
closing with code 1006

Does any one know what this error means? I tried a similar code with similar servers and I don't get any error. Also, if I don't send any code  to the function ws.close(), I don't get any error. Does any one knows why this happens? What

A: Just learned this trying to do my own WebSocket implemetation in C#.
What the error means by "MASK must be clear" is that the data isn't expected to be masked; meaning omit the XOR key and don't encode the payload.
Byte exmaple of a frame sending "hi" encoded:
     Mask bit set and 7-bit payload length
     vv
{81, 82, 97, 34, 89, 6A, FF, 5D}
         ^^^^^^^^^^^^^^  ^^^^^^
         Mask Key        Encoded Payload

Byte exmaple of a frame sending "hi" unencoded:
Note there is no mask key.
     Mask bit not set and 7-bit payload length
     v
{81, 2, 68, 69}
        ^^^^^^
        Raw Payload

Since you seem to be working with a WebSocket library in JS, I'd look to see if there's a parameter you must set that is encoding what your ws.send() is doing.


text:
Q: Showing that $P(AB) \geq P(A) + P(B) - 1$ Proof that $P(AB) \geq P(A) + P(B) - 1$
Is this proof sufficient?
By contradiction: Assume $P(AB) < P(A) + P(B) - 1$
if $P(A) + P(B) = 1$, then
$P(AB) < 0$, which contradicts Axiom 1.

A: On the one hand, we have
\begin{align*}
\mathbb{P}(A\cup B) = \mathbb{P}(A) + \mathbb{P}(B) - \mathbb{P}(A\cap B) \leq 1 \Rightarrow \mathbb{P}(A\cap B) \geq \mathbb{P}(A) + \mathbb{P}(B) - 1
\end{align*}
On the other hand, we have
\begin{align*}
\begin{cases}
\mathbb{P}(A\cap B) \leq \mathbb{P}(A)\\\\
\mathbb{P}(A\cap B) \leq \mathbb{P}(B)
\end{cases} \Rightarrow \mathbb{P}(A\cap B) \leq \min\{\mathbb{P}(A),\mathbb{P}(B)\}
\end{align*}
Since $\mathbb{P}(A\cap B) \geq 0$, we conclude that
\begin{align*}
\max\{\mathbb{P}(A) + \mathbb{P}(B) - 1,0\} \leq \mathbb{P}(A\cap B) \leq \min\{\mathbb{P}(A),\mathbb{P}(B)\}
\end{align*}
Hopefully this helps!


text:
Q: mysql does not accept "?" as bind operator Trying to run a query to update a database, and for some reason, MySQL returns:

Error Code: 1064. You have an error in your SQL syntax; check the
manual that corresponds to your MySQL server version for the right
syntax to use near '?' at line 1

Tried the line just in SQL to see what happened
INSERT INTO eu_profile (id, profileName) VALUES ?

It also fails with the same message in the code:
import * as mysql2  from 'mysql2';
import * from 'mysql2/promise'

/** Lets open the database for mysql2 */
const mysql2connection = mysql2.createConnection({
    "host": "localhost",
    "port": 3306,
    "user": "node",
    "password": "NotTellingYou",
    "database": "stats"
});
mysql2connection.connect(function(error){
    if(!!error){
        console.log(error);
    }else{
        console.log('Connected!:)');
    }
});

    let dbTables: string="";
    let sqlInsert: string="";
    dbTables = "id, profileName";
    sqlInsert = "INSERT INTO eu_profile ("+dbTables+") VALUES ?"

    const profileLoad = await mysql2connection.query(sqlInsert, [profileData], function(err) {
        if (err) throw err{
        mysql2connection.end();
        }else
    }).then(console.log("We are done here"));

Version:

A: If you have two columns you need tiw values
INSERT INTO eu_profile (id, profileName) VALUES (?,?)

Also [profileData] needs 2 values like [req.body.topic, req.body.note]


text:
Q: evaluate the improper integral
$$
\int_0^{\pi/2} \ln\left( \tan^2\left( \frac\pi4 + x \right) \right) \tan x\, dx
$$
I tried to solve this question by substitution and let $u=\tan x$
And then using integration by parts or substitution
But I want another method to solve it

A: ** just a hint**
$$\int_0^\frac \pi 2=\int_0^\frac \pi 4+\int_\frac \pi 4^\frac \pi 2$$
$$\ln (\tan^2 (A ))=2\ln (|\tan (A)|) $$
$$\tan (x+\pi/4)=\frac {1+\tan (x)}{1-\tan (x)} $$
put $t=\tan (x) $
then by parts.


text:
Q: can cv::convexHull be applied to double-precision points data The following code works fine:
typedef cv::Point cvp;

    std::vector <cvp> points{ cvp(0, 0), cvp(1, 0), cvp(0, 1), cvp(0.5, 0.5) };
    std::vector<cvp> hullPoints;

    cv::convexHull(points, hullPoints);

However, when I change the definition of cvp:
typedef cv::Point2d cvp;  // cvp is now a double-precision point

the program crashes on entering the cv::convexHull procedure. Looks like
either cv::convexHull may be called only for integer-valued points, or I am doing something terribly wrong.
I found nothing on this issue in OpenCV documentation.

A: convexHull works only with Point2i (same as Point) and Point2f.
See the code for reference:
CV_Assert(total >= 0 && (depth == CV_32F || depth == CV_32S));

So you can work with floating point values, but they must be float, not double:
typedef cv::Point2f cvp;


text:
Q: Under what circumstanses will AppDomain.DoCallback() fail? I'm trying to use AppDomain to load and unload assemblies run-time. I'm trying to get the example on MSDN working in my application before implementing assembly loading, but I'm running into issues - the DoCallback-invokation fails with exception

Could not load file or assembly '[MyPluginAssembly], Version=1.0.0.0,
  Culture=neutral, PublicKeyToken=null' or one of its dependencies. The
  system cannot find the file specified.

My assembly ([MyPluginAssembly]) is running loaded by a host application (i.e. it is a plugin). The plugins AppDomain seem to be the application-domain (i.e. it is not sandboxed in a separate domain). I've tried loading the entry/calling/executing-assembly in the new domain to ensure [MyPluginAssembly] is loaded, but even though these calls return non-null I still get the exception above.
The code I use (as in the example on MSDN + the code to load the "parent"-assemblies):
public class PingPong : MarshalByRefObject
{
    private string greetings = "PING!";

    public static void Main()
    {
        AppDomain otherDomain = AppDomain.CreateDomain("otherDomain");
        // All of these Load()-calls returns non-null
        Assembly entryAssembly = otherDomain.Load(Assembly.GetEntryAssembly().GetName());
        Assembly callingAssembly = otherDomain.Load(Assembly.GetCallingAssembly().GetName());
        Assembly executingAssembly = otherDomain.Load(Assembly.GetExecutingAssembly().GetName());

        PingPong pp = new PingPong();
        pp.MyCallBack();
        pp.greetings = "PONG!";
        otherDomain.DoCallBack(new CrossAppDomainDelegate(pp.MyCallBack));

        // Output:
        //   PING! from defaultDomain
        //   PONG! from defaultDomain
    }

    // Callback will always execute within defaultDomain due to inheritance from
    // MarshalByRefObject
    public void MyCallBack()
    {
        string name = AppDomain.CurrentDomain.FriendlyName;
        if (name == AppDomain.CurrentDomain.SetupInformation.ApplicationName)
        {
            name = "defaultDomain";
        }
        Console.WriteLine(greetings + " from " + name);
    }
}

What circumstances can cause the exception I get?

A: You should look at the CreateInstanceFromAndUnwrap method. It is the one to use for sandboxed add-in scenarios like yours. System.AddIn (MAF) is using this method to load the add-in pipeline segments.


text:
Q: eBooks download website, page or post? I am creating an eBooks download website. There will be around 5000 eBooks. Each page/post will have a download link to the pdf file of the eBook. My question is, should I create 5000 pages or 5000 posts for these eBooks?

A: Pages are relatively more static. They don't change much. Posts on the other hand do change on a regular basis. Just like any store, it's best to use posts in this case.
You can also create a custom post type and call it "ebooks". It would be more appropriate, but posts can do fine.

A: The best way to create posts or custom posts instead of pages because you may be use pages type for creating various pages like about us, contact us, privacy etc.


text:
Q: Why does Eclipse show me a "Source not found" error? Here's what it looks like:

And here's my code:
import java.util.*;
import java.io.*;

public class ProcessSchedulingDemo {
    public static void main(String[] args) throws IOException {
        File file = new File("process-schedule.txt");
        Scanner inputFile = new Scanner(file);

        ArrayList<Process> processes = new ArrayList<Process>();

        // Skip past the first line, which is the column headers
        inputFile.nextLine();

        while (inputFile.hasNext()) {
            int processID = Integer.parseInt(inputFile.next());
            int timeUnitsRequired = Integer.parseInt(inputFile.next());
            int priority = Integer.parseInt(inputFile.next());
            int timeOfArrival = Integer.parseInt(inputFile.next());

            // Create and add to process a new process based on the information given
            Process process = new Process(processID, timeUnitsRequired, priority, timeOfArrival);
            processes.add(process);
        }

        Scanner keyboard = new Scanner(System.in);

        System.out.print("How much time does the CPU hold onto each process? ");
        int holdTime = keyboard.nextInt();

        if (holdTime <= 0) {
            while (holdTime <= 0) {
                System.out.print("Value must be greater than 0. Please input new value: ");
                holdTime = keyboard.nextInt();
            }
        }

        Heap<Process> processHeap = new Heap<Process>();

        // Holds a particular process being processed
        Process[] CPU = new Process[1];
        CPU[0] = null;

        int turn = 1;

        int timeSlices = 0;

        do {
            // Check if the list of processes has processes that should be added at the current turn
            for (int i = processes.size() - 1; i >= 0; i--) {
                if (processes.get(i).getTimeOfArrival() == turn) {
                    processHeap.add(processes.remove(i));
                }
            }

            // Print current standing of the processHeap at the beginning of the turn
            processHeap.enumerate();

            // If there currently isn't an item being processed by the CPU
            if (CPU[0] == null) {
                CPU[0] = processHeap.deleteMax();
                timeSlices = holdTime;
                System.out.println("got to cpu setting");
            }

            if (CPU[0].getTimeUnitsRequired() == 0 || timeSlices == 0) {
                if (CPU[0].getTimeUnitsRequired() > 0) {
                    processHeap.add(CPU[0]);
                }

                CPU[0] = null;
            }
            else {
                CPU[0].setTimeUnitsRequired(CPU[0].getTimeUnitsRequired() - 1);
                timeSlices--;

                if (CPU[0].getTimeUnitsRequired() == 0 || timeSlices == 0) {
                    if (CPU[0].getTimeUnitsRequired() > 0) {
                        processHeap.add(CPU[0]);
                    }

                    CPU[0] = null;
                }
            }

            if (CPU[0] != null) {
                System.out.println("-- STATE OF CPU --");
                System.out.println("[" + CPU[0].getProcessID() + ", " + CPU[0].getTimeUnitsRequired() + ", " + CPU[0].getPriority() + "]\n");
            }

            turn++;
        } while (processes.size() != 0 && processHeap.size() != 0);
    }
}

What on earth is causing it? EVERY time I save it pops up. Argh. (Using Eclipse)

A: Scanner is part of the Java run time libraries, provided by Oracle (if you're using the Oracle JDK).  I think it should be included with the JDK as a file called src.zip.  You can click the Edit Lookup Path button and add this file.  It should be in your Java JDK install directory.

A: Eclipse debugging works with the class actually loaded by the program.
Something you installed wrong to some file is missing in your project that why you get this errorThis can happen for several reasons but have a look at the location where the classes showing this behaviour is found (look in the navigation pane to identify it). You will most likely need to change the build path of the project to avoid using this jar and have the JVM use the project instead
you can use this link to solved your problem - http://www.vogella.com/articles/Eclipse/article.html#classpath
Please update your java and Eclipse.


text:
Q: Azure ML Studio: How to import images dataset? In Azure ML studio, how to import images dataset, for image recognition algorithms. As zip file?

A: I just asked the support team in chat, they were super fast in replying

*

*You could try converting your image into a format that the Studio
  data upload tool understands (i.e. csv).

*You can probably put the image file in a .zip file, upload that to
  your workspace, and then manipulate this data file in an 'Execute R
  Script". An example of first Option.

A: You can use "import images" module in Azure ML Studio that can read images from Azure blob storage - here is the sample experiment


text:
Q: Cannot use GridLayout even though support lib was imported with ActionBarSherlock I have an Android project in which I am using ActionBarSherlock, which I have imported in the workspace as a separate project that also contains the Android Support Library.
I would like now to use GridLayout and I was assuming that, given the presence of the support
library, it would be recognized and available, but it is not. Eclipse tells me that I need to set the minimum API for my project to 14, while I'm forced to leave it at 8. Is there a way I can fix this?
I hope this was clear enough. Thanks for help.

A: GridLayout was back ported to API 7+ only and is available as a library project in your SDK folder. You can find it at SDK/extras/android/support/v7.
It is not a part of ABS nor the v4 support library jar.

A: It is hard to identify your problem without seeing project settings.
I am able to create new project from the scratch which uses both ActionBarSherlock and GridLayout libraries.

*

*Make sure you have latest SDK, ActionBarSherlock, GridLayout
and v4-support libraries as well as an updated ADT Eclipse
plugin.

*Create new project and leave everything by-default, except for:
Build SDK = Android 4.1 (API 16)
Minimum Required SDK = API 8

*Goto project Properties --> Android and add actionbarsherlock and
gridlayout libraries.

*Goto res folder and remove values-v11 and values-v13
sub-folders.

*Edit res\values\styles.xml:
<resources>
    <style name="AppTheme" parent="Theme.Sherlock.Light" />
</resources>

*Edit res\layout\activity_main.xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <android.support.v7.widget.GridLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        app:columnCount="2"
        tools:context=".MainActivity" >

        <TextView
            android:padding="@dimen/padding_medium"
            android:text="@string/cell1"
            tools:context=".MainActivity" />

        <TextView
            android:padding="@dimen/padding_medium"
            android:text="@string/cell2"
            tools:context=".MainActivity" />

        <TextView
            android:padding="@dimen/padding_medium"
            android:text="@string/cell3"
            tools:context=".MainActivity" />

        <TextView
            android:padding="@dimen/padding_medium"
            android:text="@string/cell4"
            tools:context=".MainActivity" />
    </android.support.v7.widget.GridLayout>

</RelativeLayout>

*Create missing string resources (cell1,…)

*Edit MainActivity.java:
package com.test.gridlayout;

import android.os.Bundle;

import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.actionbarsherlock.view.Menu;

public class MainActivity extends SherlockFragmentActivity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        ActionBar ab = getSupportActionBar();
        ab.setDisplayShowTitleEnabled(true);
        ab.setDisplayUseLogoEnabled(false);
        ab.setDisplayHomeAsUpEnabled(false);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getSupportMenuInflater().inflate(R.menu.activity_main, menu);

        return true;
    }
}

*That it.
If you still have troubles, use this demo project as starting point.


text:
Q: How do I simplify $\overline{(\bar{X} + Z\bar{Y} + Y\bar{Z})(\bar{X}+Y\bar{Z})}$? $\overline{(\bar{X} + Z\bar{Y} + Y\bar{Z})(\bar{X}+Y\bar{Z})}$
The farthest I've gotten is DeMorgans:
$X(\bar{Z} + Y)(\bar{Y} + Z) + X(\bar{Y} + Z)$
The answer should be $X\bar{Y} + XZ$, but I'm unable to get anywhere close to it. I tried foiling the binomial but it results in a single X value when the whole expression is evaluated, and that's not correct.

A: Continuing from where you stopped using $1$ for $True$
\begin{eqnarray*} X(\bar{Z} + Y)(\bar{Y} + Z) + X(\bar{Y} + Z)
& = & X(\bar{Y} + Z)((\bar{Z} + Y) + 1) \\
& \stackrel{x+1=1}{=} & X(\bar{Y} + Z)\\
& = & X\bar{Y} + XZ
\end{eqnarray*}


text:
Q: JPA Entitties, how to join tables I have three tables
CREATE TABLE "ingredient" (
  "id" INTEGER GENERATED BY DEFAULT AS IDENTITY(START WITH 1, INCREMENT BY 1) PRIMARY KEY,
  "ingredient" VARCHAR(50) NOT NULL
);

CREATE TABLE "pizza" (
  "id" INTEGER GENERATED BY DEFAULT AS IDENTITY(START WITH 1, INCREMENT BY 1) PRIMARY KEY,
  "pizza" VARCHAR(50) NOT NULL
);

CREATE TABLE "pizza_structure" (
  "pizza_id" INT NOT NULL,
  "ingredient_id" INT NOT NULL,
  "amount" INT NOT NULL
);

how to join them, to get Pizzas structure as a Map
@Entity
@Table(name = "ingredient")
public class Ingredient{

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    private String name;

    public Ingredient() {
    }
}

@Entity
@Table(name = "pizza")
public class Pizza {

    @Id
    @GeneratedValue
    private Long id;
    private String name;
    @OneToMany ????
    private Map<Ingredient, Integer> pizzaStructure;

    public Pizza() {
    }

    public Pizza(String name, Map<Long, Integer> pizzaStructure) {
        this.name = name;
        this.pizzaStructure = pizzaStructure;
    }
}

do I need to create @Embeddable class PizzaStructure, if yes when how to use it?
now I'm getting an error
Invocation of init method failed; nested exception is org.hibernate.AnnotationException: Use of @OneToMany or @ManyToMany targeting an unmapped class:

A: You have a manyToMany relationship between pizza and ingredient and an additional column in your relationship.
I found a similar question here: JPA 2.0 many-to-many with extra column
(I would comment, but i do not have enough reputation.)

A:
how to join them, to get Pizzas structure as a Map

It seems to look like this:
@ElementCollection
@CollectionTable(name = "pizza_structure", joinColumns = {@JoinColumn(name = "pizza_id")})
@Column(name = "amount")
@MapKeyJoinColumn(name = "ingredient_id")
private Map<Ingredient, Integer> pizzaStructure;

do I need to create @Embeddable class PizzaStructure

No.
More info is here: Hibernate User Guide - Maps.
Note that table pizza_structure should have foreign keys to pizza and ingredient tables and also unique constrain of pizza_id and ingredient_id, like this (it's postgresql dialect):
create table pizza_structure
(
  pizza_id ... constraint fk_structure_pizza references pizza,
  ingredient_id ... constraint fk_structure_ingredient references ingredient,
  amount ...,
  constraint pizza_structure_pkey primary key (pizza_id, ingredient_id)
);