text:
Q: Retrieve data from JSON web service with Ajax I have a web service which works fine, when I open it manually and type the parameters in manually. For example:
When I navigate to url.url/webservice.php?region=NY it gives me all the data I need from my database. Now I want to type in a city in an input field and let ajax do the rest.
<form>
<input type="text" value="NY" name="myText" id="input">
<input type="submit" value="Submit" name="mySubmit" id="submit" onClick="changeView()">
</form>

So now, when I type something in the input field Ajax should send an request to my webservice and get the data.
My web service looks like this:
<?php
header("Content-type: application/json");
$mysqli = new mysqli('localhost','root','','ttzaferis');
$array = array();
$region = $_GET['region'];
if($result = $mysqli->query("SELECT lon, lat FROM pointsofinterest WHERE region = '".$region."'")){
    $tempArray = array();
    while($row = $result->fetch_assoc()){
        $tempArray = $row;
        array_push($array, $tempArray);
    }
    echo json_encode($array);
}
?>

I have now only problems on the Ajax-part. I can't understand how to make it work. I tried the following
function changeView(){
    var region = document.getElementById('input').value;
    alert(region);
    $j.ajax({
    type: 'GET',
        url: 'webservice.php',
        data: region,
        success: function(response, textStatus, XMLHttpRequest) {
        alert("test");
    }
});
}

I don't understand what the problem is and how to solve it.

A: I usually send get data like this :
  $j.ajax({
    url: 'webservice.php?region='+region,

    success: function(response, textStatus, XMLHttpRequest) {
    alert("test");
}
});

Which according to your comments should solve this. I don't know if it's possible sending via data, but if it is then you should do something like this :
  $j.ajax({
    url: 'webservice.php',
    dataType: "json",
    data: {region : region},
    success: function(response, textStatus, XMLHttpRequest) {
    alert(response.somekey);
}
});

Or seirlizing it, But yet again, i'm not sure if it'll work. Note that i added dataType, though jQuery usually tries to find out what the dataType will be, won't hurt to add it


text:
Q: Usage of addImageFromBase64 I came across this addImageFromBase64 function from https://facebook.github.io/react-native/docs/imagestore#addimagefrombase64
As quoted:

Note that it is very inefficient to transfer large quantities of binary data between JS and native code, so you should avoid calling this more than necessary. @platform ios

It sounds like a terrible idea to use this function. Wondering if there is any good use case to implement this function?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Android spinner default value problem In my Application i am using Spinner which contain 1 to 60 items from which user have to select anyone of them.My problem is that when user again call the Activity which contain spinner, user can able to see his previously selected item as the default value of spinner.
I have try to use the spineer.setselection() but i am not able to get.
so if anyone have any ideal about this then please give some hint to solve my problem.
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    ViewGroup viewgroup = (ViewGroup) findViewById(R.id.myprofilelinear);
    ViewGroup.inflate(this, R.layout.spinner,
            viewgroup);

    LoadUI();
}
public void LoadUI()
{
    imgtoggle = (ImageView) findViewById(R.id.btntoggle);
    imgtoggle.setOnClickListener(this);
    String param=JsonDataProcessor.MYPROFILELIST.get(0).getIsTracking();
    if(param.equalsIgnoreCase("True"))
    {
        imgtoggle.setImageResource(R.drawable.on_button);
    }
    else
    {
        imgtoggle.setImageResource(R.drawable.off_button);
    }

    btnsave = (Button)findViewById(R.id.btnSavechanges);
    btnsave.setOnClickListener(this);

    String[] s = new String[60];
    int i;
    for (i = 0; i < 60; i++) {
        s[i] = Integer.toString(i+1);
    }

     spin = (Spinner) findViewById(R.id.TimeSpinner);
    ArrayAdapter<String> adapter = new ArrayAdapter<String>(TimeSpin.this,
            android.R.layout.simple_spinner_item, s);
    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    spin.setAdapter(adapter);

}

A: Use
spin.setSelection(adapter.getPosition(previously_saved_value));
previously_saved_value can be get by using Shared Preference or by making a static variable and its value is set to what user has previously selected.

A: You should Ignite OnItemselectedListener for this and set the selected value in Spinner
Check this Code :
    boolean flag_default_country=false;

    spin_country.setOnItemSelectedListener(new OnItemSelectedListener() {

        @Override
        public void onItemSelected(AdapterView<?> arg0, View arg1,
                int arg2, long arg3) {
            // TODO Auto-generated method stub
                for (int i = 0; i < s.length; i++) {
                    if (flag_default_country == false) {
                        if (s[i].toString().equalsIgnoreCase("US")) {
                            spin_country.setSelection(i);
                            flag_default_country = true;
                        }
                    }
                }
            }

        @Override
        public void onNothingSelected(AdapterView<?> arg0) {
            // TODO Auto-generated method stub
        }
    });

spin_country is Spinner Object
first initialize the flag_default_country to false , then check for the String value selected by User that was stored in Some values. if the Array value at i'th position equals to the user selected value it will set the value at i in the Spinner.
For Saving the user selected value you can use the Shared preference.
Check this link for Shared Preference.
Let me know if you find any difficulty.


text:
Q: How create my own assertions for casperJS Is there a way to create custom assertions for casperJS? The only thing that I got worked is something like this:
casper.test.assertIsChecked = function(selector, msg) {
  var isChecked = !this.casper.getElementsAttribute(selector, 'checked')
  this.assertTruthy(isChecked, msg);
}

But its a bit hacky to just add it to test object and it lacks from proper error message.


text:
Q: Can't resize /boot partition (fat32 / EFI system partition) I'm searching for a way to expand my /boot partition. In general I have some free unallocated space.
Using gparted the new size of /boot can't be bigger then the actual size according to the GUI.

Is there any chance to resize this partition from 100mb to 200mb?
I'm having a multi boot system (win 7 / gentoo); so using a tool with windows would be also possible.

A: As mention in the comment you'll need to shrink sda3 from the LEFT (which is not the default why) then move sda2 the same way (expand to the right > then shrink from the left), then you'll have the free space needed to expand sda1.
P.S, you will need to do all this via external system which not using the disks, like a LIVECD - try systemrescuecd for that matter.

A: Since it's a Linux-compatible partition with relatively little data and you have a few larger empty spots in your partition layout, I'd suggest you just

*

*backup the contents of the partition,

*delete it¹,

*recreate it in one of the larger empty spots (e.g. the 900 MB one),

*change the mount information in /etc/fstab (since you just replaced the partition UUID with a new one),

*mount it, and

*copy the data backup onto it.

Since this is the /boot partition containing your kernel, you'll need to make its new position known to the bootloader (usually GRUB) afterwards.
The exact commands depend on the distribution you're using, but you'll usually boot a live CD/USB of your distro, mount your partitions in a chroot environment, and run grub-install /dev/<your main disk>.
With prior experience or a good tutorial, that's done in five to ten minutes. ;)
That should be much faster than moving around multiple large filesystems (which involves more than just moving the first few MB to the end of the partition, since the filesystem on the partition has to stay consistent).
Besides, I'm not sure if Windows likes having "Microsoft reserved" partitions moved around: partitions like that are often used for "revert to factory defaults" features and have their partition number and/or position hardcoded somewhere.
¹ Deleting it before recreating it only serves to keep the partition number the same. If you don't care if the partition gets changed from sda1 to sda4, you can create the new partition and copy over the data straight away. That way, you might even get away without requiring a live CD/USB after all, just running everything (including grub-install from your existing Linux system.


text:
Q: Load average is high after adding second drive My laptop was working fine and its load average was between 0.2 - 0.5 (and around 0.02 while doing nothing) until I decide to upgrade it with an SSD.
First I replaced my HDD with SSD, moving HDD into a HDD Caddy, removing the optical drive and putting HDD there instead.

*

*Both my SSD and HDD are capable of working with SATA III interfaces.

*However my HDD is working at SATA 2 mode:
sudo smartctl -a /dev/sdb | grep SATA
SATA Version is:  SATA 3.0, 6.0 Gb/s (current: 3.0 Gb/s)

*Seems my optical drive interface is SATA 2.
Problem
The problem is whenever there is something in HDD Caddy (SSD, HDD, Doesn't matter) load average while doing nothing is around 1.5 - 2 and while system is just booted up is around 4.
What did I done?

*

*I have tried any combination of setup nothing takes any effects.

What else?

*

*CPU usage is normal and no process is consuming the CPU.

*If I only use one disk as the main hard drive load average is normal.

*If I even use one disk at the optical drive place, I get high load average.

A: There is an excellent Q&A with the same problem:

*

*kworker consumes high cpu for external hard drive

The solution from top-voted answer was this command:
echo "disable" > /sys/firmware/acpi/interrupts/gpe6F

In the link grep was used to discover the interrupt causing grief:
grep . -r /sys/firmware/acpi/interrupts/

Load Average
If you look at your system load average for 1-5-15 minutes like this:
$ cat /proc/loadavg
0.50 0.76 0.91 2/1037 14366

It's reporting .5, .76 and .91. From Understanding Linux CPU Load - when should you be worried? it says:

*

*The "Need to Look into it" Rule of Thumb: 0.70 If your load average is staying above > 0.70, it's time to investigate before
  things get worse.

Further in the article it will mention something like the load average for all your CPUs are added together but not divided by the number of CPUs to get an average of all CPUs. You have to do this manually so the true values are:
.063 - .095 - .113
because I have 8 CPUs.
I prefer to use Conky to display this in real-time though:

Notice the 4th line from the bottom display 1-5-15 minute load averages as:
.150 .177 .143

The 1 minute load average of .15 equates to 15% which matches the All CPU percentage value two lines above the Load Average.
Without diving by 8 I'd have a heart attack because I would be seeing:
1.200 1.416 1.144

Conky automatically divides for me with the Conky code:
${execpi .001 (awk '{printf "%s/", $1}' /proc/loadavg; grep -c processor /proc/cpuinfo;) | bc -l | cut -c1-4} ${execpi .001 (awk '{printf "%s/", $2}' /proc/loadavg; grep -c processor /proc/cpuinfo;) | bc -l | cut -c1-4} ${execpi .001 (awk '{printf "%s/", $3}' /proc/loadavg; grep -c processor /proc/cpuinfo;) | bc -l | cut -c1-4}

Of course not everyone uses conky probably only 1% of Linux users but for those out there that love Conky like me, you might find this code helpful.

A: This could be related to the HDD caddy you use.
Please see if it has a button or a switch, in order to change the state of the caddy.


text:
Q: Function does not remove string from body of text Hi there this is a continuation of my question  Find string and move it up to the top of the document
The code does almost what I need to to. It does search for <!Entity> elements and moves them to the top of the document, but it doesn't remove them from the body of the document. I also need to broaden the search to just <!.*$
Here is the code. On line 15 "lines.RemoveAt(item.Key)" it doesn't seem to be working
Dim largeFilePath As String = "largeFilePath"
Dim lines = File.ReadLines(largeFilePath).ToList 'don't use ReadAllLines
Dim reg = New Regex("<!Entity.*$", RegexOptions.IgnoreCase)
Dim entities = From line In lines
               Where reg.IsMatch(line)

Dim dictionary As New Dictionary(Of Integer, String)
Dim idx = 0
For Each s In entities
    idx = lines.IndexOf(s, idx)
    dictionary.Add(idx, s)
Next

For Each itm In dictionary
    lines.RemoveAt(itm.Key)
Next

For Each s In entities.ToList
    lines.Insert(1, s)
Next

Using sw As New System.IO.StreamWriter("newfile.txt")
    For Each line As String In lines
        sw.WriteLine(line)
    Next
    sw.Flush()
    sw.Close()
End Using

Test Data
<!DOCTYPE DOC PUBLIC "-//USA-DOD//DTD 38784STD-BV7//EN"[
<!ENTITY cdcs_5-35.wmf SYSTEM "graphics\CDCS_5-35.wmf" NDATA wmf>
<!ENTITY cdcs_2-2a.wmf SYSTEM "graphics\CDCS_2-2A.wmf" NDATA wmf>
<!ENTITY GCS38849 SYSTEM "Graphics\GCS38849.cgm" NDATA cgm>
<!ENTITY GCS39016 SYSTEM "Graphics\GCS39016.cgm" NDATA cgm>
<doc service="xs" docid="BKw46" docstat="formal" verstatpg="ver" cycle="1" chglevel="1">
<front numcols="1">
<idinfo>
<?Pub Lcl _divid="100" _parentid="0">
<tmidno>Life with Pets</tmidno>
<chgnum>Change 1</chgnum>
<chgdate>2 August 2018</chgdate>
<chghistory>
<chginfo>
<!ENTITY CDCS_4-21B SYSTEM "Graphics\CDCS_4-21B.wmf" NDATA wmf>
<!ENTITY CDCS_4-24B SYSTEM "Graphics\CDCS_4-24B.wmf" NDATA wmf>
<!ENTITY CDCS_4-42B SYSTEM "Graphics\CDCS_4-42B.png" NDATA png>
<!ENTITY CDCS_MFW11 SYSTEM "Graphics\CDCS_MFW1.wmf" NDATA wmf>
<!ENTITY CDCS_blk10_Cont_consl_markingsworking1 SYSTEM "Graphics\CDCS_b
<chgtxt>Change 1</chgtxt>
<date>2 August 2018</date>
</front>
<!ENTITY cdcs_2-19.wmf SYSTEM "graphics\CDCS_2-19.wmf" NDATA wmf>
<!ENTITY cdcs_3-5.wmf SYSTEM "graphics\CDCS_3-5.wmf" NDATA wmf>
<body numcols="1">
<chapter>
<title>This is chapter 1</title>
<!ENTITY cdcs_2-5.wmf SYSTEM "graphics\CDCS_2-5.wmf" NDATA wmf>
<!ENTITY cdcs_2-24.wmf SYSTEM "graphics\CDCS_2-24.wmf" NDATA wmf>
<para0>
<title>Climb the ladder immedietly</title>
<para>Retrieve the cat.</para></para0></chapter>
<chapter>
<title>Don't forget to feed the dog</title>
<para0>
<!ENTITY GCS17777 SYSTEM "Graphics\GCS17777.cgm" NDATA cgm>
<!ENTITY GCS17782 SYSTEM "Graphics\GCS17782.cgm" NDATA cgm>
<!ENTITY GCS17783 SYSTEM "Graphics\GCS17783.cgm" NDATA cgm>
<!ENTITY GCS19983 SYSTEM "Graphics\GCS19983.cgm" NDATA cgm>
<!ENTITY GCS19984 SYSTEM "Graphics\GCS19984.cgm" NDATA cgm>
<!ENTITY cdcs_4-48.wmf SYSTEM "graphics\CDCS_4-48.wmf" NDATA wmf>
<title>Prep for puppies</title>
<para>Puppies are cute</para></para0>
</chapter>
</body>
</doc>

The results is a file with all the <!Entity elements moved to the top of the document, but also remain in the body of the document.
The desired results is all <!.* elements to be moved to the top of the document and removed from the body of the document.
Thank you for all your help and patience with this question.
Max

A: This was solved.
Dim largeFilePath As String = "largeFilePath"
Dim lines = File.ReadLines(largeFilePath).ToList 'don't use ReadAllLines
Dim reg = New Regex("\<\!NOTATION.*$|\<\!ENTITY.*$", RegexOptions.IgnoreCase)
Dim entities = From line In lines
               Where reg.IsMatch(line)

Dim dictionary As New Dictionary(Of Integer, String)
Dim idx = -1
For Each s In entities
    idx = lines.IndexOf(s, idx + 1)
    dictionary.Add(idx, s)
Next

Dim deletedItems = 0
For Each itm In dictionary
    lines.RemoveAt(itm.Key - deletedItems)
    deletedItems += 1
Next

For Each s In dictionary.Values
    lines.Insert(1, s)
Next

Using sw As New System.IO.StreamWriter("newfile.txt")
    For Each line As String In lines
        sw.WriteLine(line)
    Next
    sw.Flush()
    sw.Close()
End Using


text:
Q: JQuery/PHP - Overlay another page on keypress I'm trying to make a page "overlay" when the user presses the keyboard key T or P. With the code below, I am able to make the page turn blank, however, I would like to be able to display another html page or other text while the other disappears. When the user presses T or P again, it returns to there previous window.
Here is my current code:
$(document).keypress(function(e) {
    var key = e.which;
    if (key == 116) {
        // if the user pressed 't':
        if(!$("body").hasClass('active'))
            $("body").addClass('active');
        else
            $("body").removeClass('active');
    }
});

 <style>
    .active{opacity:0;}
 </style>

NOTE: I'm using style tags for testing purposes.
Please, if you have any suggestions on how to make one object hide, and another one appear please let me know. I would really appreciate it. A JSfiddle would be much appreciated if possible.
Thank you so much for reading!
Toby.

A: There are a few problems with your code that are notable.
1. You are hiding the body.
Everything should be within your document body, so if you hide the whole document, you can't see anything! Put your content into separate divs so that you can hide each one independently.
2. You are not fading
In order to fade, you either have to use CSS3 transitions or use a jQuery animation.
See this example JSFiddle for an idea. Press 'T' to alternate between the red and blue divs (you'll have to click on the div to put your focus on the document). I use a placeholder class .hidden (which has no styles attached; it is just  a placeholder) to keep track of which div is visible and hide/show accordingly.
$(document).ready(function(){

    $(document).keypress(function(e) {
        var key = e.which;
        if (key == 116) {
        // if the user pressed 't':
            if($(".red").hasClass("hidden"))
            {
                $(".red").removeClass("hidden").animate({
                    opacity: "1"
                }, 500).css("z-index", 1);
                $(".blue").addClass("hidden").animate({
                    opacity: "0"
                }, 500).css("z-index", 0);
            }
            else
            {
                $(".blue").removeClass("hidden").animate({
                    opacity: "1"
                }, 500).css("z-index", 1);
                $(".red").addClass("hidden").animate({
                    opacity: "0"
                }, 500).css("z-index", 0);
            }
        }
    });

});

JSFiddle


text:
Q: Polymer: How can I customize color and font size of paper header How I can change the color and font-size of the header of a paper-card element using --paper-card-header-color?
I am looking at this link but not very sure how I can put the above attribute, i.e. --paper-card-header-color and the color value.
I tried like:

<paper-card heading="Total Linear Sales" paper-card-header-color="#ff0000">
  <div class="card-content">
    ...
    ...
  </div>
</paper-card>

Bit the above does not change the color.
I am not very familiar with Polymer yet, still learning basics.
Thanks in advance.

A: What you're looking at are Polymer's Custom CSS Properties. You apply them like regular CSS properties:
paper-card {
    --paper-card-header-color: #ff0000;
}

Or inline:
<paper-card style="--paper-card-header-color: #ff0000">


text:
Q: When to call notify in RecyclerView.Adapter? Will notify* methods in RecyclerView.Adapter run view's callbacks in UI thread automagically or have I to explicitly switch from my job's thread?

A: If you want to update your  RecyclerView.Adapter you should call method notify in UI thread.

A: Whenever you interact with a View in android you must do it on the UI thread. This includes recyclerviews and their adapters.


text:
Q: Images not uploading using ng-file-upload and multer I am trying to use ng-file-upload and multer for file uploading. My code looks currently like this.
HTML file
<form class="form-inline" ng-submit="startUpload()">

    <fieldset>

        <input id="city" class="form-control" type="text" name="city"
               ng-model="city" placeholder="City" />

        <input id="description" class="form-control" type="text" name="description"
               ng-model="description" placeholder="Description" />

        <input id="images" class="form-control" type="file" name="images"
               placeholder="Images"  accept="image/*"
               ngf-select="uploadFiles($files, $invalidFiles)" />

        <input class="btn btn-custom btn-submit" type="submit" value="Upload">
    </fieldset>

Angular controller
angular.module('upload').controller('uploadController', function($scope, Upload) {
var uploadUrl = 'http://localhost:1337/api/v1/upload';
var images;

$scope.uploadFiles = function(files, errFiles) {
    images = files;
};

$scope.startUpload = function() {
    var data = {
        location: $scope.city,
        title: 'test title',
        description: $scope.description,
    };

    Upload.upload({
        url: uploadUrl,
        headers : {
            'Content-Type': 'multipart/form-data'
        },
        arrayKey: '',
        data: data,
        files: images
    });
};
});

Backend API
var multer = require('multer');
var upload = multer({ dest : 'source/public/assets/img/test/' });

app.post(versionUrl + '/create-entry', upload.array('images'), function(req, res, next) {
    console.log(req.body) // this contains all text data
    console.log(req.files) // this is always an empty array
});

Since this is the first time I'm doing such a thing, I am totally frustrated it does not work. There are plenty of examples in the internet, providing the exactly same code - still this one does not work for me.
I would be happy about all suggestions, helping me to solve this problem.

A: You need to instead set images: images in your data object:
var data = {
  location: $scope.city,
  title: 'test title',
  description: $scope.description,
  images: images
};

Upload.upload({
  url: uploadUrl,
  arrayKey: '',
  data: data,
});


text:
Q: Find multiple tags with condition Is it possible to find multiple tags with a condition?

Could I say
Find all "a" and "img" tags containing "/img/"

A: Yes, just supply function (can be lambda function) to find_all() method:
data = """
"""

from bs4 import BeautifulSoup

soup = BeautifulSoup(data, 'lxml')

for tag in soup.body.find_all(lambda t: t.name in ('a', 'img') and \
                         ('href' in t.attrs and '/img/' in t['href']) or
                         ('src' in t.attrs and '/img/' in t['src'])):
    print(tag.name, tag.attrs)
    print('*' * 80)

Outputs:
a {'href': '/img/something.jpg'}
********************************************************************************
img {'src': '/img/somethingelse.png'}
********************************************************************************


text:
Q: How to analyze data which might come from a few normal distribution concatenate together in order? For example, I have a series of values for example like the following:
data <- c(rnorm(10000,40,1500),rnorm(9000,-35,1400),rnorm(11000,30,1300))

I don't know the mean, don't know the sd of my data, and am particularly interested in the "sign of the mean" of my data (I can do a t-test but most often it is not significant, and even if it is, it only tells half of the story), and would be better to know if it changes over time. (how ever, I believe the data is not a time series, i.e. consecutive data points are independent of each other). But, I also doubt that my data might have different baseline distributions (assumed normal) at different time stages.
So, what is a standard way of analysing such data? You can see the sd of my data is quite big. Do I have to pretend it is a time series and decompose it to see the trend?
df <- data.frame(x=1:30000, data=data)
ggplot(df, aes(x=x)) + geom_bar(aes(y=cumsum(data)), width=1, stat="identity")

This is the graph of cumulative values of the data. Can we tell if it is from one normal distribution, or several normal distributions with different means and variances? If it is possible, what assumptions do I have to make?

Compared to this:
data <- rnorm(30000, 3, 1800)
df <- data.frame(x=1:30000, data=data)
ggplot(df, aes(x=x)) + geom_bar(aes(y=cumsum(data)), width=1, stat="identity")

Update:
I guess that changepoint package in R is good enough
> a <- cpt.meanvar(data=c(rnorm(10000,40,1500),rnorm(9000,-35,1400),rnorm(11000,30,1300)), method="BinSeg")
> summary(a)
Changepoint type      : Change in mean and variance
Method of analysis    : BinSeg
Test Statistic  : Normal
Type of penalty       : SIC with value, 20.61791
Maximum no. of cpts   : 5
Changepoint Locations : 10264 19013

> b <- cpt.meanvar(data=rnorm(30000, 3, 1800), method="BinSeg")
> summary(b)
Changepoint type      : Change in mean and variance
Method of analysis    : BinSeg
Test Statistic  : Normal
Type of penalty       : SIC with value, 20.61791
Maximum no. of cpts   : 5
Changepoint Locations :

PELT would give some small intervals thought I had penalty to include the number of change points.
> a <- cpt.meanvar(penalty="SIC1",data=c(rnorm(10000,40,1500),rnorm(9000,-35,1400),rnorm(11000,30,1300)), method="PELT")
> summary(a)
Changepoint type      : Change in mean and variance
Method of analysis    : PELT
Test Statistic  : Normal
Type of penalty       : SIC1 with value, 30.92686
Maximum no. of cpts   : Inf
Changepoint Locations : 10049 18984 18987
>
> a <- cpt.meanvar(penalty="SIC1",data=c(rnorm(10000,40,1500),rnorm(9000,-35,1400),rnorm(11000,30,1300)), method="PELT")
> summary(a)
Changepoint type      : Change in mean and variance
Method of analysis    : PELT
Test Statistic  : Normal
Type of penalty       : SIC1 with value, 30.92686
Maximum no. of cpts   : Inf
Changepoint Locations : 8810 8814 18962

A: Please be careful when using the Binary Segmentation flag in the changepoint package.  If you are not familiar with changepoints then you may not be aware that this gives an approximate solution to the changepoint search - meaning that a more accurate segmentation may exist.  I would advise using method='PELT' as this provides an exact search approach and thus the most accurate segmentation.
You should also be aware that for changes in mean it is hard to detect a change if (mu_1-mu_2)/sigma < 0.7.  By hard I mean that the likelihood ratio test has power less than 0.8.


text:
Q: drawImage resize image to 500px high I am trying to take the image that is 1280x960 and resize it using drawImage so that is is 600 pixels high.  I have worked out the ratio that I think I need to achieve this but don't know how to apply...

var canvas = document.getElementById('mycanvas');
var ctx = canvas.getContext('2d');
var img = new Image();
img.onload = function () {
  canvas.height = this.height;
  canvas.width = this.width;

  ratio = canvas.height / canvas.width;

  console.log(canvas.width + 'x' + canvas.height + ' | ratio = ' + ratio);

  ctx.drawImage(img, 0, 0, 300, 500);
}
img.src = 'https://c.slashgear.com/wp-content/uploads/2015/06/dxo-one-sample-3-1280x960.jpg';
<canvas id="mycanvas"></canvas>

How can I specify the resulting image size, making the width automatic? I eventually want this function to resize any image to 500 pixels high.

A: I applied the ratio to your call to drawImage and it seems to work:
ctx.drawImage(img, 0, 0, 500 / ratio, 500);

var canvas = document.getElementById('mycanvas');
var ctx = canvas.getContext('2d');
var img = new Image();
img.onload = function () {
  canvas.height = this.height;
  canvas.width = this.width;

  ratio = canvas.height / canvas.width;

  console.log(canvas.width + 'x' + canvas.height + ' | ratio = ' + ratio);

  ctx.drawImage(img, 0, 0);
  canvas.style.width = 500 / ratio + "px";
  canvas.style.height = 500 + "px";
}
img.src = 'https://c.slashgear.com/wp-content/uploads/2015/06/dxo-one-sample-3-1280x960.jpg';
<canvas id="mycanvas"></canvas>

A: Here is a solution, a bit roundabout but seems to work. I created a new image using toDataURL() from the original sized canvas. Although the new image is reduced, the total dimension is still that of the original image, such that the remaining space is transparent. Then I set and clip this image into a new canvas. The resulting canvas has the correctly sized image which can be copied and pasted with the desired dimension.
If the snippet below does not display the image in the new canvas, please try the following fiddle which seems to work well: https://jsfiddle.net/jfeferman/u80fhy0z/

var canvas = document.getElementById('mycanvas');
var ctx = canvas.getContext('2d');
var img = new Image();
img.crossOrigin = "Anonymous";
img.onload = function () {
  canvas.height = this.height;
  canvas.width = this.width;

  ratio = canvas.height / canvas.width;

  console.log(canvas.width + 'x' + canvas.height + ' | ratio = ' + ratio);

  ctx.drawImage(img, 0, 0, 500 / ratio, 500);

  var newImage = new Image();
  newImage.crossOrigin = "Anonymous";
  newImage.src = canvas.toDataURL();

  var newCanvas = document.getElementById("newcanvas");
  newCanvas.height = 500;
  newCanvas.width = 500 / ratio;
  var newCtx = newCanvas.getContext('2d');
  newCtx.drawImage(newImage, 0, 0, 500 / ratio, 500, 0, 0, 500 / ratio, 500);
}
img.src = 'https://c.slashgear.com/wp-content/uploads/2015/06/dxo-one-sample-3-1280x960.jpg';
#mycanvas {
  display: none;
}
<canvas id="newcanvas"></canvas>
<canvas id="mycanvas"></canvas>


text:
Q: ApiPlatform Change messages only for browsers I use Symfony 5.4 & ApiPlatform 2.6
ApiPlatform displays message when you tray to reach certain routes.
For example if you don't have json token or it is expired you have :
status : 403 & Message : Expired tokens
I managed to customize these messages with event subscribers.
My question is :
Is it possible to display a different message if the route is reached via a browser ?
Currently the systems respond with Json which is good, but I would like to "hide" routes for browsers only.
Thanks.


text:
Q: bcrypt.compareSync is always returning false I verified that in my db I am saving the username and hash of the password.  I am able to retrieve the name from the db, however when I check the password it always returns false.  Not sure what is wrong.
Here is my HTML

        <form name="login_form">

Login

UserName

            <input ng-model="user" type="text" ng-minlength="1" required>

Password

            <input ng-model="password" type="password" name="password" ng-minlength="4" required>
            <input type="submit" value="Login" ng-click="login()" >

Your field is too short

Username or login is incorrect

        </form>

        <form name = "register_form">

Register

UserName

            <input ng-model="reg.name" type="text" required>

Password

            <input ng-model="reg.password" type="password">
            <input type="submit" value="Register" ng-click="register()" required >

Your field is too short

That user name is taken, please choose another

Registration Succesfull

        </form>

Here is my controller on the server side
var mongoose = require('mongoose'),
Todo = mongoose.model('Todo');
Login = mongoose.model('Login');
var bcrypt = require('bcrypt');
var name = ""

module.exports = (function(){
  return {
    save_name:function(req, res){
        req.session.user = req.body.user
      Login.findOne({name: req.body.user},
      function(err, user) {
        if(user){
          console.log(user.password);
            console.log( bcrypt.compareSync(req.body.password, user.password));
           res.json({'error': false});
          }else {
            res.json({'error': true});
          }
      })
    }, //end of save name method
    register:function(req, res){
      bcrypt.hashSync(req.body.password, bcrypt.genSaltSync(8));
      login = new Login({
        name:req.body.user,
        password: bcrypt.genSaltSync(8)
      })
      login.save(function(err){
        if(err){
          res.json({'error': true});
        } else {
          res.json({'sucess': true})
        }
      })
    } // end of register user function
  }
})();

A: You're saving a generated salt as the password instead of the actual hash itself. Also, explicitly calling genSalt*() is unnecessary. Lastly, you really should use the async functions instead, to avoid unnecessarily blocking the event loop. So with all of this in mind, you may end up with something like:
module.exports = {
  save_name: function(req, res) {
    req.session.user = req.body.user;
    Login.findOne({ name: req.body.user },
                  function(err, user) {
      if (err)
        return res.json({ error: true });
      bcrypt.compare(req.body.password,
                     user.password,
                     function(err, valid) {
        res.json({ error: !!(err || !valid) });
      });
    });
  }, // end of save name method
  register: function(req, res) {
    bcrypt.hash(req.body.password, 8, function(err, hash) {
      if (err)
        return res.json({ error: true });
      login = new Login({
        name: req.body.user,
        password: hash
      })
      login.save(function(err) {
        res.json({ error: !!err });
      })
    });
  } // end of register user function
};

A: Despite other answers, if it is still not resolving your issue. Try by applying the toString() when passing the password upon login like this.
req.body.password.toString();

A: The immediate cause of your bug is in register you should be using bcrypt.hashSync(myPlaintextPassword, saltRounds) instead of genSaltSync. Fixing that should make things "work".
However, you need to recode all this to use the async bcrypt APIs or your application will respond very poorly under load (like crippled and unusable, not just "slow"). General rule: no sync calls in a node.js server.


text:
Q: C - Comparing a string in a 2D Array against another string So, I have a 2D array for storing client ids in my program. I have to write a routine where I iterate through each string in this array and compare it against another string. I am using strcmp() for this. Following is the code.
char client_ids[100][100];

int find_client_by_id(char* name)
{
    for (int i = 0; i < n; i++)
    {
        if (strcmp(&client_ids[i], name) == 0)
        {
            return i;
        }
    }
    return -1;
}

It does what it is supposed to do, and returns the index of the passed string if found in the array and -1 otherwise. The issue I am facing is that on compiling I get the following warning,
server.c: In function 'find_client_by_id':
server.c:30:14: warning: passing argument 1 of 'strcmp' from incompatible pointer type [-Wincompatible-pointer-types]
if (strcmp(&client_ids[i], name) == 0)
          ^
In file included from server.c:5:0:
/usr/include/string.h:140:12: note: expected 'const char *' but argument is of type 'char (*)[100]'
extern int strcmp (const char *__s1, const char *__s2)

What am I doing wrong? Is there any way to avoid this warning?


text:
Q: Where to store value for duration of request Preamble
I'm developing a card game server in Rails. The application records what a player is expected to do via a tree of instances of the PendingAction model.
class Player < ActiveRecord::Base
  has_many :cards
  has_many :pending_actions
end

At any time, the player needs to act on any leaf PendingActions - there may be more than one, for instance:
1. End turn
|
+- 2. Do thing A
|  |
|  + 3. Do thing pre-A
|
+- 4. Do thing B
   |
   + 5. Do thing pre-B

The view code presents the player with one or more forms, requesting their choice for each leaf action. For instance, in the above case, forms would be presented to solicit input for actions 3 and 5.
When the player makes a choice for, say, action 5, that action is destroyed. However, processing their choice may cause them to need to make another choice before the parent (action 4) can happen. Like so:
1. End turn
|
+- 2. Do thing A
|  |
|  + 3. Do thing pre-A
|
+- 4. Do thing B
   |
   + 6. Do other thing pre-B

Action 4 therefore needs to be on-hand, so action 6 can be created as its child. At present, I am simply passing action 4 around as a function argument. However, I've just come across a situation where it would really help to be able to have access to it in a before_save hook on a Card object.
Question
Where is the best place to store an object, associated with a Player, that I can access from all models related to that Player, which is valid throughout - but not beyond - a single HTTP request?
I am running under Heroku, with 1 dyno - so I believe I'm single-threaded.

A: It depends on which environment you work, but lets assume that this is single-threaded environment. Next, first thought was to create instance attribute to manually assign and retrieve anything. It is will work fine when Player instance is the same for all places.
If not, I suggest to introduce class variable, some sort of cache, that will hold Player#id => <some_obj> reference, and with helper accessors, like Player#some_obj which will query Player for object by self.id.
That way you will be ensured that for all Player with the same Id, some_obj will be the same. Also, you will need to deside, when to empty that class-cache. For Rails, i suppose after_filter is good enough.


text: Q: Only one resolution available 640 x 480 ubuntu 16.04 I am completely new to Ubuntu and I want to change my resolution as everything is so big that even navigating this site is a pain. I am running a GTX 1080 and when I check display options there is only one drop down option and that is 640 x 480. Is this a driver issue? Because this is what Windows did before I installed the driver. As I said I am completely new to Ubuntu and have just reformatted everything. The only thing I installed was my Linksys wusb6300 driver. I looked around but I can't quite find what I need. Can someone point me in the right direction? Thank you!


text:
Q: Distributed Counters / Likes or Votes for Suggestions & Security Rules I've used the documented technique to implement a Distributed Counter for likes on a post. Right now I'm not using FieldValue.increment but I increment it myself. Regardless of this detail, I find it highly suspicious that a user could just intercept the commit-request and change the number to increment and so change the likes in the database.
As I'm also collecting the likes in a collection (with documents per user), I was hoping I could write a security rule that checks if the counter equals the amount of documents of the collection (with the get() function) but I cannot read collections with it.
How is this problem solved (without cloud funcitons)? How do I make sure the counter is synchronous with the actual amount of likes?

A: What I would recommend to solve this is to have a collection of likes per post and user uid and to write a simple rule that a user can only add his uid into that collection if it equals his uid. That is a very basic security rule. The user could also only add and remoe his own uid.
To cound just crate a coud function that counts how many of those uids are there for a specific post. You can here also use the "distributed" counter method.
The counting can't be secured without Cloud Functions. If the user can change the end result of the counting he could save there anything. You can only do it with cloud functions and the method above would be the most secure one.

A: After thinking about it a lot, I managed to come up with the following solution:
let suggestionRef = this.firestore.firestore.collection("suggestions").doc(suggestion.id);
let suggestionUpVotesOfUser = suggestionRef.collection('upvotes').doc(this.authService.userId);

let batch = this.firestore.firestore.batch();
let increment = 1;
if ((await suggestionUpVotesOfUser.get()).exists) {
    increment = -1;
    batch.delete(suggestionUpVotesOfUser);
} else {
    batch.set(suggestionUpVotesOfUser, {});
}
batch.update(suggestionRef, { upvotesCount: firebase.default.firestore.FieldValue.increment(increment) });
batch.commit();

I was concerned, that an "evil client" could just update the votes without adding or deleting his own document.
So I came up with the following firestore rule for updating a suggestion (the rule for the upvotes-subcollection is fairly simple only allowing a user to add or delete his own document):
allow update: if
  (
    request.resource.data.diff(resource.data).affectedKeys().hasOnly(['upvotesCount']) &&
    (
      (request.resource.data.upvotesCount == resource.data.upvotesCount + 1 && !exists(/databases/$(database)/documents/suggestions/$(suggestion)/upvotes/$(request.auth.uid)) && existsAfter(/databases/$(database)/documents/suggestions/$(suggestion)/upvotes/$(request.auth.uid)))
      ||
      (request.resource.data.upvotesCount == resource.data.upvotesCount - 1 && exists(/databases/$(database)/documents/suggestions/$(suggestion)/upvotes/$(request.auth.uid)) && !existsAfter(/databases/$(database)/documents/suggestions/$(suggestion)/upvotes/$(request.auth.uid)))
    )
  )
);

This is to make sure, that a user can only increase/decrease the vote by 1 and only if the user is allowed to by adding or removing his upvote-document in the upvotes-subcollection accordingly.


text:
Q: "ip route" Commands in Dockerfile Generate Error I create a Docker container like this:
$sudo docker build -t "logstash-collector" ~/logging/logstash/

$sudo docker run -d \
--user=root \
--name="logstash-collector-01" \
--net=logging \
--cap-add=NET_ADMIN \
logstash-collector

And from there I can change its default gateway to an nginx container (for transparent load balancing):
$sudo docker exec -it logstash-collector-01 ip route delete default
$sudo docker exec -it logstash-collector-01 ip route add default via 172.18.0.10

And it works, and everything's fine:
$sudo docker exec -it logstash-collector-01 ip route
default via 172.18.0.10 dev eth0
172.18.0.0/16 dev eth0  proto kernel  scope link  src 172.18.0.3

But when I try to automate this by putting those commands in my ~/logging/logstash/Dockerfile like:
FROM logstash
COPY logstash.conf /usr/local/share
CMD ["-f", "/usr/local/share/logstash.conf", "--config.reload.automatic"]
CMD ["ip", "route", "delete", "default"]
CMD ["ip", "route", "add", "default", "via", "172.18.0.10"]

I see them getting executed during build:

But the container fails to launch.  sudo docker logs logstash-collector-01 tells me:
RTNETLINK answers: File exists
That error happens if I issue the second ip route command without issuing the first one (Linux won't add a route if one is already in its active routing table).  But how can this be?  Are my Dockerfile's CMD commands processing out of order?

A: This is because you can only specify one CMD per dockerfile.
CMD is what the container will be running (which would normally be logstash, a long-running, daemon-like process), so what are you doing is only running the last CMD.
See https://stackoverflow.com/questions/23692470/why-cant-i-use-docker-cmd-multiple-times-to-run-multiple-services#23693804
You could consider a lo-fi solution like using a single container's network to share between nginx and the logstash agents, but you then need to keep track of ports.
Higher up the chain are solutions like kubernetes that make this kind of thing easier.
In between, you might look into consul(/SkyDNS) to help with DNS discovery.


text:
Q: Angular: NgbTypeahead and onScreen keyboard I've implemented some autocomplete with the NgbTypeahaed bootstrap lib and it works fine. Now i'm trying to attach onScreen virtual keyboard, but I have no idea how to connect between them since the NgbTypeahaed firing the event from input's attribute --> [ngbTypeahead]="autocomplete_data" when autocomplete_data is the source.
So how can I control or 'mock' the events of real typing?

A: To 'mock' the event triggered by outsource element, I dispatched an event to it:
let input = document.getElementsByClassName('searchText')[0];
    input.dispatchEvent(new Event('input'));


text:
Q: Почему не отображается иконка? Подскажите пожалуйста вот у меня есть проект:

Когда я запускаю модуль registration_window открывается окно с кнопкой, когда я нажимаю на кнопку открывается окно модуля main_window, но почему то не отображается иконка user.png, хотя если отдельно запустить окно модуля main_window, то иконка отображается нормально.
У меня большая программа будет в которой пользователь проходит регистрацию и открывается главное окно программы, я хочу чтобы иконка отображалась, как это можно сделать.
user.png:

registration_window.py
from PyQt5.QtWidgets import (QWidget, QPushButton, QVBoxLayout, QApplication)
from main_window import CentralWidget
import sys

class RegistrationWindow(QWidget):
    def __init__(self, parent=None):
        super(RegistrationWindow, self).__init__(parent)
        self.resize(300, 300)
        self.setWindowTitle("")
        self.setObjectName('registration_window')
        self.setStyleSheet('''#registration_window {
                                background-color: #4dffff;
        }''')
        self.main_window_app = CentralWidget()
        self.btn = QPushButton('Открыть')
        self.btn.clicked.connect(self.save_input_user_kbju)

        layout = QVBoxLayout()
        layout.setContentsMargins(30, 30, 30, 30)
        layout.addWidget(self.btn)
        self.setLayout(layout)

    def save_input_user_kbju(self):
        self.close()
        self.main_window_app.show()

if __name__ == '__main__':
    app = QApplication(sys.argv)
    win = RegistrationWindow()

    win.show()
    sys.exit(app.exec_())

main_window.py
from PyQt5.QtWidgets import (QWidget, QApplication, QFrame, QVBoxLayout, QLabel, QHBoxLayout)
from PyQt5.QtGui import QPixmap, QImage
import sys

class CentralWidget(QWidget):
    def __init__(self, parent=None):
        super(CentralWidget, self).__init__(parent)
        self.resize(300, 300)

        self.setWindowTitle('КБЖУ')
        self.setStyleSheet('background-color: #ffffff;')

        self.frame_name = QFrame()
        self.frame_name.setFrameStyle(QFrame.Box)
        self.frame_name.setStyleSheet('''QFrame {
                            border: 0px;
                            background-color: #9EFFFF;
        }''')

        self.icon_user = QLabel()
        self.icon_user.setPixmap(QPixmap.fromImage(QImage('icon_app/user.png')))
        self.label_name = QLabel('Имя')
        self.label_name.setStyleSheet('''QLabel {
                            color: #4f4a4a;
                            font-size: 20px;
        }''')

        #  Верхнее меню и имя
        self.name_layout = QHBoxLayout()
        self.name_layout.setSpacing(10)
        self.name_layout.addWidget(self.icon_user)
        self.name_layout.addWidget(self.label_name)
        self.name_layout.addStretch(1)
        self.frame_name.setLayout(self.name_layout)

        #  Главная форма
        self.layout_main_menu = QVBoxLayout()
        self.layout_main_menu.setContentsMargins(0, 0, 0, 30)
        self.layout_main_menu.addWidget(self.frame_name, stretch=2)
        self.layout_main_menu.addStretch(1)

        self.setLayout(self.layout_main_menu)

if __name__ == '__main__':
    app = QApplication(sys.argv)
    win = CentralWidget()
    win.show()
    sys.exit(app.exec_())

A: Попробуйте, так.
Обратите внимание, что запускать (откуда угодно) будем модуль q1388871_main_window.py:
C:\> python D:\_Qt\__Qt\q1388871_main_window.py
Проект у меня находится D:\_Qt\__Qt, изображения D:\_Qt\__Qt\icon_app
q1388871_main_window.py
import sys
import os
from PyQt5.QtWidgets import (QWidget, QApplication, QFrame,
    QVBoxLayout, QLabel, QHBoxLayout)
from PyQt5.QtGui import QPixmap, QImage

from q1388871_registration_window import RegistrationWindow                    # +++

dir_path = os.path.dirname(os.path.abspath(__file__))                          # !!! +++
directory = os.path.join(dir_path, 'icon_app')                                 # !!! +++
print(f'\n{dir_path} \n{directory}')

class CentralWidget(QWidget):
    def __init__(self, parent=None):
        super(CentralWidget, self).__init__(parent)
        self.resize(300, 300)

        self.setWindowTitle('КБЖУ')
        self.setStyleSheet('background-color: #ffffff;')

        self.frame_name = QFrame()
        self.frame_name.setFrameStyle(QFrame.Box)
        self.frame_name.setStyleSheet('''QFrame {
                            border: 0px;
                            background-color: #9EFFFF;
        }''')

        self.icon_user = QLabel()

#        self.icon_user.setPixmap(QPixmap.fromImage(QImage('icon_app/user.png')))
        self.icon_user.setPixmap(QPixmap.fromImage(QImage(f'{directory}/user.png')))      # +++
# +++ -->                                                 ^^^^^^^^^^^^^

        self.label_name = QLabel('Имя')
        self.label_name.setStyleSheet('''QLabel {
                            color: #4f4a4a;
                            font-size: 20px;
        }''')

        #  Верхнее меню и имя
        self.name_layout = QHBoxLayout()
        self.name_layout.setSpacing(10)
        self.name_layout.addWidget(self.icon_user)
        self.name_layout.addWidget(self.label_name)
        self.name_layout.addStretch(1)
        self.frame_name.setLayout(self.name_layout)

        #  Главная форма
        self.layout_main_menu = QVBoxLayout()
        self.layout_main_menu.setContentsMargins(0, 0, 0, 30)
        self.layout_main_menu.addWidget(self.frame_name, stretch=2)
        self.layout_main_menu.addStretch(1)

        self.setLayout(self.layout_main_menu)

        self.registrationWindow = RegistrationWindow(self)                           # !!! +++
        self.registrationWindow.show()                                               # !!! +++

if __name__ == '__main__':
    app = QApplication(sys.argv)
    win = CentralWidget()

#    win.show()                                                                      # !!! ---

    sys.exit(app.exec_())

q1388871_registration_window.py
import sys
from PyQt5.QtWidgets import (QWidget, QPushButton, QVBoxLayout, QApplication)

# - from q1388871_main_window import CentralWidget

class RegistrationWindow(QWidget):
#    def __init__(self, parent=None):
#        super(RegistrationWindow, self).__init__(parent)
    def __init__(self, parent):                                                # +++
        super().__init__()                                                     # +++
        self.parent = parent                                                   # +++

        self.resize(300, 300)
        self.setWindowTitle("")
        self.setObjectName('registration_window')
        self.setStyleSheet('''#registration_window {
                                background-color: #4dffff;
        }''')
#-        self.main_window_app = CentralWidget()
        self.btn = QPushButton('Открыть')
        self.btn.clicked.connect(self.save_input_user_kbju)

        layout = QVBoxLayout()
        layout.setContentsMargins(30, 30, 30, 30)
        layout.addWidget(self.btn)
        self.setLayout(layout)

    def save_input_user_kbju(self):
        self.close()
#-        self.main_window_app.show()
        self.parent.show()                                                     # +++

if __name__ == '__main__':
    app = QApplication(sys.argv)
    win = RegistrationWindow()
    win.show()
    sys.exit(app.exec_())

Я понимаю, то что если я в один пакет положу все модули то все работает, но мне нужно чтобы работала так как у меня пакеты сделаны в проекте, и у меня запускается первым регистрация а потом главное окно, а вы просто все поняли местами и в один пакет положили, но у меня в настоящей программе будут десятки модулей в разных пакетах

Вы не поняли мой посыл. Да, я не разместил модули как у вас в проекте, но я предполагал, что вы это сделаете самостоятельно. Теперь я разместил все как у вас. Я изменил только одну строчку:
q1388871_main_window.py
import sys
import os
from PyQt5.QtWidgets import (QWidget, QApplication, QFrame,
    QVBoxLayout, QLabel, QHBoxLayout)
from PyQt5.QtGui import QPixmap, QImage

from authentication_window.q1388871_registration_window import RegistrationWindow    # +++
#--> ^^^^^^^^^^^^^^^^^^^^^^

dir_path = os.path.dirname(os.path.abspath(__file__))                          # !!! +++
directory = os.path.join(dir_path, 'icon_app')                                 # !!! +++
print(f'\n{dir_path} \n{directory}')

class CentralWidget(QWidget):
    def __init__(self, parent=None):
        super(CentralWidget, self).__init__(parent)
        self.setWindowTitle("main_window.py")
        self.resize(300, 300)

        self.setWindowTitle('КБЖУ')
        self.setStyleSheet('background-color: #ffffff;')

        self.frame_name = QFrame()
        self.frame_name.setFrameStyle(QFrame.Box)
        self.frame_name.setStyleSheet('''QFrame {
                            border: 0px;
                            background-color: #9EFFFF;
        }''')

        self.icon_user = QLabel()

#        self.icon_user.setPixmap(QPixmap.fromImage(QImage('icon_app/user.png')))
        self.icon_user.setPixmap(QPixmap.fromImage(QImage(f'{directory}/user.png')))      # +++
# +++ -->                                                 ^^^^^^^^^^^^^

        self.label_name = QLabel('Имя')
        self.label_name.setStyleSheet('''QLabel {
                            color: #4f4a4a;
                            font-size: 20px;
        }''')

        #  Верхнее меню и имя
        self.name_layout = QHBoxLayout()
        self.name_layout.setSpacing(10)
        self.name_layout.addWidget(self.icon_user)
        self.name_layout.addWidget(self.label_name)
        self.name_layout.addStretch(1)
        self.frame_name.setLayout(self.name_layout)

        #  Главная форма
        self.layout_main_menu = QVBoxLayout()
        self.layout_main_menu.setContentsMargins(0, 0, 0, 30)
        self.layout_main_menu.addWidget(self.frame_name, stretch=2)
        self.layout_main_menu.addStretch(1)

        self.setLayout(self.layout_main_menu)

        self.registrationWindow = RegistrationWindow(self)                           # !!! +++
        self.registrationWindow.show()                                               # !!! +++

if __name__ == '__main__':
    app = QApplication(sys.argv)
    win = CentralWidget()

#    win.show()                                                                      # !!! ---

    sys.exit(app.exec_())

Обратите внимание, что запускать (откуда угодно) будем модуль q1388871_main_window.py


text:
Q: dynamically setting meta tags as per URL Lets I have a search engine which searches for the query specified in the URL as exemplified :-
1. xyz.com/apple-ipod-touch
2. xyz.com/apple-macbook-pro
3. xyz.com/reebok-shoes

Now, depending on the URL, I wish to set the meta tags of my pages.
Please note that I don't wish to change these meta-tags using javascript , as these have to be read by Facebook for publishing stream. So, I am expecting something which changes meta-tags in the server-side itself(like somehow through .htaccess). Is there any way to do the same ?
Any suggestions or links will do.
Please comment if I am unclear in asking my doubt.
Thanks !
Thanks !

A: If the pages are being created dynamically, than I would assume you're using some sort of database to store information pertaining each product. So when you make a call, just simply placing something along the lines like
<?
    $ogtitle = ($mysqlrow["product_title"])? $mysqlrow["product_title"] : "Use normal site title here";
?>
<meta property="og:title" content="<?=$ogtitle;?>" />

This is assuming you are using PHP, but basic scenario for other server side languages as well.


text:
Q: Rewrite rule. .htaccess . ERR_TOO_MANY_REDIRECTS I added the following Rewrite rule to .htaccess:
RewriteEngine on
RewriteRule ^page/?$ index.php?cat=123 [L]

and it loads content of /index.php?cat=123 when I go to www.site.com/page
The problem is that I also need to set up redirection from www.site.com/index.php?cat=123 to www.site.com/page
but when I try to do this I get "too many redirections" error. Any idead how fix this?
RewriteEngine on
RewriteRule ^page/?$ index.php?cat=123 [L]
RewriteCond %{QUERY_STRING} ^cat=123$
    RewriteRule ^index\.php$ http://www.mysite.com/page [L,R=301]


text:
Q: DownGrade versão do java - The package javax.xml.parsers is accessible from more than one module Tenho um projeto em Java 12 que está funcionando 100%.
Meu objetivo é fazer um downgrade do Java 12 para o 11, porém quando eu faço essa mudança recebo um erro em umas dependências específicas.
Este é o erro que recebo:

The package javax.xml.parsers is accessible from more than one module

Imagem dos erros abaixo:

Eu já tentei importar as 3 dependências que não estão mais embutidas, se não me engano a partir do Java 9. Porém ainda assim o problema persiste, sendo que no Java 12 funciona normalmente


text:
Q: Is file cache flushed automatically after time? Let's say I copy a file using cp and the proccess returns immedietly because the file was written to cache.
Then I leave the PC alone for 1 hour. Nothing special running on it.
Is the cache flushed automatically in this time?
Does it matter if the file (writing to) is a block device file, a mapper file or normal file?

A: First of all, the cache is flushed as soon as OS is able to do it. Second, even the least important process has a chance to do its work.
For example, even if you have a super-high priority process, which is constantly touching hard drive, then even a super-low shell operation will have a chance to remind cache that it has some data to flush.
So, the answer is no.


text:
Q: android regex error That is my text i want to do regex
    url: 'http://stackoverflow.com/questions/33048725/ocamllex-regex-syntax-error'

},

That is normal form of regex
url:\s'(.*)'\s*},

Yhat is inside eclipse version with escape
url:\\s'(.*)'\\s*},

but android studio gives error.
Caused by: java.util.regex.PatternSyntaxException: Syntax error in regexp pattern near index :

It shows last letter. ,
this , is faulty.
i define patter like this
 pattern = "url:\s'(.*)'\s*},"

Why?
I also used with backslash but still same. This time it shows \ in front of coma.

A: url:\\s'(.*)'\\s*\\},

You need to escape {} as well.


text:
Q: Convolution of two PDF: $1/(2\sqrt{3x})$ I'm trying to find the result of the sum of two PDF that is the square of two continuous uniform distribution (rectangular distribution) that have $\mu =0$ and $\sigma =1$.
The square of this continuous uniform distribution is defined from 0 to 3 and is $$p(x)= \frac{1}{2 \sqrt{3x}}$$
Now i need to find the PDF of the sum of two random variables with p(x) as distribution.
The convolution integral is $$p(u)=\int_0^3 p(u-t)p(t)dt=\int_0^3 \frac{dt}{12 \sqrt{t(u-t)}}= \frac{arcsin \left( \sqrt{ \frac{3}{u}} \right)}{6}$$
This funcion is not defined on R from 0 to 6.
If i extract the real part of $(p(u))$ i obtain the correct PDF from 0 to 3 but the part from 3 to 6 is wrong and p(u) is not normalized from 0 to 6.
I simulate this PDF with python, here is an image
Simulation of PDF: https://imgur.com/ImqT7ya
Plot of the PDF: https://imgur.com/khg8rGM
what did I do wrong?

A: The key is in the support interval.   Both $t$ and $u-t$ must lie within the support, or otherwise $p(t)p(u-t)=0$.   So the bounds for the integral depends on the value given for $u$.
You have $p(x)=\dfrac 1{2\sqrt{3x}}\mathbf 1_{0\leq x\leq 3}$
The the convolution is $$\begin{split}\int_\Bbb R p(t)p(u-t)~\mathsf d t &= \int_\Bbb R \tfrac{1}{12\sqrt{t(u-t)}}\mathbf 1_{0\leq t\leq 3~,~0\leq u-t\leq 3}~\mathsf d t\\&= \int_\Bbb R \tfrac{1}{12\sqrt{t(u-t)}}\mathbf 1_{0\leq t\leq 3~,~ t\leq u~,~ u-3\leq t}~\mathsf d t\\ &= \int_{\max\{0,u-3\}}^{\min\{3,u\}} \tfrac{1}{12\sqrt{t(u-t)}}~\mathbf 1_{0\leq u\leq 6}~\mathsf d t \\ &= \mathbf 1_{0\leq u\leq 3}\int_{0}^{u} \tfrac{1}{12\sqrt{t(u-t)}}~\mathsf d t+\mathbf 1_{3<u\leq 6}\int_{u-3}^{3} \tfrac{1}{12\sqrt{t(u-t)}}~\mathsf d t\end{split}$$


text:
Q: Setup local IIS7 for testing websites Is there an alternative, other then modifying HOSTS to setup temp domains when testing websites locally? I'm using IIS7 on Win7.
I don't want to use /localhost/domainname. I'd rather do /domainname so i don't have to worry about paths to files, etc. My websites are setup so that paths to files are relative to the root folder and not to the page.

A: Unless your code explicitly checks the domain name, you should be able to deploy on II7 and test through http://localhost.
There are few caveats with this approach, though:

*

*if you are using third-party API that requires a key tied to the domain name of you app, you might have to request two keys - one for the domain name (for PROD purposes) and one for localhost (for DEV purposes). I do that with both Google Ajax API and Facebook Connect keys.

*http://localhost is in different security zone in IE than regular internet sites, so if your app uses any AP that requires cross-domain communication (like Facebook Connect), you might have problems testing on IE7. Works like a charm on Chrome and seems to work properly on IE8.

*if you are working on multiple apps at the same time, you can't have all of them listen on port 80 at the same time. SO, some of the apps will have to be moved to http://localhost:8080 or another port.

My approach is to run the VS Dev WebServer (Cassini) on ports 808x during developing and to deploy to the local IIS7 (using CruiseControl.Net) on ports 888x. This allows me to debug easily with VS while working on the code, yet still have the site set under medium trust on IIS7.
I also have a host name on the target domain pointing to my dev machine, so the IIS7 instances are available both as http://localhost:888x and http://dev.domain.com:888x, which allows me to also test the domain integration with Google Ajax and Facebook Connect APIs. Of course, this requires control over the domain DNS and the ability to add an A record to it.
However, note that nothing in this setup requires actual testing on the domain URL.


text:
Q: How to submit iPhone app (with watch kit extension and watch app) to app store? I'd like to know how the process differs from the existing iPhone app submission procedure, as by following the usual process leads to an error of invalid binary after the app gets successfully submitted to App Store.

A: Perhaps your version or build number is not the same between your iPhone and watch app?  More information on the error you're getting would be helpful.
I assume you've read this: https://developer.apple.com/app-store/watch/

A: I would also suggest running through the tips listed here: http://www.fiveminutewatchkit.com/blog/2015/4/2/submitting-your-watchkit-app


text:
Q: How can I use swift to read through and identify? If I am using swift, how can I get my program to read through a string of letters to identify something? For example, lets say var aa = "Apple". If I have this string of letters: "aghdbgkldhgaabdfhjk", what code can I use for the program to read through it, identify "aa", and print "apple"? I appreciate any help, thank you!

A: you can check if your String contains "aa" in this link
then return 'Apple'
e.g:
var string = "aghdbgkldhgaabdfhjk"

if string.range(of: "aa", options: String.CompareOptions.diacriticInsensitive, range: nil, locale: nil) != nil {
    print("apple")
}


text:
Q: ETL jobs are failing due to excessive amount of data in big query We are maintaining transaction and historical tables in big query.
If today transaction table have 100 records, the same 100 records would be reflected in history as well. the transaction table is WRITE_TRUNCATE and historical table contains appended data of every day snapshot.
The historical table is now reached to 1 billion. i am pulling the data based on transnational and historical tables into another table by using ETL job. The ETL job is failing while pulling data from historical table.
Is there any solution for this, i dont want to modify the ETL job.


text:
Q: How to disable vim's indentation after "case"? I want my code indent like this:
switch (msg)
{
    case WM_CREATE:
    {
        DoSomething();
    }
}

But Vim always indent code like this:
switch (msg)
{
    case WM_CREATE:
        {
            DoSomething();
        }
}

My vimrc file is:
set autoindent
filetype plugin indent on

What's more, I hava tried:
set cindent
set smartindent
set cinoption=l1

But they all do not work,
I really do not know how to fix it,
Can you help me?
BYW: I am not English native speaker, please forgive me if there are any errors about grammar.

A: Add this to your .vimrc file:
set cino==0
That sets the indent after case to zero. You can find the various options for cindent here.


text:
Q: Cannot delete object with nil fields in Core Data Whenever I create a new entity in core data and save the first object, the Entity always returns the saved object and a object with all fields = nil. If I try to iterate though all objects in Entity and delete, all objects with data delete except the nil object, so problem is this object with nil values for fields is always there.
Any input appreciated.
//get context

        var appDel : AppDelegate = UIApplication.sharedApplication().delegate as AppDelegate;

        var context : NSManagedObjectContext = appDel.managedObjectContext!;

        var newEntry3 = NSEntityDescription.insertNewObjectForEntityForName("TestParse", inManagedObjectContext: context) as NSManagedObject;

        var error : NSError? = nil;

        //Fetch request

        var request = NSFetchRequest(entityName: "TestParse");

        // for beta 4 xcode only
        request.returnsObjectsAsFaults = false;

        var results  = context.executeFetchRequest(request, error: nil);

        println("\n\nResults from DB \(results?.count) and teh results object \(results)\n\n");

        if results?.count > 0{

            for result : AnyObject in results! {

                println("Database object form parse: \(result.count) and contents : \(result.description)");

              // delet object and save for debugging an delete the 'nil' object                  context.deleteObject(result as NSManagedObject);

               context.save(&error);
                println("DELETED CORE DATA OBJECT : \(result)");


text:
Q: SQL group by highest occurance By executing this query
SELECT year, genre, COUNT(genre)
FROM Oscar
GROUP BY year, genre

I got the following output:
2016        Action      2
2016        Romance     1
2017        Action      1
2017        Romance     2
2018        Fantasy     1
2019        Action      1
2019        Fantasy     2
2020        Action      3
2020        Fantasy     1
2020        Romance     1

Now i want to display only the genre with the highest number per year to display. What is the best way to do this?
So I want the output to look like this:
2016 Action
2017 Romance
2018 Fantasy
2019 Fantasy
2020 Action

A: You can use window functions:
SELECT year, genre
FROM (
    SELECT year, genre, RANK() OVER(PARTITION BY year ORDER BY COUNT(*) DESC) rn
    FROM Oscar
    GROUP BY year, genre
) t
WHERE rn = 1

If your database does not support window functions (eg MySQL < 8.0), another option is:
SELECT year, genre
FROM Oscar o
GROUP BY year, genre
HAVING COUNT(*) = (
    SELECT COUNT(*)
    FROM Oscar o1
    WHERE o1.year = o.year
    GROUP BY o1.category
    ORDER BY COUNT(*) DESC LIMIT 1
)

A: Use window functions:
SELECT year, genre
FROM (SELECT year, genre, COUNT(*) as cnt,
             RANK() OVER (PARTITION BY year ORDER BY COUNT(*) DESC) as seqnum
      FROM Oscar
      GROUP BY year, genre
     ) yg
WHERE seqnum = 1;

If there are ties, RANK() returns all highest ranked values.  Use ROW_NUMBER() if you specifically want one row, even when there are ties for first.


text:
Q: Vuejs and HTML5 Gamepad API: How to render Gamepad Object? I'm trying to list available gamepads and select a gamepad in available gamepads. When select this gamepad button pressed gamepads list will be not visible and only selected gamepad will be visible.
I tried to do this with v-if:

  {{selectedGamepad.axes}}

    {{gamepad.id}}
    <button v-on:click="selectedGamepad = gamepad;">Select This Gamepad</button>

But when I press the button selectedGamepad values not change dynamically. Because when I press the button, Vuejs not render the gamepads loop.
But if gamepads loop visible selectedGamepad values changes dynamically.(if you remove v-if on gamepads loop)
I don't understand why v-for="gamepad in gamepads" effect to selectedGamepad.
If I use v-show instead of v-if everything works fine but I don't want to render gamepads after button pressed.
You can see full example from here : https://jsfiddle.net/eywraw8t/518811/
I think the problem is related to the Gamepad object. If selectedGamepad is a Gamepad object Vuejs can't render dynamically. But if selectedGamepad is a array(axes array for example) everything works fine. But i can't figure out how to render Gamepad object correctly.


text:
Q: How synchronize multiple machines to insert one single row? I have some code that is running on several machines, and accesses an Oracle database. I use this database (among other things) as a synchronization object between the different machines by locking rows.
The problem I have is that when my process is starting, there is nothing yet in the database to rely on for synchronization, and my processes get oracle exceptions about unique constraint violated since they all try to insert at the same time.
My solution for now is to catch that precise exception and ignore it, but I don't really like having exceptions being thrown in the normal workflow of my application.
Is there a better way to "test and insert" atomically in a database ? Locking the whole table/partition when inserting a row is not an acceptable solution.
I checked merge into, thinking it was my solution, but it produces the same problem.

A: You probably want to use DBMS_LOCK, which allows for user application code to implement the same locking model as the Oracle database does in locking rows and other resources.  You can create an enqueue of type 'UL' (user lock), and define a resource name, and then have multiple sessions lock to their hearts content, without any dependence on data in a table somewhere.  It supports both exclusive and shared locking, so, you have have some processes that can run concurrently (if they take a shared lock) or other processes that run exclusively (if they take an exclusive lock) and they will automatically queue behind the shared lock (if any) that are being held by the other type of process, etc.
It's a a very flexible locking model, and you don't need to rely on any data in any table to implement it.
See the Oracle PL/SQL Packages and Types Reference, for the full scoop on the DBMS_LOCK package.
Hope that helps.

A: You won't get an error immediately if your PK is policed by a non-unique index, consider:
<<SESSION 1>>
SQL> create table afac (
  2     id number,
  3     constraint afac_pk primary key (id)
  4        deferrable /* will cause the PK to be policed by a non-unique index */
  5  );

Table created.

SQL> insert into afac values (1);

1 row created.

<<SESSION 2>>
SQL> insert into afac values (1); /* Will cause session 2 to be blocked */

Session 2 will be blocked until session 1 either commits or rollbacks. I don't know if this mechanism is compatible with your requirement though.


text:
Q: Visual Studio Error "make sure the path or internet address is correct" Error Message Box Pops out and said

"file:///%7B0%7D make sure the path or internet address is correct"

the line of code which sent this error v
webBrowser1.Url = new Uri(string.Format("file:///{0}/Monaco/Monaco.html", Directory.GetCurrentDirectory()));


text:
Q: Why isn't $\sqrt{64x^4y^8z^6}$ equal to $8x^2y^4z^3$? I simplified $$\sqrt{64x^4y^8z^6}$$ by taking the square root of $64$ (getting $8$), $x^4$ (getting $x^2$), $y^8$ (getting $y^4$), and $z^6$ (getting $z^3$). My answer, $8x^2y^4z^3$, not quite right and I am having a hard time understanding why not.
I even placed the problem into WolframAlpha.com (here) and got the same answer, which was really confusing. Any pointers of what I might be doing wrong?

A: As per the hint, you have to be careful since $z^3$ is negative if $z<0$ and the square root refers to the principal (nonnegative) root. Wolfram also mentions the assumption that $x,y,z$ are positive in their simplification to your answer. But for arbitrary real $x,y,z$ we have
$$\sqrt{64x^4y^8z^6}=8x^2y^4|z|^3.$$

A: It's conventional for $\sqrt n$ to give you the positive square root of $n$, but in this case they might be expecting you to give the answer in the form $\pm {8x^2y^4z^3}$


text:
Q: Unable to add all the files once but individually can in git I am learning how to use git. I am unable to add all the files once but individually can.

Error : doesn't have a commit checked out.
Its been long i have been trying to use git, have followed 3 videos. In the videos, they successfully able to do all the operations but I receive an error which they don't. I am not able to setup the git. I have attached the screen shot for your reference.
Also, please refer me to some tutorials or book in which i can get right from git installation.
I am using Windows 10 and git version 2.27.0.windows.1
If somebody can, list down all the steps, so that i can follow it and if error occurs and can point out specific step and error. As there are many ways to setup git, i have to follow where i have incomplete project, which i can push and can restart working on code.
Early help would be much appreciated.
Thanks

A: It seem like you have another git repository(nested git repositories) initialized in the "pro1" directory. I don't think you require that. Remove ".git" from the "pro1" directory. You can use command on git bash(command line of which you have posted the screenshot):
rm -rf pro1/.git

Now use following command to add all the files:
git add .

or

git add -A

Another alternative is that you first commit and push the code in "pro1" directory and then try to push the code outside that directory. But that is not the recommended way of handling the git repositories.
You can refer Traversy Media tutorial for quick reference. It will work for most of cases. if still you face issue, just copy and paste that error on google, you will get the right answer.

A: It looks like the pro1 subdirectory inside your repo is registered as a submodule.
To confirm this : run cat . gitmodules from your repo base directory.

If this was unintented, follow this procedure to remove it :
git submodule deinit pro1
git rm pro1
rm -rf .git/modules/pro1

If you want to have pro1 as a submodule within itself : go into pro1, and choose what should be checked out there :
cd pro1
git checkout some/branch


text:
Q: JS event listener for a type of element? Is there a way to add some kind of listener for a type of html element? For example if i wanna call a function when the user clicks any p element

A: the easiest answer would be using addEventListener() if you want a specific html tag just like what i wanted in my question then you'll find the answer there ill paraphrase it here too
add this

to the end of your document
by the way don't forget to use uppercase nodeNames or just put a toLowerCase() before it. cheers :)

A: Add the event listener to the window / document / document.body and check the type of the element and the types of its parents because if you have a  inside a
, clicking the span won't trigger the click in the paragraph.
document.addEventListener("click", function (eventArgs) {
    var target = eventArgs.target;
    var elementToLookFor = "p";
    while (target !== null) {
        if (target.tagName.toLowerCase() === elementToLookFor) {
            // Do magic stuff with the paragraph
            console.log(target);
        }
        target = target.parentElement;
    }
});

This technique is called "event delegation."
Edit: Note that you cannot early return from the loop above. If your have nested paragraphs, i.e.

    Hey,

there!

Having an early return will only call your event handler for the inner paragraph, whereas you said that you'd like the handler to be invoked on every paragraph which is why you need to traverse all the ancestors of the element.

A: I assume that you are looking for code along these lines:
var paras = document.getElementsByTagName("p");

// Loop through elements.
for(var i = 0; i < paras.length; i++) {
    // Add listener.
    paras[i].addEventListener("click",
        function() {
            // Execute function.
        }, false);
}

A: I'd just select all the elements on the page and add eventListeners on them like so:
function addListeners(elementType, eventType, callback) {
    Array.prototype.slice.call(document.querySelectorAll(elementType)).forEach(function (el, i) {
        el.addEventListener(eventType, callback, false);
    });
}

Above we use querySelectorAll to pick all the wanted elements, convert it to an Array (if you use es6, you can use Array.from) and then we loop through the array and add listeners with the wanted callback.
Here's an example: https://jsfiddle.net/a7en4d4s/

A: Look at this JSFiddle, and see if it works for you
Click Yes

Click No

Clicked:


text:
Q: Почему для hibernate свойства можно прописать только через hibernate.properties Почему у меня через файл hibernate.properties получается задать свойства:

А через application.properties не получается?

A: Дело было в том, что у меня приложение не было spring-boot приложением. Поэтому файл application.properties не считывался.


text:
Q: Android XML Parsing error: Only one root element allowed I want to parse an XML. I am posting my XML response below. In the
pre tag I am getting a JSON which i want to print but I am not able to parse with my code. I am posting my code to parse this XML.
private void xmlParsing(String qrCode) {
        try {
            qrCode = qrCode.replaceAll("[^\\x20-\\x7e]", "");
            //loge("qrCode : " + qrCode);
            DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
            Document doc = dBuilder.parse(new ByteArrayInputStream(qrCode.getBytes("utf-8")));

            Element element = doc.getDocumentElement();
            element.normalize();

            NodeList nList = doc.getElementsByTagName("head");
            loge("--df--nList.getLength()---"+nList.getLength());
            for (int i=0; i<nList.getLength(); i++) {

                Node node = nList.item(i);
                if (node.getNodeType() == Node.ELEMENT_NODE) {
                    Element element2 = (Element) node;

                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

{"status":true,"message":"Login Successfull","data":{"user":{"id":2,"name":"Rommy Garg","email":"rommy@signitysolutions.com","user_group_id":"2","company_id":2,"last_login":"2019-05-29 05:48:27","last_logout":"2019-05-28 10:33:39","profile_pic":null,"created_at":"2018-12-20 10:12:23","updated_at":"2019-05-29 05:48:27","sf_reference_id":"0056F00000BqMZSQA3","sf_setup":1},"company_logo":"http:\/\/staging.sales-chap.com\/dist\/uploads\/company\/1545300743.jpg","client_id":1,"client_secret":"IQ09J2BdDuc3lSKUJlQAp8uhCXRq+s2EucsBOb9rfjo="}}

but I am getting below error:

org.w3c.dom.DOMException: Only one root element allowed

A: Well, as the error said, XML only allows a single root element. You could create a fake one around the string you recieve:
qrCode = "" + qrCode + "";


text:
Q: Always face north-up sided maps activity In maps Activity, the user should not change the angle of direction which the map faces. Map should always face only north side up. How to lock the direction only to north side up and it should able to zoom-in and zoom-out.

A: If you use Google Maps, just add
googleMap.uiSettings.isRotateGesturesEnabled = false


text:
Q: Can't perform API request from one docker image to another Im working on an application where I have a react frontend and a java spring backend. I have a simple API call where I want to return a new address. I have verified this works by using a separate container to perform a curl command docker container run --rm -it --net multichain-network byrnedo/alpine-curl http://multichain-api:8080/api/blockchain/address/create. This call returns the the expected result.
Now I have created my docker environments using docker-compose and they are all up and running and can ping one another
version: "3.7"

networks:
  multichain-network:
    driver: bridge
    ipam:
      driver: default
      config:
        - subnet: 172.18.0.0/16
    name: multichain-network

services:
  multichain-api:
    build:
      context: ./blockchain
    networks:
      - multichain-network
    ports:
      - "8080:8080"
    volumes:
      - type: bind
        source: ${PWD}/blockchain/target
        target: /target
    container_name: multichain-api

  frontend:
    build:
      context: ./frontend
    networks:
      - multichain-network
    ports:
      - "3000:3000"
    volumes:
      - type: bind
        source: ${PWD}/frontend
        target: /frontend
    container_name: frontend

I am fairly new to react so I am wondering if it could be something to do within my code, so here is the snippet that makes the call;
getNewAddress = () => {
    console.log("Button clicked");
    axios.get('http://multichain-api:8080/api/blockchain/address/create')
        .then(function (response) {
            console.log("getting new address");
            this.setState({newAddress: response.data});
            console.log(this.state.newAddress);
        })
        .catch(function (error) {
            console.log(error);
        })
}

You will notice in the call that I am calling the container name directly and not the IP address. I am doing this as they are all apart of the one network and when I ping the backend container from the frontend using the container name it works;
docker exec frontend ping multichain-api
PING multichain-api (172.18.0.4): 56 data bytes
64 bytes from 172.18.0.4: seq=0 ttl=64 time=0.295 ms
64 bytes from 172.18.0.4: seq=1 ttl=64 time=0.158 ms
64 bytes from 172.18.0.4: seq=2 ttl=64 time=0.253 ms

When my code tries to make the call this is the error being produced on the dev console;
VM2194:1 GET http://multichain-api:8080/api/blockchain/address/create 0 ()
(anonymous) @ VM2194:1
dispatchXhrRequest @ xhr.js:178
xhrAdapter @ xhr.js:12
dispatchRequest @ dispatchRequest.js:59
Promise.then (async)
request @ Axios.js:51
Axios.(anonymous function) @ Axios.js:61
wrap @ bind.js:9
Container._this.getNewAddress @ Container.js:12
apply @ _apply.js:15
baseInvoke @ _baseInvoke.js:21
apply @ _apply.js:16
(anonymous) @ _overRest.js:32
(anonymous) @ Button.js:74
callCallback @ react-dom.development.js:100
invokeGuardedCallbackDev @ react-dom.development.js:138
invokeGuardedCallback @ react-dom.development.js:187
invokeGuardedCallbackAndCatchFirstError @ react-dom.development.js:201
executeDispatch @ react-dom.development.js:461
executeDispatchesInOrder @ react-dom.development.js:483
executeDispatchesAndRelease @ react-dom.development.js:581
executeDispatchesAndReleaseTopLevel @ react-dom.development.js:592
forEachAccumulated @ react-dom.development.js:562
runEventsInBatch @ react-dom.development.js:723
runExtractedEventsInBatch @ react-dom.development.js:732
handleTopLevel @ react-dom.development.js:4477
batchedUpdates$1 @ react-dom.development.js:16660
batchedUpdates @ react-dom.development.js:2131
dispatchEvent @ react-dom.development.js:4556
interactiveUpdates$1 @ react-dom.development.js:16715
interactiveUpdates @ react-dom.development.js:2150
dispatchInteractiveEvent @ react-dom.development.js:4533
Container.js:19 Error: Network Error
    at createError (createError.js:16)
    at XMLHttpRequest.handleError (xhr.js:87)

Just to note the browser I am using is Chromium Version 68.0.3440.106.
All in all I am not sure if this is a React, docker or browser issue. Looking at the logs for my backend app, when the call is made by the frontend, there is no activity logged, so it is like it is not even being hit.
Any insights into this would be great
Update
I tried this test on Firefox to see if it was a browser issue and the dev console there should an extra piece of information;
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://multichain-api:8080/api/blockchain/test. (Reason: CORS request did not succeed).

A: You have a cors issue, not a docker one. It says that the origin domain of the server that make the request ( frontend - react ) and the server's origin domain ( backend - multichain-api ) are different, and you can find the cors system arch here
For solving this issue in backend server you should tell your server to accept requests from different domains.


text:
Q: What can this C preprocessor macro mapping to a C keyword be used for? I found this line in a legacy code and I'm wondering what is it good for. Do you have any idea?
#define CONST const

A: Sometimes macros like that are used to be able to compile the code with older compilers that may not support all features.
For instance, in this case, you could simply define CONST as empty, which would allow you to compile the code in a very old C compiler without support for the const qualifier.
You will typically see macros like this in implementations of the standard libraries.

There is another common, related case of macros that map to C keywords: to be able to introduce new C keywords in newer C Standards without breaking old code. These standard macros are added for usage convenience, e.g. the bool macro defined in stdbool.h for the _Bool keyword.


text:
Q: JAVA: Draw Gantt diagram How to draw a Gantt chart in JAVA SWING application? Is there any free library that provides such capability? So, what is the best free option? Web-links might be helpful.

A: Have a look at E-Gantt (it only took a few seconds of Google searching to find) :)
Edit: found a better one which is still under active development (the other was not updated since 2006): SwiftGantt.


text:
Q: how to get append table data and getting clicked table row data using jquery I'm trying to append some table row data using ajax and getting that data via jquery
but the thing is both functions are working.
this code function well
function podetails(pid) {
    $.ajax({
        url: "../phpfile/getpurchaseordetails.php?pid=" + pid,
        dataType: 'json',
        type: 'post',
        cache: false,
        success: function (data) {
            alert(data);
            console.log(data);
            var event_data = '';
            $.each(data, function (index, value) {
                console.log(value);
                event_data += '
';
                event_data += '' + value.countt + '	';
                event_data += '' + value.podetail + '	';
                event_data += '' + value.saless + '	';
                event_data += '' + value.productt + '	';
                event_data += '' + value.qty + '	';
                event_data += '' + value.date + '	';
                event_data += '<button class="btn btn-dark editt" onclick="dog()" type="submit" name="insert" id=" '+ value.poid + '">Edit</button>	';
                event_data += '
';
            });
            $("#list_table_json > tbody").empty();
            $("#list_table_json").append(event_data);
        },
        error: function (d) {
            /*console.log("error");*/
            alert("404. Please wait until the File is Loaded.");
        }
    });
}

in this code also function well but alert shows nothing(empty)
function dog() {

    var $row = $(this).closest("tr");    // Find the row
    var $text = $row.find('#co').text();
    alert($text);

    var podetail = $('#list_table_json').closest("tr").find('td:eq(0)').text();
    var pocode = $(this).closest("tr").find('td:eq(1)').text();
    var saleline = $(this).closest("tr").find('td:eq(2)').text();
    var product = $(this).closest("tr").find('td:eq(3)').text();
    var qty = $(this).closest("tr").find('td:eq(4)').text();
    alert(podetail);}

how do I get the data?

A: Your question seems unclear to me but maybe try this :
function podetails(pid) {
    $.ajax({
        url: "../phpfile/getpurchaseordetails.php?pid=" + pid,
        dataType: 'json',
        type: 'post',
        cache: false,
        success: function (data) {
            alert(data);
            console.log(data);
            var event_data = '';
            $.each(data, function (index, value) {
                console.log(value);
                event_data += '
';
                event_data += '' + value.countt + '	';
                event_data += '' + value.podetail + '	';
                event_data += '' + value.saless + '	';
                event_data += '' + value.productt + '	';
                event_data += '' + value.qty + '	';
                event_data += '' + value.date + '	';
                event_data += '<button class="btn btn-dark editt" onclick="dog()" type="submit" name="insert" id=" '+ value.poid + '">Edit</button>	';
                event_data += '
';
            });
            $("#list_table_json > tbody").empty();
            $("#list_table_json").append(event_data);
        },
        error: function (d) {
            /*console.log("error");*/
            alert("404. Please wait until the File is Loaded.");
        }
    });
}

function dog() {
    var $row = $(this).closest("tr");    // Find the row
    var $text = $row.find('.co').text();
    alert($text);

    var podetail = $(this).closest("tr").find('td:eq(0)').text();;
    var pocode = $(this).closest("tr").find('td:eq(1)').text();
    var saleline = $(this).closest("tr").find('td:eq(2)').text();
    var product = $(this).closest("tr").find('td:eq(3)').text();
    var qty = $(this).closest("tr").find('td:eq(4)').text();
    alert(podetail);
}

I replaced "id" by "class" since there can only one element with a specific id per page. There's a chance that the first element with the "co" id is empty, this is the reason why you only get empty values when searching by id.

A: I make this update to my code
    function podetails(pid) {
    $.ajax({
        url: "../phpfile/getpurchaseordetails.php?pid=" + pid,
        dataType: 'json',
        type: 'post',
        cache: false,
        success: function (data) {
            // alert(data);
            // console.log(data);
            var event_data = '';
            $.each(data, function (index, value) {
                console.log(value);
                event_data += '
';
                event_data += '' + value.countt + '	';
                event_data += '' + value.podetail + '	';
                event_data += '' + value.saless + '	';
                event_data += '' + value.productt + '	';
                event_data += '' + value.qty + '	';
                event_data += '' + value.date + '	';
                event_data += '<button class="btn btn-dark editt" onclick="dog(' + value.poid + ')" type="submit" name="insert" id=" ' + value.poid + '">Edit</button>	';
                event_data += '
';
            });
            $("#list_table_json > tbody").empty();
            $("#list_table_json").append(event_data);
        },
        error: function (d) {
            /*console.log("error");*/
            alert("404. Please wait until the File is Loaded.");
        }
    });
}

function dog($dag) {

    var podetail = $('.'+$dag).find('td:eq(0)').text();
    var pocode = $('.'+$dag).find('td:eq(1)').text();
    var saleline = $('.'+$dag).find('td:eq(2)').text();
    var product = $('.'+$dag).find('td:eq(3)').text();
    var qty = $('.'+$dag).find('td:eq(4)').text();
    alert(podetail);}


text:
Q: Importing RxJS 6 in browser? Now that all modern browser support javascript modules, I'm trying out  importing code right in the browser. We can get npm modules from unpkg.com, and I've found the jspm project, which wraps npm modules into a format that can be consumed by the browser.
But I'm still having problems, most notably with RxJS. RxJS, as of version 6, recommends you import constructors and operators like this:
import { Observable, Subject, ReplaySubject, from, of, range } from 'rxjs';
import { map, filter, switchMap } from 'rxjs/operators';

But if I try to do that in the browser with:
import { Observable, Subject, ReplaySubject, from, of, range } from 'https://dev.jspm.io/rxjs@6';
import { map, filter, switchMap } from 'https://dev.jspm.io/rxjs@6/operators';

I get errors along these lines:

Uncaught SyntaxError: The requested module 'https://dev.jspm.io/rxjs@6/operators' does not provide an export named 'map'

I can get around it by importing the whole rxjs module and teasing out what I need, like I would using a CDN:
import rxjs from 'https://dev.jspm.io/rxjs@6';
const { Observable } = rxjs;
import operators from 'https://dev.jspm.io/rxjs@6/operators';
const { map } = operators;

but this defeats what the Rx team is trying to do to decrease the final bundle size, etc.
I'm sure this isn't just an RxJS problem.
What is the solution here moving forward to get our dev javascript (imports directly into the browser) to look like what we'd finally want to pass to a bundler?

A: Here's a simple rxjs starter example stackblitz:

*

*https://stackblitz.com/edit/js-gm1qso
In short:
Make sure you have a script to add the rxjs js file (for example from a CDN)
<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/6.1.0/rxjs.umd.js">

Everything is imported under the rxjs namespace, so to a simple example usage:
rxjs.of(1, 2, 3)
  .subscribe(x => {
    const element = document.createElement('div');
    element.innerText = 'Data: ' + x;
    document.body.appendChild(element)
  },
  err => { },
  () => {
    const element = document.createElement('div');
    element.innerText = 'All done';
    document.body.appendChild(element)
  });

A: The es6 module export syntax is inside the subfolder _esm2015. So you need to import:
import { Observable, Subject, ReplaySubject, from, of, range } from 'https://dev.jspm.io/rxjs@6/_esm2015';
import { map, filter, switchMap } from 'https://dev.jspm.io/rxjs@6/_esm2015/operators';

Sadly you can't just install rxjs with npm install rxjs@6 and then import in the browser, because the distribution source is missing the file extension .js in the import statements: https://unpkg.com/@reactivex/rxjs@6.3.3/dist/esm2015/index.js.
But the browser needs the file extensions for import (at the moment):   (https://developers.google.com/web/fundamentals/primers/modules#specifiers):
// Not supported (yet):
import {shout} from 'jquery';
import {shout} from 'lib.mjs';
import {shout} from 'modules/lib.mjs';

// Supported:
import {shout} from './lib.mjs';
import {shout} from '../lib.mjs';
import {shout} from '/modules/lib.mjs';
import {shout} from 'https://simple.example/modules/lib.mjs';

There is also an issue for this: https://github.com/ReactiveX/rxjs/issues/4416 .

*

*Sidenote: https://dev.jspm.io/rxjs@6/_esm2015 will resolve to https://dev.jspm.io/rxjs@6/_esm2015/index.js
For now you have to rely on https://jspm.io or make your own bundle (e.g. with rollup as suggested by @Ovidiu Dolha).


text:
Q: Can we implement levenberg_marquardt optimizer in tf.keras.sequential compiler? I am using NN for prediction of Fe grades for a given input location coordinates. The total data is divided into training data = 3495 points and test data = 617 data points.
Input and output data
enter image description here
ann = tf.keras.models.Sequential()

ann.add(tf.keras.layers.Dense(units =25, activation = 'gelu'))

ann.add(tf.keras.layers.Dense(units =15, activation = 'gelu'))

ann.add(tf.keras.layers.Dense(units =10, activation = 'gelu'))

ann.add(tf.keras.layers.Dense(units = 1))

ann.compile(optimizer= 'adam', loss = 'mean_squared_error', metrics = ['mae','RootMeanSquaredError'])

history = ann.fit(x_train,y_train,batch_size = 32, epochs = 500, validation_split=0.10, shuffle= True)

I would like to implement Levenberg_marquardt optimizer instead of 'adam'.
Can we do it directly in here? If not how should I proceed if I want to use this optimizer algorithm?

A: It is possible, but definitely not an easy task. See the documentation to see how to do it.

Creating a custom optimizer
If you intend to create your own optimization algorithm,
simply inherit from this class and override the following methods:

_resource_apply_dense (update variable given gradient tensor is dense)
_resource_apply_sparse (update variable given gradient tensor is sparse)
_create_slots (if your optimizer algorithm requires additional variables)
get_config (serialization of the optimizer, include all hyper parameters)
If you're looking for additional optimizers that you can pass directly, you can look at tensorflow_addons


text:
Q: Memory leaks with HashMap/HashSet on Android I have an Android application where I use HashMap where I keep my Threads (values) each executing a task (Runnable). To identify the Threads I use Strings as keys. The Threads are alive as long as they execute a task what is usually not very long. The problem is that they seem to never been released by GC after finishing and being removed from the HashMap (and they are not referenced from anywhere else). If I create a dump of my application there are as many of my tasks in memory as started through the life of the application. Have tried to use HashSet instead but with the same result.
In code I start them with this few lines:
Thread image_fetch_thread = new Thread(new ImageFetchTask(image_url, this));

this.running_image_fetch_threads.put(image_url, image_fetch_thread);

image_fetch_thread.start();

and at some point later they become removed:
this.running_image_fetch_threads.remove(image_url);

Why GC don't like to collect them?

A: Are you certain that your threads are actually finishing?  Even if you remove the reference to your Thread in the HashMap, it will not be GCed if it has not actually finished.  The run method must complete for that to occur.

A: How certain are you that you're actually removing them from the HashMap or HashSet? What's the size() of the collection when you create your dump?

A: As long as you don't declare the hasmap or hashset as weakreference the GC can't do anything to it because your application has a strong reference to it. My answer is in additon to what Robin already said.
http://download-llnw.oracle.com/javase/1.4.2/docs/api/java/lang/ref/WeakReference.html