What triggers a buying frenzy vs a fully stocked bonus?

Question: After fully stocking a floor,  sometimes instead of getting a minor bonus, I receive a message saying that a buying frenzy is going on.  To me, it appears to be randomly generated, but what triggers a buying frenzy as appose to fully stocked bonus?

 VS
Comment: Excellent question, as always, BTW . . .
Answer: I've been looking into this, and first of all, your screenshot shows that the "Fully Stocked" bonus is the buying frenzy, and that's what I've seen...there's only 1 type of bonus possible.  I believe this works the same way as in Tiny Tower, where you get a bux for a Fully Stocked floor.
What I've seen is that this will happen with floors that have all 3 items nearly fully stocked, but it will also happen when 1 of the items is nearly full, and another item is nearly empty.  This leads me to believe that the trigger is something like: if 3 items stocked & at least 2 items > 90% stocked, then award fully stocked bonus.  I have yet to see a fully stocked bonus where this hasn't been met.
Comment: From what I have seen, you get a coin bonus (no popup, +coins in the bottom left of your screen) or fully stocked frenzy bonus
Comment: I updated the original question to show both.  The +41 is the coin bonus I got when fully stocked. (didnt get buying frenzy)
Comment: @ZeroStack - I once got an Imperial Bux for fully stocking! I was in such shock-and-awe that I forgot to take a screenshot. But that's possible too.
Answer: I believe it to be random.  But, it does seem to primarily happen in my quicker stocked levels.  For example, I see it mostly in Mos Espa Cafe, Workout Center, etc.  Never in say Marriage Center, or Lightsaber Craft.
UPDATE:  Of course, right after writing this I started getting buying frenzies on all levels.
You don't know the power of the dark side . . .
LOL
Comment: +1 `you don't know the power of the darkside` lol, I agree that it is random, but it is possible that the only reason it *seems* that we get them more on fast levels is because they are fast, so we tend to stock them more often!
Comment: The more you play straight, the more you get buying frenzies because it's related to the amount of stock you have on a floor.  Perhaps there's more leeway on floors with longer stock times...
Comment: Agreed. I thought the same.


JQuery Conditionally submit forms

Question: I have a table with multiple rows. Each row is a form. I want to use JQuery to submit all the forms that have the check box checked. The form is posting to an IFrame so there is not much need for AJAX.
So far I have:
<code>       $("form").submit();
</code>
which submits the form. but all forms. There is arbritary number of rows, could be 80-100.
Answer: Off the top of my head, you probably want something like this
<code>$("input:checked").parent("form").submit();
</code>
This will find the checked form fields, traverse up to find the parent form object and submit that.
Comment: except if all rows are in the same form, it just submitted the whole form.
Comment: The poster said "Each row is a form" so my example still works.
Answer: I'm not sure about submit, because I've done this in .post(), but here is what I've used to get what I want to send on the submission:
<code>var formElements = $("form").find("input:checked").parent("td").serialize();
</code>
you should be able to send back that variable.
Answer: This is kinda a guess since I'm not sure of your layout, but here goes....
<code>$("td > input:checked > form").submit();
</code>
Comment: The selector should never return null, only a collection with no items.

JQuery Conditionally submit forms


ttk progress bar freezing

Question: I want a progress bar that shows the user the download progress. When updating the GUI and downloading at the same time the progress bar freezes, and I understand why but I don't know how to solve it. I tried multithreading using this post:
 Tkinter: How to use threads to preventing main event loop from "freezing" and using The Basics of Python Multithreading and Queues as a guid to help me fit it to my needs. The problem is that which way I try to achieve my goal, I always seem to make a mistake when changing it to do what I need it to do.
The most basic version of my code (without multithreading):
from Tkinter import *
import ttk
from urllib import URLopener # Downloading files

# Make frame to tell user what file is getting downloaded
self.Progressmsg = Label(self, text="TempValue")
self.Progressmsg.pack(pady=(10,0))

# Make progress bar to show user download progress
self.Progressbar = ttk.Progressbar(self, mode="determinate", orient='horizontal', lengt=280, maximum=len(self.AllClasses))
self.Progressbar.pack(padx=10, pady=10)
self.Progressbar["value"] = 0

def DownloadFile(Class):
    # Update progress message
    self.Progressmsg["text"] = "Downloading {0}.ics...".format(Class)

    # Download each file from saxion website
    CalFile = URLopener()
    CalFile.retrieve("http://[school website]/ical/group/{0}.ics".format(Class), "Data/{0}.ics".format(Class))

    # Update progress bar
    self.Progressbar["value"] += 1

for Study in self.Parameters["Classes"]:
    for Class in Study:
        DownloadFile(Class)

Notes: In this code AllClasses is a list of different classes from which a calendar file has to be downloaded.
The code itself is part of a fairly large class which I didn't include. This is why I am using self.[variablename]
When this code runs the progressbar doesn't load or update, all the files download properly and when they are downloaded the progress bar updates everything at once. My question is: how do I solve this problem in my case?
Answer: Try this:
# Update progress bar
self.Progressbar["value"] += 1
self.Progressbar.update_idletasks()

If it does not work then use self.Progressbar.update() instead.
The GUI won't reflect your changes if there is something else to do (like downloading the next file) unless you call update_idletasks() or update().
Answer: Here's a package you can use which by itself takes care of multithreading issues and also has a control panel to start, stop/resume or terminate the task as needed:

Installation:
pip install progresspanel

Usage:
import tkinter as tk
from progresspanel import Progresspanel
from time import sleep

root = tk.Tk()
panel = Progresspanel(root, title="Sample Task")
panel.pack()

def sample_task():
    total = 5
    panel.set_total(total)
    for i in range(total):
        panel.update(i)
        print("Running iteration: {}".format(i))
        sleep(1)

panel.set_task(sample_task)
root.mainloop()

For your case, you can easily wrap the for loop in a method with proper set_total() and update() as in the example, and pass it to the Progresspanel to start/stop/terminate the task without freezing the GUI.

ttk progress bar freezing


PHP Code and Linefeeds/Carriage Returns

Question: Just wondering, would the following code arrangement cause any issues when calling mysql_connect, i.e.:
public function connect() {
    mysql_connect($this->host,
                  $this->username,
                  $this->password)
        or die("Could not connect. " . mysql_error());

or does it need to be all on one line, i.e.:
mysql_connect($this->host,$this->username,$this->password) or die("Could not connect. " . mysql_error());

Thanks.
Comment: It shouldn't matter. Why don't you post the error you're getting.
Comment: Don't understand the downvote, the question seems clear to me.
Answer: Whitespace (which in this case includes newlines) between tokens is irrelevant.  You could even make it look like this if you wanted
public
function
connect
(
)
{
mysql_connect
(
$this
->
host
,
$this
->
username
,
$this
->
password
)
or
die
(
"could not connect. "
.
mysql_error
(
)
)
;
}

Answer: no, whitespaces are ignored in php as they are in almost every other language (python being a special case, but you can still split lines in python)
Comment: True *most* languages don't care about line breaks, but there are still plenty that use line breaks as delimiters. BASIC variants (incl. VBScript), most shell scripting languages, Javascript to an extent (thanks to the insanely wrong "semicolon insertion" thing)...
Comment: @t.j. crowder: well, in vb you can work around it by using the `_` operator, shell-scripts need to be escaped with `\` and javascript will always be a mystery ;) but you are right, not every language ignores whitespace

PHP Code and Linefeeds/Carriage Returns


Setting element height relative to available space

Question: My grid currently has the following rows defined:
<RowDefinition Height="50" />
<RowDefinition Height="*" />

Unfortunately the data I'm loading into this, even with a ScrollViewer makes the window too "tall" and I lose some of it off the bottom of my screen.
To fix this, I was thinking of doing something like Height="* - x" where x is the amount of pixels I'd like to subtract from whatever value * would be.
Unfortunately this isn't valid markup so how would I do this?
Comment: Have you tried setting a `MaxHeight`?
Comment: Create another RowDefinition with a Height of X or add X to the height of the first one?
Answer: I'm not sure if it is what you are asking for:
<DockPanel>
    <Button DockPanel.Dock="Bottom" Content="Button" />

    <ScrollViewer>
        <Grid DockPanel.Dock="Top" Height="2000">
            <Grid.RowDefinitions>
                <RowDefinition Height="50" />
                <RowDefinition Height="*" />
            </Grid.RowDefinitions>

            <TextBlock Text="Grid.Row=0" />

            <Rectangle Fill="Crimson"  Grid.Row="1" RadiusX="100" RadiusY="100" />
        </Grid>
    </ScrollViewer>
</DockPanel>

Comment: What are the `DockPanel` and `Button` for? Do they make any difference?
Comment: The Button is just there to show that it is never hidden independently the height of the scrollviewer.

The Dockpanel is there to make the Scrollviewer fill all the available space (Not sure if Scrollviewer does already this for its own).


How do you perform mediation analysis with multiple treatments in R

Question: I would like to analyze data from an experiment using mediation analysis in R.  However, the experimental design is a full factorial design across three variables (two continuous, one categorical) and I cannot find an explanation of how to implement mediation in R with multiple treatments.  I have read the documentation on the mediation package but they do not appear to provide ways of expanding X beyond a single treatment.  Similarly, I cannnot find a way to do that in MBESS or lavaan packages.
I found a very recent article that discusses the statistical theory/approaches necessary to implement multiple treatments in mediation analysis, Hayes and Preacher 2014 (http://quantpsy.org/pubs/hayes_preacher_2014.pdf) but, unfortunately, they only give code implementations of their approach in Mplus, SPSS and SAS.  I need to implement this in the next couple days for a presentation so I don't have time to get up to speed on another program to do it, I need to implement it in R.
Does anyone know if there is an implementation in R that I've missed?
Or if there is a way to implement this approach outside of a package?
(I realize I could convert my full factorial design into a single treatment by treating each 3-factor combination as a level but such an analysis would not be helpful.)
Comment: Did you see the function multimed?  Also, the function "findFn" from SOS package can be used to locate packages, e.g., findFn("mediation")  http://www.inside-r.org/packages/cran/mediation/docs/multimed.  See bmem.mi also...
Comment: Thanks, these were helpful ways to research further, though I didn't find what I was looking for.
Answer: After more exhaustive search, it appears that there is not currently an R package that can handle mediation with multiple treatments (ie, predictors).  Packages in R that can do mediation include: mediation, MBESS, lavaan, multimed, bmem, and OpenMx.  However, it appears that those that handle multiple predictors (e.g., OpenMx) also require a model coded as a RAM path model.  This is the type of model needed to code full path analyses and is notably more complex than simplified mediation model coding (e.g. in mediation) that I was hoping for.
Comment: I just skimmed the paper, but on the surface this approach appears similar to partially / hidden markov modeling with latent states for longitudinal data.  There are a number of Markov model packages.  LMest package simulates Markov models for latent categorical data.
Comment: Thanks for the guidance - I may end up going the route of trying to implement that method in R as opposed to a full RAM model/SEM approach.


I'm getting a 404 error when trying to render my results for my API Hack assignment

Question: I'm working on an API Hack assignment for my class with Thinkful and my issue has been that I've been trying to make a call to spoonacular's food api and render the results onto the DOM. However, when I try to do that, All I get in return is a 404 error. I'm wondering if i did something wrong or is some unforeseen problem that is beyond my control?
I've already look at manually typing the composed URL and postman as well.
function queryParams(params) {
    const queryItems = Object.keys(params).map(key => `${encodeURIComponent(key)}= ${encodeURIComponent(params[key])}`)
    return queryItems.join('&');
}

function displayResults(responseJson){
  console.log(responseJson);
  $('#results-list').empty();
  for(let i = 0; i < responseJson.results.length; i++){
    $('#results-list').append(
      `

${responseJson.results[i].id},${responseJson.results[i].protein}

By ${responseJson.results[i].calories}

`
    )};

   $('#results').removeClass('hidden');

};

function getRecipe(query,maxResults,){
  const params ={
    q:query,
    number: maxResults,
  };

  const queryString = queryParams(params)
  const url = searchUrl+'?'+ queryString +'?apiKey='+ apikey;

  console.log(url);

fetch(url,option)
  .then(response =>{
    if(response.ok){
      return response.json();
    }
    throw new Error(response.statusText);
  })
  .then(response => console.log(responseJson))
  .catch(err =>{
    $('#js-error-message').text(`Something went wrong: ${err.message}`);
  });
}

function watchForm() {
  $('form').submit(event => {
    event.preventDefault();
    const searchRecipe = $('.js-search-recipe').val();
    const maxResults = $('.js-max-results').val();
    getRecipe(searchRecipe, maxResults);
  });
}

$(watchForm);

Answer: It looks like you have a couple issues:
First, you're constructing an invalid url:
const url = searchUrl+'?'+ queryString +'?apiKey='+ apikey;
notice the 2 ?s
Also, when you're constructing the query params, you're adding a space between the = and the value of your param
${encodeURIComponent(key)}= ${encodeURIComponent(params[key])}
If you're using the correct path and a valid API key, fixing those things may be enough to make it work.


Realtek 8822CE wifi not working but bluetooth working

Question: I tried to install both Ubuntu 18.04.4 LTS and Ubuntu 19.10 but I'm facing the same issue: I am able to use bluetooth but wifi adapter is not detected.
I checked on my Lenovo laptop's BIOS and I have "Secure boot" disabled so I really don't know what to do.
Can you please help me? Thanks.
This is the output of the command lspci -knn | grep Net -A3; rfkill list:
01:00.0 Network controller [0280]: Realtek Semiconductor Co., Ltd. Device [10ec:c82f]
    Subsystem: Lenovo Device [17aa:c02f]
06:00.0 Non-Volatile memory controller [0108]: Sandisk Corp Device [15b7:5005] (rev 01)
    Subsystem: Sandisk Corp Device [15b7:5005]
0: ideapad_wlan: Wireless LAN
    Soft blocked: no
    Hard blocked: no
1: ideapad_bluetooth: Bluetooth
    Soft blocked: yes
    Hard blocked: no
2: hci0: Bluetooth
    Soft blocked: yes
    Hard blocked: no
While the output of the command dmesg | grep rtw is empty.
Comment: Does this answer your question? [Realtek RTL8822CE is unable to detect WiFi networks](https://askubuntu.com/questions/1180714/realtek-rtl8822ce-is-unable-to-detect-wifi-networks)
Comment: unfortunately not. I tried that but it doesn't work for me
Comment: Please [edit] your question and add output of `lspci -knn | grep Net -A3; rfkill list` terminal command. And also `dmesg | grep rtw`.
Comment: ok I just added the output of the commands you requested
Comment: Why do you think it is rtl8822ce? It is not detected by kernel at all.
Comment: because on windows 10 under the device manager, it shows up as "Realtek 8822CE"
Comment: I couldn't find any drivers that support `[10ec:c82f]`.
Answer: I had the same problem, and I finally found a solution. See here.
In short: it turns out the driver that should support this hardware (rtw88) was available and compatible with this hardware already in kernel > 5.2, but it is not set to recognize this hardware.
To fix the problem I had to compile linux kernel with a small modification to the source code:
Locate the file: ./linux/drivers/net/wireless/realtek/rtw88/pci.c, and edit it. Look for the string '0xC822', and replace it with '0xC82F'
Answer: The idea of the solution from yaron160 works.
I used the code here instead to install the relevant driver module: https://github.com/lwfinger/rtw88. In the code dated 18th May, the file to be changed is rtw8822ce.c instead of pci.c
Hope this answer is helpful
Comment: Welcome to AskUbuntu! This is a good catch, but not a full answer. The other answer may be removed, etc. Please write a full answer, or sugest an edit to the @yaron160 answer.
Comment: Welcome to Ask Ubuntu. This is a question answer site. Incomplete and low quality answers are likely to be deleted by moderators. An link only answer is considered incomplete, as links change or fail after a time. Consider editing your answer and make it self standing and complete. This will help others.
Comment: And also I don't see `rtw_8822ce.mod.c` file there.
Comment: Where did you get the code dated today?
Comment: Thanks everyone for your suggestions. I've had a long day today trying to find the answer. Will update sometime soon (hopefully tomorrow) to be used for my future reference as well. There is a clear set of steps I ended up following that I'll list down
Comment: @Pilot6 Thanks. Edited my original post.
I just checked out the latest code (dated today) :)
Comment: I see that the latest commit was on May 15. I fixed the file name.
Comment: Thanks again for your kind inputs Pilot6 and @user68186
Answer: My solution is for debian(debian 10.5) but since I didn't see my solution anywhere in forums I'm gonna post it if it is not against the rules.
Did it on a Matebook D14 2020 CPU AMD Ryzen 5 3500U with a realtek 8822CE network card.
I had no display without a new linux kernel so I installed the 5.7.X if you want any info on this feel free to DM me.
First you have to edit your /etc/apt/sources.list and add :
deb http://deb.debian.org/debian buster-backports main contrib non-free

then
apt update
this will allow us to download the firmware
https://packages.debian.org/buster-backports/firmware-realtek

back to your terminal install the package by typing :
apt-get -t buster-backports install firmware-realtek

it is important to download with buster-backports, the version in synaptic is not updated and doesn't have the ce firmware. Now you can check if everything is fine with synaptic (if you don't have it I suggest to download it)
synaptic-pkexec

search for "realtek" in the searchbar, you should have the latest version including 8822ce firmware(check the description).
it could probably work on ubuntu but I haven't tried it.
now you can reboot and you should be fine.
Answer: I am new to Linux and had the same problem with my asus tuf gaming a17 laptop.  The lwfinger repository was no longer available, but found the driver elsewhere on github.  Anyway,  installing the driver didn't help,  here it was because i was on firmware 1.173. Search for Linux firmware archive and update to 1.187 (1.187.3 is the current stable supported)  make sure to use the 187_all deb. This got me on track and was able to finally use wifi in Linux.  I didn't post links because it was a learning experience for me and i think all would benefit from that.  Synaptic didn't help by the way.


How to find which zone on Rain Bird sprinkler system is for backyard?

Question: When we did pavers in the backyard, contractor simply capped off sprinklers and did pavers. That means, if sprinklers are running in the backyard, I cannot see it.

We have Rain Bird ESP-RZX sprinkler system.
We have total of 4 zones.
When I run zone 1, I can see sprinklers sprinklers in the front yard working. I cannot see anything in the backyard because of pavers.
When I run zones 2,3 and 4, I don't see anything in the front yard also anything in the backyard because of pavers.

Here are all the pics, that I know of, that are related to sprinklers:

I have this fear that zone 1 is also activating sprinklers in the backyard and it will cause issues with foundation.
How can I be sure that zone 1 is also not activating sprinklers in the backyard?
To further clarify my statement "I cannot see anything in the backyard because of pavers.", here is the photo of my backyard:

This is what the wiring of the Rain Bird looks like:

For people asking, if it is capped off why worry? I have this fear that maybe one of the sprinklers is not closed properly and it is leaking below the pavers and I can't see.
Comment: What do you mean "you can't see anything bc of pavers"?  that makes no sense.  How could you not see the sprinklers?   How many zone control valves do you have? Have you located them? DO you even have 4 zones? Best way to check is with nothing else using water in the house, one at a time, run each zone manually and see if the water meter shows flow or not.
Comment: If they are capped doesn't that mean no water will come out when they are on?
Comment: How many wires are attached to zones on the controller? Flip up the lower panel and see. Your two pictures only show one valve.
Comment: I'd agree that running zones 2-4 and checking the water meter to see if it's indicating water flow is great. Unfortunately, that will _not_ tell you if you're pumping water out through a broken pipe or missed sprinkler head on zone 1 _if_ zone 1 also covers the back yard as you are concerned. The only way to test that would be to cap all the sprinklers in the front yard, turn on zone 1 and check the meter to see if water is flowing. (Make sure nobody is doing dishes, taking a shower, using the bathroom, etc. while testing this.)
Comment: An interesting wiring mess... Looks like green (zone 2) is note connected to anything, red (zone) 1 and white (common) are connected to that one valve. I predict no water flow if #2 is "on" according to the controller. Nice of them to run a spare if you wanted to add a separate zone though.
Comment: @GeorgeAnderson
This is what my backyard looks like: https://imgur.com/a/Oo2ueNc
Sprinklers in the backyard are underneath those pavers and capped.

But you gave a good clue of checking water meter, will do that. Thanks!
Comment: @JonCuster Added pic to my question.I hope it is the one you are asking for.
Comment: @user253751 That is true but I have this fear that one of the sprinklers may not be closed properly and it is leaking and I can't see.
Comment: @FreeMan You seem to understand my question completely also your suggestion of closing sprinklers in the front yard and checking the meter reading makes sense to me.
I guess there is no other easy way than looking at the meter reading.
Thanks for your time in looking into my question.
Comment: @javanoob - there are wires to control 2 zones, the red and the green. In the top picture it looks like red is connected to that valve - where does green go? Is there a second zone? You only need to try running zones 1 and 2 to look for flow - the others are not connected.
Comment: @JonCuster I just took another photo and I guess this shows where green wire is going. https://imgur.com/a/WpXBChA
Comment: @JonCuster Here is a better picture: https://i.imgur.com/HF0QjrO.jpeg
Answer: I'd suggest running zones 2-4 and checking the water meter to see if it's indicating water flow.
Unfortunately, that will not tell you if you're pumping water out through a broken pipe or missed sprinkler head on zone 1 if zone 1 also covers the back yard as you are concerned. The only way to test that would be to cap all the sprinklers in the front yard, turn on zone 1 and check the meter to see if water is flowing. (Make sure nobody is doing dishes, taking a shower, using the bathroom, etc. while testing this.)
It probably won't be much fun, and it'll probably take time and cost you to cap off all the sprinkler heads then reinstall them when you're done testing. But, if you're that paranoid about there being issues under the patio in the back, it's the only realistic way of testing it out.
Comment: Thank you again sir for your time.


Need some assistance with my Unit Test using Moq regarding await emailClient.SendAsync

Question: I am really battling with creating an Unit Moq test for my email function and was wondering if anyone could help me. I think I have most of it right but still something is broken. Thanks in advance
Below is the actual implementation code:
public async Task Email(string htmlContent, string? connectionString, string? subject, string? sender, string? recipient)
        {
            try
            {
                // Encode HTML content to Base-64
                string base64Content = EncodeToBase64(htmlContent);

                Console.WriteLine("Sending email...");

                // Assuming emailClient is an instance of some EmailClient class
                var emailClient = new EmailClient(connectionString); // replace EmailClient with the actual type
                var emailSendOperation = await emailClient.SendAsync(
                    Azure.WaitUntil.Completed,
                    sender,
                    recipient,
                    subject,
                    base64Content);
            }
            catch (Exception ex)
            {
                throw ex;
                //SvrErrorMsg = $"An error occurred: {ex.Message}";
                // Log the exception or take appropriate action
            }
        }

Below is the unit test I have written so far but I am getting a compile error stating :
'ISetup<EmailClient, Task>' does not contain a definition for 'ReturnsAsync' and the best extension method overload 'SequenceExtensions.ReturnsAsync(ISetupSequentialResult<Task>, EmailSendOperation)' requires a receiver of type 'Moq.Language.ISetupSequentialResult<System.Threading.Tasks.Task<NUnit_TestProject.EmailSendOperation>>'
this is on the following lines:
EmailClientClientMock.Setup(x => x.SendAsync(WaitUntil.Completed, It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>(), null, CancellationToken.None))
                    .ReturnsAsync(emailSendOperationMock.Object);

Below is the test I have written so far:
        [Test]
        public async Task Email_SendEmailSuccessfully()
        {
            // Arrange
            var configurationMock = new Mock<IConfiguration>();
            configurationMock.Setup(x => x["CommunicationServiceConnectionString"]).Returns("YourConnectionString");
            configurationMock.Setup(x => x["EmailSettings:Subject"]).Returns("YourSubject");
            configurationMock.Setup(x => x["EmailSettings:Sender"]).Returns("YourSender");
            configurationMock.Setup(x => x["EmailSettings:Recipient"]).Returns("YourRecipient");

            var loggerMock = new Mock<ILogger>();

            // Mocking the SecretClient for testing purposes
            var EmailClientClientMock = new Mock<EmailClient>();
            var emailSendOperationMock = new Mock<EmailSendOperation>();

            var _EmailSendOperation = new EmailSendOperation();

            //ERROR:
            //error CS1929: 'ISetup<EmailClient, Task<EmailSendOperation>>' does not contain a definition for 'ReturnsAsync' and the best extension method overload 'SequenceExtensions.ReturnsAsync<EmailSendOperation>(ISetupSequentialResult<Task<EmailSendOperation>>, EmailSendOperation)'
            //requires a receiver of type 'Moq.Language.ISetupSequentialResult<System.Threading.Tasks.Task<NUnit_TestProject.EmailSendOperation>>'
            EmailClientClientMock.Setup(x => x.SendAsync(WaitUntil.Completed, It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>(), null, CancellationToken.None))
                .ReturnsAsync(emailSendOperationMock.Object);
            //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

            var myHelper = new Helper();

            await myHelper.SendEmail(configurationMock.Object, "YourHtmlContent", "YourKeyVaultUrl", loggerMock.Object);

Answer: SendAsync method in your EmailClient class returns a Task. But, in your test setup, you're trying to return a Mock. below changes should fix this.
EmailSendOperation emailSendOperation = new EmailSendOperation(); // Or however you instantiate this

// If you need to mock EmailSendOperation
// var emailSendOperationMock = new Mock<EmailSendOperation>();
// Use emailSendOperationMock.Object in the Task.FromResult

EmailClientClientMock.Setup(x => x.SendAsync(
    WaitUntil.Completed,
    It.IsAny<string>(),
    It.IsAny<string>(),
    It.IsAny<string>(),
    It.IsAny<string>())
).ReturnsAsync(Task.FromResult(emailSendOperation)); // or emailSendOperationMock.Object if you're mocking


REGEX for spaces between alpha numeric string

Question: Can you help me build a regex which will match any one of below patterns:

N0007120DJKAWE (9 to 14 char of alphanumeric)
N  0007120DJKAWE (1st position is a alphanumeric, 2nd and 3rd position can be space, next it can 8 to 13 alphanumeric)
N0007120D  KAWE (10 alphanumeric, 10th and 11th position can be space, next it can 1 to 4 alphanumeric)

I've tried:

(\b(?=[\dA-Za-z]*\d)(?=[\dA-Za-z]*[A-Za-z])[\dA-Za-z]{9,14}\b)

(\b[\dA-Z]{1}[\s]{1,2}[\dA-Z]{8,13}\b)

((?=[\dA-Za-z]*\d)(?=[\dA-Za-z]*[A-Za-z])[\dA-Z]{10}[\s]{1,2}[\dA-Z]{1,4})

How can we create a single regex for all patterns
Comment: Is there a reason you only accept white space in certain positions? Does it have significance? Why not remove all white space and check `/^[a-z0-9]{9,14}$/i` ? Are you trying to validate input or extracting patters from a larger text? Please provide more context about what you are trying to achieve here.
Comment: Why not just `or` your 3 expressions with `|`?
Comment: What about characters from 1st to 8th? Can they be any or letters or digits or alphanumeric?
Comment: Note that your third example would have its first word match with the first rule. So how would you decide that the extra spacing and 4 letters would also need to be included?
Comment: Try `^(?:[\dA-Za-z]{9,14}|[\dA-Za-z] {1,2}[\dA-Za-z]{8,13}|[\dA-Za-z]{9} {1,2}[\dA-Za-z]{1,4})$`, see [demo](https://regex101.com/r/qT53lS/1).
Answer: Based on your requirements alone above, the following worked for me:
^[a-zA-Z0-9]{9,14}$|^[a-zA-Z0-9] {1,2}[a-zA-Z0-9]{8,13}$|^[a-zA-Z0-9]{10} {1,2}[a-zA-Z0-9]{1,4}$

Here is the explanation:

^: Match the beginning of the string
$: Match the end of the string
[a-zA-Z0-9]{9,14}: Match any alphanumeric characters between 9 and 14 times, inclusive (NOTE: [a-zA-Z] only matches characters, and \w also matches _)
space{1,2}: Match 1 or 2 space characters

NOTE: Definitely check out regex101.com
Comment: This would match a string with *two* space gaps also. Not sure if the OP wants that to happen...
Comment: Note that `\w` also matches `_`.
Answer: This seems to work :

/\^w{9,14}$|^\w\s{0,2}\w{8,13}$|^\w{9}\s{0,2}\w{1,4}$/


$L/K$ being formally smooth implies $L/K$ is separable?

Question: If $L/K$ is a finite separable fields extension, then it is formally smooth, i.e., for every commutative diagram

where $B$ is a ring and $I\subseteq B$ is an ideal satisying $I^{2}=0$ there exists a lifting $\lambda\colon L\to B$ making the diagram commute.
I need to prove the converse. If $L/K$ is finite and not separable, then it is not formally smooth.
This is how one could proceed. If $K$ has characteristic $p$ and $a\in L$ is not a $p$-th power in $K$ then suppose that $K(\sqrt[p]{a})$ is formally smooth over $K$.
Then
$$K(\sqrt[p]{a})\otimes_{K} K(\sqrt[p]{a})\cong \frac{K(\sqrt[p]{a})[x]}{(x^{p}-a)}\cong\frac{K(\sqrt[p]{a})[x]}{(x-\sqrt[p]{a})^{p}}$$
should be formally smooth because https://stacks.math.columbia.edu/tag/00TJ but I want to prove that this is a contradiction because, in reality, $\frac{K(\sqrt[p]{a})[x]}{(x-\sqrt[p]{a})^{p}}$ is not formally smooth. But I am unable to prove this.
To conclude the proof, one could demonstrate that if $L/K$ were formally smooth, then by considering $K_{0}$ such that $K\subseteq K_{0}\subseteq L$ and $L=K_{0}(\sqrt[p^{r_{1}}]{a_{1}},\dots,\sqrt[p^{r_{m}}]{a_{m}})$ we get a formally smooth subextension $K_{0}(\sqrt[p](a_{1}))/K_{0}$, so a contradiction. This is another point that I am unable to prove. Is it true that given $K\subseteq F \subseteq L$, if $L/K$ is formally smooth, then both $L/F$ and $F/K$ are also formally smooth?
Comment: Is $L/K$ assumed to be finite, or algebraic? (Please add the answer to the question.)
Comment: It is assumed finited, I forgot this.
Comment: Hint: If the extension defines a smooth morphism, then it is etale and hence separable. So, it suffices to prove smoothness. But Spec L -> Spec K is finitely presented and formally smooth, hence smooth (see Stacks Project). So you could also look at the proof of   "locally finitely presented formally smooth implies smooth"
Answer: You want the following statement: Let $K$ be a characteristic $p$ field. Then $K[x]/x^p$ is not formally smooth over $K$.
Let $B=K[\epsilon]/\epsilon^{p+1}$ and $B/I=K[\epsilon]/\epsilon^{p}$. Let $K\to B$ be the obvious map, and let $K[x]/x^p\to B/I$ send $x$ to $\epsilon$. Then there is no lift $K[x]/x^p\to B=K[\epsilon]/\epsilon^{p+1}$, since $\alpha^p=0$ in $B$ implies $\alpha\in\epsilon^2B$.


Use delegate method written in Objective-C in Swift code

Question: I'd like to use a delegate method written in Objective-C in Swift. The method is included in the MGSwipeTableCell framework (MGSwipeTableCell.h).
Objective-C:
-(BOOL) swipeTableCell:(MGSwipeTableCell*) cell tappedButtonAtIndex:(NSInteger) index direction:(MGSwipeDirection)direction fromExpansion:(BOOL) fromExpansion;

I try to convert it into Swift to and use the method:
func swipeTableCell(cell:MGSwipeTableCell, index:Int,  direction:MGSwipeDirection, fromExpansion:Bool) -> Bool {

    return true
}

But I don't know why but the function isn't getting called. Did I something wrong? I just want to get the indexPath of the swiped cell with this function.
Answer: You should implement MGSwipeTableCellDelegate protocol in your table view controller first. So you can just write:
class TableViewController : UITableViewController, MGSwipeTableCellDelegate {
    ....
    ....
    ....
    func swipeTableCell(cell:MGSwipeTableCell, index:Int,  direction:MGSwipeDirection, fromExpansion:Bool) -> Bool {
        return true
    }
}

and then when creating cells in cellForRowAtIndexPath: method you should create it like this:
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
  {
    let reuseIdentifier = "cell"
    var cell = self.table.dequeueReusableCellWithIdentifier(reuseIdentifier) as! MGSwipeTableCell!
    if cell == nil {
      cell = MGSwipeTableCell(style: UITableViewCellStyle.Subtitle, reuseIdentifier: reuseIdentifier)
    }
    cell.delegate = self
    return cell
}

Then you'll be able to track when swipe method is called because you set the cell delegate property.
Comment: Thanks for your answer! It works. But now I set a detailTextLabel with this gesture/swipeTableCell function. Don't know why but it's not displayed in the cell. I think that it has something to do with the subclass of the tableView (MGSwipeTableCell). Hope you can help me.
Comment: I think you should probably change style of the cell when you're creating it in `cellForRowAtIndexPath:`. Current style is set to `.Subtitle`, it should be `.Default`.
Answer: It appears that the library you're trying to use has not adopted Objective-C nullability annotations yet, as such, any return values or arguments which are objects will be translated into Swift as implicitly unwrapped optionals (with the exclamation mark).
So, the signature you're looking for is this:
func swipeTableCell(cell: MGSwipeTableCell!, tappedButtonAtIndex: Int, direction: MGSwipeDirection, fromExpansion: Bool) -> Bool

But with that said, you need to add the protocol conformance anyway.  If you do that first then try to write this method out, it should autocomplete to exactly how Swift expects it to look.
And then just make sure you're actually setting the cell's delegate property to whatever object is implement this method.
Comment: Thanks for your answer! It works. But now I set a detailTextLabel with this gesture/swipeTableCell function. Don't know why but it's not displayed in the cell. I think that it has something to do with the subclass of the tableView (MGSwipeTableCell). Hope you can help me.


Selenium scrapes only the first item that it finds

Question: I use the following block of code to scrape a website
driver = webdriver.Chrome(executable_path=r'C:/Users/USER/Downloads/chromedriver_win32/chromedriver.exe')
url = 'https://mamikos.com/cari/ugm/all/bulanan/0-15000000'
driver.get(url)

kamar = driver.find_elements_by_class_name('kost-rc__content')

for desc in kamar :
    nama = desc.find_element_by_xpath('//*[@id="app"]/div/div[5]/div/div[1]/div/div/div[1]/div[1]/div[1]/div/div[2]/div/div[2]/div[2]/div/span[1]').text
    kecamatan = desc.find_element_by_xpath('//*[@id="app"]/div/div[5]/div/div[1]/div/div/div[1]/div[1]/div[1]/div/div[2]/div/div[2]/div[2]/div/span[2]').text
    harga = desc.find_element_by_xpath('//*[@id="app"]/div/div[5]/div/div[1]/div/div/div[1]/div[1]/div[1]/div/div[2]/div/div[2]/div[4]/div/div[2]/div/span[1]').text
    print(nama, kecamatan, harga)

After running it, the output only seems to print the first result of that page. I've tried to change the xpath to this
for desc in kamar :
    nama = desc.find_element_by_xpath('.//*[@id="app"]/div/div[5]/div/div[1]/div/div/div[1]/div[1]/div[1]/div/div[2]/div/div[2]/div[2]/div/span[1]').text
    kecamatan = desc.find_element_by_xpath('.//*[@id="app"]/div/div[5]/div/div[1]/div/div/div[1]/div[1]/div[1]/div/div[2]/div/div[2]/div[2]/div/span[2]').text
    harga = desc.find_element_by_xpath('.//*[@id="app"]/div/div[5]/div/div[1]/div/div/div[1]/div[1]/div[1]/div/div[2]/div/div[2]/div[4]/div/div[2]/div/span[1]').text
    print(nama, kecamatan, harga)

But it only gives out an error, please help.
Side note : google chrome Version 95.0.4638.69 (Official Build) (64-bit) and driver used was ChromeDriver 95.0.4638.69
Comment: You need to read about xpath and how to write it better.
Comment: but it only gives out an error - what error ?
Answer: To scrape the Name, Info and Price information you can use the Locator Strategies:
Code Block:
driver.get("https://mamikos.com/cari/ugm/all/bulanan/0-15000000")
names = [my_elem.text for my_elem in WebDriverWait(driver, 20).until(EC.visibility_of_all_elements_located((By.XPATH, "//div[@class='kost-rc__info']//span[contains(@class, 'rc-info__name')]")))]
infos = [my_elem.text for my_elem in WebDriverWait(driver, 20).until(EC.visibility_of_all_elements_located((By.XPATH, "//div[@class='kost-rc__info']//span[contains(@class, 'rc-info__location')]")))]
prices = [my_elem.text for my_elem in WebDriverWait(driver, 20).until(EC.visibility_of_all_elements_located((By.XPATH, "//div[@class='rc-price__real']//span[contains(@class, 'rc-price__text')]")))]
for i,j,k in zip(names, infos, prices):
    print(f"Name:{i} Title:{j} Price:{k}")
driver.quit()

Console Output:
Name:Kost Singgahsini Sakura Karanggayam Sleman Yogyakarta Title:Kecamatan Depok Price:Rp1.370.000
Name:Kost Singgahsini Granada UGM Yogyakarta Title:Kecamatan Depok Price:Rp1.790.000
Name:Kost Kurnia Terban Tipe A UGM Yogyakarta RMZ Title:Kecamatan Gondokusuman Price:Rp606.000
Name:Kost Singgahsini Maleo UGM Kaliurang Yogyakarta Title:Kecamatan Depok Price:Rp1.973.000
Name:Kost AB-AE Tipe B Gejayan Yogyakarta RMZ Title:Depok Price:Rp1.710.000
Name:Kost AB-AE Tipe A Gejayan Yogyakarta RMZ Title:Depok Price:Rp1.425.000
Name:Kost Pogung Familia Tipe C Sleman Yogyakarta RMZ Title:Mlati Price:Rp1.900.000
Name:Kost Pogung Familia Tipe B Sleman Yogyakarta RMZ Title:Mlati Price:Rp1.710.000
Name:Kost Pogung Familia Tipe A Sleman Yogyakarta RMZ Title:Mlati Price:Rp1.425.000
Name:Kost Hanung Tipe B UGM Yogyakarta RMZ Title:Mlati Price:Rp736.000
Name:Kost Apik Tapak Dara Tipe B Deresan Yogyakarta Title:Depok Price:Rp1.620.000
Name:Kost Singgahsini Putri Maoni Tipe A Gejayan Yogyakarta Title:Depok Price:Rp1.520.000
Name:Kost Singgahsini Omah Khiar Tipe F Karang Gayam Yogyakarta Title:Depok Price:Rp1.720.000
Name:Kost Apik Tapak Dara Tipe C Deresan Yogyakarta Title:Kecamatan Depok Price:Rp2.205.000
Name:Kost Singgahsini Putri Maoni Tipe B Gejayan Yogyakarta Title:Depok Price:Rp1.720.000
Name:Kost Wisma Yudhistira Tipe C Mlati Sleman Yogyakarta Title:Mlati Price:Rp2.250.000
Name:Kost Pondok Bugenvil 3 Caturtunggal Depok Sleman Title:Depok Price:Rp1.800.000
Name:Kost Pranasmara 34C Tipe B Depok Sleman Title:Depok Price:Rp1.200.000
Name:Kost Pondok Bugenvil 2 Caturtunggal Depok Sleman Yogyakarta Title:Depok Price:Rp1.800.000
Name:Kost Rahayu Residence Tipe C Depok Sleman Yogyakarta Title:Depok Price:Rp1.150.000

Comment: Hi, thanks for the code, helped me a lot. Quick question, do you have any recommendations about where to start learning web scraping using selenium ? since I'm new to this and would like to know the basics before advancing any further with web scraping. Thank you in advance
Comment: The best way is to start with [Frequent 'selenium' Questions](https://stackoverflow.com/questions/tagged/selenium?tab=Frequent) within StackOverflow.
Answer: Here is the complete code in c# to solve your problem. You can adapt it to your language, especially the xpath part.
var els = driver.findElements(By.Xpath("//div[@class='kost-rc__content']"));

foreach(var el in els){
var nama = el.findElement(By.Xpath(".//span[@class='rc-info__name bg-c-text bg-c-text--title-4 ']"));
console.log("nama:"+nama.Text());

var kecamatan = el.findElement(By.Xpath(".//span[@class='rc-info__location bg-c-text bg-c-text--body-1 ']"));
console.log("kecamatan:"+kecamatan.Text());
}


How to pass a 1D array of 500 pointers to a function in C

Question: The programm is compiling ok but once the user inputs something to the array it crashes. Any help will be appreciated :)
#include <stdio.h>
#include <stdlib.h>

void Register(char *arr[],char arr2[]);
int main() {
    char *Username[500];
    char table1[20];
    Register(Username,table1);
    return 0;
}
void Register(char *Username[],char table1[]){
    int i;
    for(i = 0; i < 500; i++){
        scanf("%s",&table1);
        Username[i] = table1;
        printf("for i = %d username[%d] is %s\n\n",i,i,Username[i]);
    }
}

Comment: This is a 1d array of 500 pointers. Each of them will point to the same 1d array of 20 characters `Username[i] = table1`.
Comment: yup that i am new to c so i dont really knew how to explain it :)
Comment: regarding: `for(i = 0; i < 500; x1++){`  The third parameter is not correct.  The staement should be: `for( i = 0; i < 500; i++ ){`
Comment: OT: regarding the function name: `Register()`  The C language has the type modifier: `register`.  It is a poor programming practice to use names those only difference between a name in the C language is the capitalization
Comment: OT: regarding: `#include `  Nothing in this header file is being used by the posted code.   It is a poor programming practice to include header files those contents are not being used.  Suggest removing that statement.
Comment: regarding: `scanf("%s",&table1);`  1) This results in a warning from the compiler:  *untitled.c:14:17: warning: format '%s' expects argument of type 'char *', but argument 2 has type 'char **' [-Wformat=]*  2) when calling any of the `scanf()` family of functions, always check the returned value (not the parameter value) to assure the operation was successful.  Note: the returned value is a count of the number of successful 'input format conversion specifiers'.  In the current scenario any returned value other than 1 indicates an error occurred. (cont)
Comment: (cont)  3) when using the format specifiers `%s` and/or `%[...]` always include a max characters modifier that is 1 less than the length of the input buffer as those specifiers always append a NUL byte to the input.  This also avoids any possible buffer overflow and the resulting undefined behavior.
Answer: The problem is that when you pass your arrays they decay to pointers to their first element. For "array" arguments something like e.g. char table1[] is actually char *table1. And this is a problem when you try to use the address-of operator & in scanf.
When you use &table1 in the scanf call you get a pointer to the pointer, which has the type char **, not the expected char *. This mismatch between the format %s and the expected type leads to undefined behavior and probably your crash.
The solution to this crash is to never use the address-of operator for reading strings (with e.g. the %s format), as it's even wrong when you have an actual array:
scanf("%s",table1);

As for the problem of making all elements of Username point to the single string in table1, I recommend that you use arrays of arrays for Username instead:
char Username[500][20];

This array decays to a pointer to an array, with the type of char (*)[20], which needs to be part of the Register function declaration:
void Register(char (*Username)[20]);

Then you can use this directly in the call to scanf:
scanf("%19s", Username[i]);

Also note how I limited the length of the input string, so you can't read more than the arrays can handle (and it's 19 because the array need to fit the string null-terminator as well).
Comment: Thanks it worked just tried it thanks a lot :) , pointers are something that confuse me a lot need to work with them a bit more
Comment: Thanks a lot now the whole programm runs smoothly :)  also Is there a good website for people to reference that explains a lot of this stuff in more detail?
Comment: @NikosTypaldos _also Is there a good website for people to reference that explains a lot of this stuff in more detail?_   Yes, this one.  In the case of your question in particular, it has been asked many times, and answered properly almost as many times.
Answer: In this statement
scanf("%s",&table1);

instead of reading a string into the array pointed to by the pointer table1 the string is read into the pointer itself.
You have to write
scanf("%s",table1);

Also the function Register does not make great sense because all elements of the array Username will point to the first character of the array table1. That is all elements of the array will point to the first character of the last string that was read.
You need to allocate memory dynamically. Also the second parameter of the function is redundant.
The function cam look the following way
size_t Register( char *Username[], size_t n )
{
    char record[20];
    int i = 0;

    for ( ; i < n && scanf( "%19s", record ) == 1; i++ )
    {
        Username[i] = malloc( strlen( record ) + 1 );
        strcpy( Username[i], record );
        printf( "for i = %zu username[%zu] is %s\n\n", i, i, Username[i] );
    }

    return i;
}

And in main the function can be called like
size_t n = Register( Username, 500 );

\Of course you will need to free all allocated memory.
Comment: So the function register does not read strings and stores them into pointers for example like this https://i1.wp.com/overiq.com/wp-content/uploads/2018/11/memory-representation-of-array-of-pointers-1504599930139.png
Comment: @NikosTypaldos You need to allocate an arrya for each pointer pf the array.


Spring profile default behaviour

Question: I have a spring profile "DEV" and thats the only profile I have and I do NOT want to create a "production" profile. So only when profile is "DEV" I would like a certain type of bean for spring security is initiated (which is an in memory guest user and a userdetails bean)
But if no spring profile is provided in my tomcat startup, which is the case in production, I would like my app to continue what it is already doing(using ldap authenticatin provider).
Is there a way to define a "default" bean behaviour without actually needing to provide a profile at start up? Or you can look at my code below and suggest a different solution maybe.
@Autowired
public void configureGlobal(final AuthenticationManagerBuilder auth, final AuthenticationProvider provider) throws Exception {

        auth
                .eraseCredentials(false)
                .authenticationProvider(provider)
                .authenticationProvider(jwtConfig.jwtAuthenticationProvider());
}

@Bean
public UserDetailsService userDetailsService() {
    final LdapUserDetailsService ldapUserDetailsService = new LdapUserDetailsService(ldapUserSearch(), ldapAuthoritiesPopulator());
    return new CompositeUserDetailsService(Arrays.asList(technicalUserDetailsService(), ldapUserDetailsService));
}

@Bean
@Profile("DEV")
public UserDetailsService devUserDetailsService() {
 useAnonymous = true;
        InMemoryUserDetailsManagerBuilder b = new InMemoryUserDetailsManagerBuilder()
                .withUser("user").password("password").authorities(ROLE_USER, ROLE_ADMIN).and();

        return new CompositeUserDetailsService(Arrays.asList(b.build(),
                technicalUserDetailsService()));

}
@Bean
public AuthenticationProvider ldapAuthenticationProvider() {
    final BindAuthenticator ba = new BindAuthenticator((BaseLdapPathContextSource) contextSource());
    ba.setUserSearch(ldapUserSearch());
    return new LdapAuthenticationProvider(ba, ldapAuthoritiesPopulator());
}

Comment: Did you try it already?  If so, did something go wrong?
Comment: By just defining the bean and override it when the profile is active...W which is basically default behavior.
Answer: I think there is a misunderstanding of what @Profile does.  Beans marked with @Profile are only loaded when that profile is active, but all other beans (without a @Profile) are still always loaded, regardless of the chosen profile.
I see a few ways to solve this:
1) Mark all those beans with a @Profile("dev") also with @Primary so Spring knows which one to pick when two beans of the same type are loaded (since you donot want to use a production profile).
2) Mark the beans that should not be loaded when profile dev is active with @Profile("!dev") -- only applicable for Spring 3.2 and higher (see https://github.com/spring-projects/spring-framework/commit/bcd44f3798ed06c0704d2a3564b8a9735e747e87).
Or...
3) Use a production profile and simply activate it in for example the web.xml file (something which you probably don't use locally).
Simply create multiple @Configuration classes and mark the entire class with a profile (it also helps to keep related stuff together).  A typical example is for the database.  Create one configuration class for the production database (something with JNDI and Oracle) and one for local development and testing (HSQLDB).
You mark the JNDI Configuration class with @Profile("production") and the other with  @Profile("dev") -- no need to mark individual beans, just split them logically amongst two different @Configuration classes.
This worked really well for us, also when combined with integration testing.
Comment: tnx, your first solution seems to work fine for picking up the correct beans, but somehow i still cant login with my guest user. is there a way to use "auth.userDetailsService(userDetailsService())" when it is dev profile and  "auth.authenticationProvider(provider)" when NOT dev? which is configured in the first method in my example
Comment: It looks a bit incomplete to answer that... however, I think you should just make two `AuthenticationManager` beans, one with `dev` profile and one without (or with `!dev`).  In those two methods you can then build the bean differently according to the profile.
Comment: thanks. Btw Primary annotation didnt work for me and I used the "!DEV" syntax
Comment: The `!dev` solution is prefered anyway, I only suggested to try `@Primary` because you didn't want to use a production profile.
Answer: I would override the bean definition in this way:
@Autowired
public void configureGlobal(final AuthenticationManagerBuilder auth, final AuthenticationProvider provider) throws Exception {

        auth
                .eraseCredentials(false)
                .authenticationProvider(provider)
                .authenticationProvider(jwtConfig.jwtAuthenticationProvider());
}

@Bean("myUserDetailService")
public UserDetailsService userDetailsService() {
    final LdapUserDetailsService ldapUserDetailsService = new LdapUserDetailsService(ldapUserSearch(), ldapAuthoritiesPopulator());
    return new CompositeUserDetailsService(Arrays.asList(technicalUserDetailsService(), ldapUserDetailsService));
}

@Bean("myUserDetailService")
@Profile("DEV")
public UserDetailsService devUserDetailsService() {
 useAnonymous = true;
        InMemoryUserDetailsManagerBuilder b = new InMemoryUserDetailsManagerBuilder()
                .withUser("guest").password("guest").authorities(ROLE_USER, ROLE_ADMIN).and();

        return new CompositeUserDetailsService(Arrays.asList(b.build(),
                technicalUserDetailsService()));

}
@Bean("myAuthProvider")
public AuthenticationProvider ldapAuthenticationProvider() {
    final BindAuthenticator ba = new BindAuthenticator((BaseLdapPathContextSource) contextSource());
    ba.setUserSearch(ldapUserSearch());
    return new LdapAuthenticationProvider(ba, ldapAuthoritiesPopulator());
}

@Bean("myAuthProvider")
@Profile("DEV")
public AuthenticationProvider devAuthenticationProvider() {

   //find a way to return userdetails here

}

In this way when the "DEV" profile is started the beans defined in that profile should override the default beans
Sure when you autowire beans you should use the @Qualifier annotation
I hope it's useful
Angelo
Comment: Downvoted, because this does not work deterministically. If two `@Bean` definitions are provided with the same name, Spring only calls one of theses methods. And whichever bean is first call it might work or not. Seems to be dependent on the order within the class.

Spring profile default behaviour


Matrix inverse problem

Question: $M$ is a $m \times n$ matrix such that $I_{m}+MM^T$ is invertible, show that
$(I_{n}+M^TM)^{-1}=I_{n}-(I_{M}+MM^T)^{-1}M$.
I don't know how to prove this question
$$(I_{m}+MM^T)(I_{m}+MM^T)^{-1}=I_{m}$$
$$(MM^T)^{-1}(I_{m}+MM^T)(I_{m}+MM^T)^{-1}M=(M^{T})^{-1}$$
$$M^{-1}(I_{m}+MM^T)(I_{m}+MM^T)^{-1}M=I_{n}$$
When I reached this point I stopped as I don't know how to continue.
Can any one help me?
Comment: I fixed some of the formatting problems, but would you mind explaning what the "s.t $I_m +MM^T$" means?
Comment: You can refer this for better formatting  and edit accordingly so that you can better help from other users -http://meta.math.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference
Answer: I suspect there is an error in your expression in the RHS.
However, such kind of expressions are generally derived using the Morrison-Woodbury formula, which is (quoted from Wikipedia)
$$(A + UCV)^{-1} = A^{-1} - A^{-1}U(C^{-1}+ VA^{-1}U)^{-1}VA^{-1},$$ provided $C^{-1}+ VA^{-1}U$ is invertible.
Set $A= I_n$, $U = M^T$, $V = M$, and $C = I_m$. Given that $I_m + MM^T$ is invertible, you get
$$(I_n + M^TM)^{-1} = I_n - M^T(I_m + MM^T)^{-1}M,$$
which is exactly same as your expression except an additional $M^T$ in the RHS.

Matrix inverse problem


I have several python versions installed and I want to remove the packages installed under them

Question: Using pip I am only able to uninstall for a few versions. I am fairly new to this, so please let me know if there is some way of deleting it. I am currently using Ubuntu 20.04. I had previously installed the packages with pip itself. But now pip no longer points to those versions. I tried commands like
pip3.6 uninstall package
python3.6 -m pip uninstall package
but none of that is even being recognised as a command.
I do not wish to uninstall the python installation itself, just the various packages that I installed by myself when using those various versions.
I have installed python3.6 version as I can see it under my /usr and home directory, however when I run this python3.6 -m pip -V or python3.6 -m pip list I get the following output
Command 'python3.6' not found, did you mean:

  command 'python3.9' from deb python3.9 (3.9.0-5~20.04)
  command 'python3.8' from deb python3.8 (3.8.5-1~20.04.2)

Try: sudo apt install <deb name>

Comment: It's `pip uninstall package` and `pip3 uninstall package` not `pip3.6 uninstall package` [this](https://askubuntu.com/questions/1226559/does-python-on-ubuntu-come-with-any-libraries) is also related .
Comment: I have tried that too, but pip3 points to my python 3.8 installation
Comment: You'd be crazy uninstalling anything beginning with "P" and ending in "ython".
Comment: What does `python3.6 -m pip -V` and `python3.6 -m pip list` return? Please [edit] your question to add the output.
Comment: @Raffa, I have edited the question.
Comment: `python3.6` is not present on your system or not configured / linked correctly. You appear to have `python3.8` and `python3.9`. Given this information, I suggest you leave the installed python packages and read [this](https://askubuntu.com/a/1321433)
Answer: Do not - ever - remove a python version if you did not install it yourself. Ubuntu has tons of scripts running in python - therefore it needs a defined python environment. There are a lot of "I've removed python now I have a problem" questions in this forum - due to a removal of the "official" python environment.
You always can install additional versions via pip and remove them. And you can set those as default version
Edit
Just of today python V3.8.5 is the current "offical" version of Ubuntu 20.04
Comment: Yes, I do not intend to remove the python installation just some packages that I installed on my own when I was using that version of python such as TensorFlow which is eating up a lot of space.
Comment: As I understand it .... The OP does not want to uninstall any python version. They want to remove packages they previously manually installed **pip** and no longer need. **+1**


Casting from a ListModel into a DefaultListModel in Java 7

Question: How can I cast a ListModel to a DefaultListModel??!  I perform  the following and I get this error message,
DefaultListModel portalListModel = (DefaultListModel) portalList.getModel();

C:\Documents and Settings\...\myfile.java:728: warning: [rawtypes] found raw type: DefaultListModel
    DefaultListModel portalListModel = (DefaultListModel) portalList.getModel();
missing type arguments for generic class DefaultListModel<E>
where E is a type-variable:
E extends Object declared in class DefaultListModel

I tried the following,
DefaultListModel<E> portalListModel = (DefaultListModel) portalList.getModel();

I have a feeling tha this is a stupid question but I'm totally confued with this new generic thing!  Please help me out!
Comment: What type of data (which class) is in your list model?
Comment: If you do not know the exact type argument, you can use the `?`. Try `DefaultListModel portalListModel = (DefaultListModel) portalList.getModel();`
Answer: The way that Java's Collections work is that you can use Collection-type objects to store a whole bunch of Objects.  Prior to the introduction of Generics, you could store any object in a Collection, and then you had to perform a cast when you wanted to get those Objects out of your collection.
List myList = new ArrayList();
myList.add("string");
myList.add(new MyValueClass(42, "identifying string"));

That's perfectly acceptable code.  If you wanted to iterate over the objects, you could do it like so:
Iterator it = myList.iterator();
while (it.hasNext()) {
    String str = (String) it.next();  // NOTE: This will work the first time, but throw a ClassCastException when it gets to the second item.
}

With Java 1.5, Generics provides compile-time type checking upon insertion into the list.  So now, if you declare myList as a List<String>, the first block of code above will fail at compile time when you attempt to add an object of type MyValueClass to the List.
In Java 1.7, DefaultListModel is genericized.  So when you call portalList.getModel(), you're going to get back a DefaultListModel that contains a certain type of object (which is what the <E> is; it's a placeholder for the actual object type.)  In the above List<String> example, String is the substitution for E.
So if your portalList object's model member is a DefaultListModel that contains a bunch of MyValueClass objects, then your declaration should look like:
DefaultListModel<MyValueClass> portalListModel = portalList.getModel();

See the DefaultListModel API doc.
Comment: Sure.  So in my example (the first code block), we have a basic (pre-Java-1.5-style) `List` object called `myList` that contains two objects.  The first object in `myList` is of class `String`.  The second object in `myList` is of class `MyValueClass`.  Thus, when you iterate over the values in `myList` to pull them out, the code inside the iterator is specifically expecting `String` objects.  The first time through the loop, it'll work fine.  The second time, however, it will grab the `MyValueClass` object, try to cast it to `String`, and throw a `ClassCastException`.
Comment: Could someone please explain the //NOTE: in his answer?


turn on anti aliasing in d3d9?

Question: I'm trying to turn on anti aliasing in my project. first look the d3d9 interface:
HRESULT CreateRenderTarget(
  [in]           UINT Width,
  [in]           UINT Height,
  [in]           D3DFORMAT Format,
  [in]           D3DMULTISAMPLE_TYPE MultiSample,
  [in]           DWORD MultisampleQuality,
  [in]           BOOL Lockable,
  [out, retval]  IDirect3DSurface9 **ppSurface,
  [in]           HANDLE *pSharedHandle
);

typedef enum D3DMULTISAMPLE_TYPE {
  D3DMULTISAMPLE_NONE           = 0,
  D3DMULTISAMPLE_NONMASKABLE    = 1,
  D3DMULTISAMPLE_2_SAMPLES      = 2,
  D3DMULTISAMPLE_3_SAMPLES      = 3,
  D3DMULTISAMPLE_4_SAMPLES      = 4,
  D3DMULTISAMPLE_5_SAMPLES      = 5,
  D3DMULTISAMPLE_6_SAMPLES      = 6,
  D3DMULTISAMPLE_7_SAMPLES      = 7,
  D3DMULTISAMPLE_8_SAMPLES      = 8,
  D3DMULTISAMPLE_9_SAMPLES      = 9,
  D3DMULTISAMPLE_10_SAMPLES     = 10,
  D3DMULTISAMPLE_11_SAMPLES     = 11,
  D3DMULTISAMPLE_12_SAMPLES     = 12,
  D3DMULTISAMPLE_13_SAMPLES     = 13,
  D3DMULTISAMPLE_14_SAMPLES     = 14,
  D3DMULTISAMPLE_15_SAMPLES     = 15,
  D3DMULTISAMPLE_16_SAMPLES     = 16,
  D3DMULTISAMPLE_FORCE_DWORD    = 0xffffffff
} D3DMULTISAMPLE_TYPE, *LPD3DMULTISAMPLE_TYPE;

I am not sure how to give the parameter MultiSample and MultisampleQuality. what is the difference between non-maskable multisampling and maskable? What does 2x anti-aliasing map to? what does 4x anti-aliasing map to? does D3DMULTISAMPLE_2_SAMPLES + 2q == D3DMULTISAMPLE_4_SAMPLES + 1q?
Answer: MultisampleQuality is only available if you take D3DMULTISAMPLE_NONMASKABLE as multisampletype (doc).
D3DMULTISAMPLE_NONMASKABLE enables only antialiasing-support (thats what you look for) and the quality is determined by the MultisampleQuality-Parameter, where 1 => 2xAA and 2 => 4xAA.
If you use a type other then D3DMULTISAMPLE_NONMASKABLE, e.g. 'D3DMULTISAMPLE_2_SAMPLES' you enable additionaly to the antialising-support a writing mask, which you can set by the renderstate D3DRS_MULTISAMPLEMASK (doc). This enables you to render to a specific set of samples of your multisampled rendertarget. Finally all samples are averaged and presented. I assume that this setting isn't the right for your problem.

turn on anti aliasing in d3d9?


How can I indicate when a shower is in use?

Question: Just bought my first home which has two bathrooms. We have guests stay over fairly often (family, friends etc) and on more than one occasion someone's shower has been ruined because either someone downstairs runs the hot tap (washing dishes etc) or someone else switches on the other shower, which makes both run cold.
Is there some cheap way of rigging up a switch (RF, I guess) which someone could press when about to get into the shower, which would light up a corresponding switch/light in the other bathroom (and/or in the kitchen to warn us not to run the taps)?
Or indeed, any better solutions to this problem (other than asking our guests to tell us/each other when they're using the water, which hasn't worked so far...)?
Comment: What size water heater? Have you seen this: https://diy.stackexchange.com/questions/24627/why-does-the-shower-get-cold-when-i-flush-and-how-can-i-prevent-it
Comment: I'd spend money fixing the real issue, not buying a band-aid.  Have you ever actually seen such an indicator system being used?  That's because you shouldn't need one....
Comment: Perhaps low volume shower heads. They provide good showers but use less water.
Comment: how much spare electrical service do you have?
Answer: This is the sort of thing that's trivial with new tech, and quite involved (expensive) without it.
It's easy with a few smart things. Assuming hot showers, a humidity sensor can trigger action. powering a dummy sensor with the exhaust fan circuit could trigger. or use a microphone sensor, or a PIR (motion detector) above the shower. Once the trigger's in the system, you can have any output you want, like a smart outlet or app notification. You can even setup "gates" around it like min/max trigger duration, debounce, etc, that would be god-awful to do in "analog".
The system can be a home-rolled node-red setup, or a commercial turn-key like SmartThings or HomeKit. The initial setup would be cheaper than fixing the problem, and then you could do lots of other neat things. If you don't have one already, it's the way to go, and if you do, then just add a new sensor and call it a day.


How to convert to int in python?

Question: my name is Jay and I'm new to python and coding!
How can I convert the results to integer?
# This function adds two numbers
def add(x, y):
    return x + y

# This function subtracts two numbers
def subtract(x, y):
    return x - y

# This function multiplies two numbers
def multiply(x, y):
    return x * y

# This function divides two numbers
def divide(x, y):
    return x / y```

How can I go on?

Comment: Note that `int(3.9)` gives `3`.  In other words, `int()` truncates the fractional part of a number.  Adding `0.5` to your number before converting will make the rounding behave more intuitively (but I think not always correct).
Comment: This is a duplicate and could easily be looked up in the documentation
Comment: You can use`int()`and put any number in it.
Comment: Does this answer your question? ["Cast" to int in Python 3.4](https://stackoverflow.com/questions/27244123/cast-to-int-in-python-3-4)
Comment: Does this answer your question? [Python float to int conversion](https://stackoverflow.com/questions/6569528/python-float-to-int-conversion)
Comment: Regarding division you would need to be careful since any quotient that is not equal to a integer would be rounded. (given that all input are integers and not floats... Otherwise Stevens comment above would need to be accounted in all cases.)
Comment: Use // for integer division
Answer: to convert to integer you must use int(x)
like this:
def my_function(x,y):
    return int(x / y)

How to convert to int in python?


Why combiner output records = 0?

Question: I have multipleinput, so I have two mappers. Also I have one combiner:
class JoinCombiner extends MapReduceBase implements
        Reducer<TextPair, Text, TextPair, Text> {

    @Override
    public void reduce(TextPair key, Iterator<Text> values,
            OutputCollector<TextPair, Text> output, Reporter reporter)
            throws IOException {

        Text nodeId = new Text(values.next());
        while (values.hasNext()) {
            Text node = values.next();
            TextPair outValue = new TextPair(nodeId.toString(), "0");
            output.collect(outValue , node);
        }
    }
}

When I use this class as Reducer - all words good. but if i  use it as combiner - I have this info in log:
Combine input records=6
Combine output records=0
Reduce input groups=0
Reduce shuffle bytes=30
Reduce input records=0
Reduce output records=0

So, no output from combiner -> no input for reduce. I cant understand why. Please make some explanation if you have ideas))
Thanks
Answer: A combiner gets executed only if you have a reducer. Try setting both the combiner and reducer to the same class(if it's possible) and also consider setting the number of reduce tasks.
UPDATE: You're trying to change the key in combiner. The purpose of the combiner is to group the values of the same key together locally to reduce the traffic.
From the Hadoop Tutorial on YDN

Instances of the Combiner class are run on every node that has run map tasks. The Combiner will receive as input all data emitted by the Mapper instances on a given node. The output from the Combiner is then sent to the Reducers, instead of the output from the Mappers.

Based on my experience, that is not totally true. Hadoop sends only the keys that are emitted by the mapper to the reducer - meaning  if you've a combiner in between it should emit the same key as that of the mapper reducing the number of values associated with the key. IMO, changing the keys in the combiner results in unexpected behavior. To make you understand a simple usecase of combiners, consider a word counter.
Mapper1 emits:
hi 1
hello 1
hi 1
hi 1
hello 1

Mapper2 emits:
hello 1
hi 1

You have seven output records. Now if you want to reduce the number of keys locally(meaning on the same machine where the mapper is runnning), then having a combiner will give you something like this:
Combiner1 emits:
hi 3
hello 2

Combiner2 emits:
hello 1
hi 1

Notice that combiner did not change the key. Now, at the reducer, you will get the values like this:
Reducer1: key: hi, values: <3, 1> and you emit hi 4
Because you've only one reducer, the same reducer will be called again by giving it a different key this time.
Reducer1: key: hello, values: <2, 1> and you emit hello 3
The final output would be as follows
hello 3
hi 4

The output is sorted on the basis of the keys emitted by the mapper. You can chose to change the key emitted by the reducer but your output will not be sorted by the key emitted by the reducer(by default). Hope that helps.
Comment: take a look please what I have. this is my configuration for job:
  conf.setCombinerClass(JoinCombiner.class);

  conf.setReducerClass(JoinCombiner.class);

  conf.setNumReduceTasks(1);

And what I have in log:
   Map input records=6
  Map output records=6
  Map output bytes=58
  Map output materialized bytes=30
  Input split bytes=1070
  Combine input records=6
  Combine output records=0
  Reduce input groups=0
  Reduce shuffle bytes=30
  Reduce input records=0
  Reduce output records=0
Comment: Looks like you're changing the key in the combiner. See my updated answer.
Comment: You can look for more interesting facts about combiner in this stackoverflow post: http://stackoverflow.com/questions/20212884/mapreduce-combiner

Why combiner output records = 0?


Install Solar Light + Panel to side of house that has Vinyl Siding?

Question: I bought a led solar motion activated light and I am wondering what is the best way to install it on a house that has vinyl siding.
I seen a few possible ways

Drill holes directly into the vinyl and then add vinyl siding mounting block.
Get vinyl siding hooks and try to mount it that way.

For the first way I am unclear if I need to found a stud to install it on to or if I can choose anywher? If I need to find a stud how do I do this? Will a stud finder be able to go through the vinly?
For the second way. I am not sure if these hooks will be able to hold the light I linked too and where I live it can get extremely windy (and in the winter time snows) so it would need to stand up to elements.
Any suggestions?
Comment: what is the wall behind the vinyl, is it wood or stucco.
Comment: I think it is stucco.
Comment: A stud finder will work just fine through vinyl siding. It may, however, be quite confounded by the solid plywood or OSB that should be acting as sheathing for the outside of your house. However, that 1/2" to 3/4" sheathing should do just fine to hold up the light, especially since it's only 2lbs (<1kg).
Answer: You will need 4 inch long wood screws.
Pre-drill through the vinyl and stucco but not further (about 1.5 inches deep.
When you screw in the 4 inch screws you will screw in the plywood boards (that are under your stucco)on your home.
That will hold almost anything.
Comment: Can you please expand to show how you come up with a 4" long screw? 1" for holding in the stud (deeper could hit electrical in an exterior wall), plus 1/2" for plywood sheathing. What is the other 2-1/2" for? Stucco can't be _that_ thick.
Comment: @FreeMan from lots of experience, 2-1/2 wont do it
Comment: Will I need to put a mounting block first?