text:
Q: Trustpilot web scraping, Empty output I am trying to scrap Trustpilot reviews using python. Since I'm new to web scraping, I used the below code snippet to do it. I ran the code from Google colab and it was completed without any error but the output dataframe is empty! I checked different companies' URLs in Trustpilot but it keeps returning an empty dataframe. Could anyone help me to find out what is wrong with my code or methodology for scrapping?
from bs4 import BeautifulSoup
import requests
import pandas as pd
import datetime as dt

# Initialize lists
review_titles = []
review_dates_original = []
review_dates = []
review_ratings = []
review_texts = []
page_number = []

# Set Trustpilot page numbers to scrape here
from_page = 1
to_page = 50

for i in range(from_page, to_page + 1):
    response = requests.get(f"https://uk.trustpilot.com/review/bupa.co.uk?page={i}")
    web_page = response.text
    soup = BeautifulSoup(web_page, "html.parser")

    for review in soup.find_all(class_ = "paper_paper__1PY90 paper_square__lJX8a card_card__lQWDv card_noPadding__D8PcU styles_cardWrapper__LcCPA styles_show__HUXRb styles_reviewCard__9HxJJ"):
        # Review titles
        review_title = review.find(class_ = "typography_typography__QgicV typography_h4__E971J typography_color-black__5LYEn typography_weight-regular__TWEnf typography_fontstyle-normal__kHyN3 styles_reviewTitle__04VGJ")
        review_titles.append(review_title.getText())

        # Review dates
        review_date_original = review.select_one(selector="time")
        review_dates_original.append(review_date_original.getText())

        # Convert review date texts into Python datetime objects
        review_date = review.select_one(selector="time").getText().replace("Updated ", "")
        if "hours ago" in review_date.lower() or "hour ago" in review_date.lower():
            review_date = dt.datetime.now().date()
        elif "a day ago" in review_date.lower():
            review_date = dt.datetime.now().date() - dt.timedelta(days=1)
        elif "days ago" in review_date.lower():
            review_date = dt.datetime.now().date() - dt.timedelta(days=int(review_date[0]))
        else:
            review_date = dt.datetime.strptime(review_date, "%b %d, %Y").date()
        review_dates.append(review_date)

        # Review ratings
        review_rating = review.find(class_ = "star-rating_starRating__4rrcf star-rating_medium__iN6Ty").findChild()
        review_ratings.append(review_rating["alt"])

        # When there is no review text, append "" instead of skipping so that data remains in sequence with other review data e.g. review_title
        review_text = review.find(class_ = "typography_typography__QgicV typography_body__9UBeQ typography_color-black__5LYEn typography_weight-regular__TWEnf typography_fontstyle-normal__kHyN3")
        if review_text == None:
            review_texts.append("")
        else:
            review_texts.append(review_text.getText())

        # Trustpilot page number
        page_number.append(i)

# Create final dataframe from lists
df_reviews = pd.DataFrame(list(zip(review_titles, review_dates_original, review_dates, review_ratings, review_texts, page_number)),
                columns =['review_title', 'review_date_original', 'review_date', 'review_rating', 'review_text', 'page_number'])

A: That information is being fed into page from an API, via javascript XHR calls [those XHR calls are being made by Javascript after the initial page' HTML is loaded, so Requests cannot see the data, as it cannot execute Javascript]. You need to scrape that API endpoint (and you can find it in Dev tools - Network tab). Here is one way to do it:
import requests
import pandas as pd
from tqdm import tqdm ## if using Jupyter notebook, import as: from tqdm.notebook import tqdm

s = requests.Session()
big_df = pd.DataFrame()

pd.set_option('display.max_columns', None)
pd.set_option('display.max_colwidth', None)

for x in tqdm(range(2, 5)):
    r = s.get(f'https://uk.trustpilot.com/_next/data/businessunitprofile-consumersite-5670/review/bupa.co.uk.json?page={x}&businessUnit=bupa.co.uk')
    df = pd.json_normalize(r.json()['pageProps']['reviews'])
    big_df = pd.concat([big_df, df], axis=0, ignore_index=True)
print(big_df)

Result in terminal:
100%
1/1 [00:01<00:00, 1.21s/it]
id  filtered    pending text    rating  title   likes   report  hasUnhandledReports consumersReviewCountOnSameDomain    consumersReviewCountOnSameLocation  productReviews  language    location    labels.merged   labels.verification.isVerified  labels.verification.createdDateTime labels.verification.reviewSourceName    labels.verification.verificationSource  labels.verification.verificationLevel   dates.experiencedDate   dates.publishedDate dates.updatedDate   consumer.id consumer.displayName    consumer.imageUrl   consumer.numberOfReviews    consumer.countryCode    consumer.hasImage   consumer.isVerified reply.message   reply.publishedDate reply.updatedDate
0   633340161133a76521b9a54a    False   False   Having just received a breast cancer diagnosis from a routine mammogram. I was unfortunately let down by the NHS.dropped me out of the system.\nFortunately, I have had medical insurance with BUPA.for the past 48 yrs.So I contacted them & they were very instrumental in getting me the treatment I needed very quickly.    5   Let down by NHS.    1   None    False   1   None    []  en  None    None    True    2022-09-27T20:25:26.000Z    BusinessGeneratedLink   invitation  invited 2021-10-07T00:00:00.000Z    2022-09-27T20:25:26.000Z    None    573c3c860000ff000a212594    Hilary Davies       7   GB  False   False   Hi Hilary, thank you for sharing your experience. Wishing you all the very best. Amy    2022-09-28T08:50:31.797Z    None
1   6333f9061c24523f3ca038d2    False   False   I used the dental care plan and was so pleased with how quick and easy it was to put a claim through. After sending my receipt which included breakdown of dental work I received I received the funds straight into my nominated bank account within 10 days. No fuss or multiple emails/calls required. Super service!    5   Dental Care plan- super easy claim process  0   None    False   1   None    []  en  None    None    True    2022-09-28T09:34:30.000Z    BusinessGeneratedLink   invitation  invited 2022-09-14T00:00:00.000Z    2022-09-28T09:34:30.000Z    None    5e9b08555efa59374f58b372    Jessica     4   GB  False   False   Great, thanks for sharing your experience Jessica. Amy  2022-09-28T09:42:50.036Z    None
2   633322a61133a76521b983b9    False   False   Bupa left a text on my phone that they needed to speak to me about a medical issue. They had given me an authority number. \n\nI have tried six times to get through. No name was left. I couldn't find a human being to talk to. This is weeks ago. No one has tried again. The message was left on date below 1   Bupa deals with insurance and takes money every month. It shouldn't be so difficult dealing with them when it comes to paying for a medical issue.  0   None    False   1   None    []  en  None    None    True    2022-09-27T18:19:50.000Z    BusinessGeneratedLink   invitation  invited 2022-09-12T00:00:00.000Z    2022-09-27T18:19:50.000Z    None    58e7abeb0000ff000a8ac3aa    a levin     2   GB  False   False   Hi there, I'm really sorry about this, I've asked the team to give you a call to discuss the reason for the Text, you'll hear from them shortly. Thanks Amy 2022-09-28T08:37:11.614Z    None
3   633696ee3d107cfdfccef1fa    False   False   BUPA processed my request quickly and allowed me the care I needed however they raised my fee from £135 to £206 a month while I was in the middle of treatment so was unable to look elsewhere. 3   BUPA processed my request quickly   1   None    False   1   None    []  en  None    None    True    2022-09-30T09:12:46.000Z    BusinessGeneratedLink   invitation  invited 2022-07-28T00:00:00.000Z    2022-09-30T09:12:46.000Z    None    5f1b27d613b1ca629d80359d    Judy March      9   GB  False   False   Hi Judy. Thanks for your feedback. You may wish to give your Loyalty team a call on 0800 010 383 to discuss the cost of your policy in more detail, and to see if there any options open to you. Many thanks, Brian 2022-09-30T10:05:44.158Z    None
4   6332c3f5484ccb2c525e811c    False   False   All very straight forward when making a claim just make sure you talk to BUPA first to check your cover then get a private referral from a GP, go to the website and choose your consultant / Hospital and give them a call to arrange an appointment. I added my wife to my policy a couple of years ago and glad I did as she recently needed some quick diagnoses and treatment for heart condition. All sorted within 6 weeks of seeing the consultant. 5   Quick and simple from diagnoses to treatment.   0   None    False   1   None    []  en  None    None    True    2022-09-27T11:35:49.000Z    BusinessGeneratedLink   invitation  invited 2022-08-15T00:00:00.000Z    2022-09-27T11:35:49.000Z    None    5ea9d7c9bbf1afc1c1f68ef6    Philip      12  GB  False   False   Thanks for taking the time to review us Phillip, we really appreciate it. Amy   2022-09-27T11:50:14.607Z    None
5   6332da211c24523f3c9f71e5    False   False   Cover was not enough to complete my treatment. I appreciate that I pay a certain amount of cover however, there was no way I could complete treatment and consultations with the benefit received. Surely enough cover should be provided to complete treatment.    3   Insufficient cover  1   None    False   1   None    []  en  None    None    True    2022-09-27T13:10:25.000Z    BusinessGeneratedLink   invitation  invited 2022-08-28T00:00:00.000Z    2022-09-27T13:10:25.000Z    None    600ff7dd771237001951b6fd    Diane       3   GB  False   False   Hi Diane, thanks for your comments. Sorry you feel that your cover is insufficient. We would happily discuss your policy options with you at your renewal. Amy  2022-09-27T13:22:00.300Z    None
6   6332cd761133a76521b92128    False   False   As over the years, during my last contact with Bupa staff member to get authorisation for consultation, I did not experience any issue what so ever. The staff member was very helpful, knowledgeable and understanding. Mine is a complex which has not been professionally diagnosed but only I know what my issue is. Throughout I have had immense moral support on top of medical support which has been very valuable. \nUnderstanding of most staff members has been above and beyond expectations.  5   Bupa has been my life saver.    0   None    False   1   None    []  en  None    None    True    2022-09-27T12:16:22.000Z    BusinessGeneratedLink   invitation  invited 2022-09-27T00:00:00.000Z    2022-09-27T12:16:22.000Z    None    5992b48b0000ff000abbf4db    Manju       9   GB  False   False   Thanks for sharing your experience Manju, we really appreciate it. All the best, Amy.   2022-09-27T12:22:09.148Z    None
7   6332d0f31133a76521b924dd    False   False   Poor at best:\n\n1) Admin, confusion when mistakes are made by them, I have to sort their errors out.\n2) Changing terms and what I can claim for, meaning that I'm going through the NHS for me treatment.\n\nI can go on but pointless as you get my drift.   1   Poorest provider yet    0   None    False   1   None    []  en  None    None    True    2022-09-27T12:31:15.000Z    BusinessGeneratedLink   invitation  invited 2022-09-23T00:00:00.000Z    2022-09-27T12:31:15.000Z    None    5cb772a47fe10841711b6bea    Guido       4   GB  False   False   Hi Guido, I'm really sorry that this is how you feel after your recent experience. It looks like we have discussed your concerns, but if you would like to discuss this any further, or have any questions we'd be happy to help, call our Customer Relations team on 0345 606 6739. Amy    2022-09-27T12:57:42.082Z    None
8   63342e5c1133a76521ba2ec0    False   False   Am in Bupa with my employer.\nHaving various tests done and need \nBupa's approval to go ahead.\nAt this stressful time for me they have been brilliant. Call handlers polite ever so friendly and extremely helpful.   5   Am in Bupa with my employer.    0   None    False   1   None    []  en  None    None    True    2022-09-28T13:22:04.000Z    BusinessGeneratedLink   invitation  invited 2022-09-28T00:00:00.000Z    2022-09-28T13:22:04.000Z    None    5c61a0faf7edcbadbf39934d    Peter Francis. Somerset     4   GB  False   False   Thank you for taking the time to review us Peter. Wishing you all the best with any further treatment. Amy  2022-09-29T09:01:26.925Z    None
9   6332ce3d1c24523f3c9f654f    False   False   Not great to be honest, it isn't this stressful on the NHS. Very disappointing, constantly having to call them, I was under the impression paying private would make life easier, I couldn't have been more wrong. Dreadful service. Paid more out in excess than what the treatment actually cost? 1   Not great to be honest  0   None    False   1   None    []  en  None    None    True    2022-09-27T12:19:41.000Z    BusinessGeneratedLink   invitation  invited 2022-09-27T00:00:00.000Z    2022-09-27T12:19:41.000Z    None    6332ce3c56accb0012f8db20    MJH     1   GB  False   False   Hi there, thank you for taking the time to share your experience. I can see that we've looked into your concerns and responded to you. If you feel that you would like to discuss this further or if you're unhappy with our response, your next steps will be noted on our correspondence. Amy 2022-09-27T13:01:57.551Z    None
10  6332ca3a1c24523f3c9f610e    False   False   As I get older I get more and more grateful that I have BUPA to contact if I need serious medical attention not readily available on the NHS. Their systems for processing inquiries and authorisations is very efficient. And I am very impressed by the BUPA hospital near me, the Cromwell.  5   As I get older I get more and more… 0   None    False   1   None    []  en  None    None    True    2022-09-27T12:02:34.000Z    BusinessGeneratedLink   invitation  invited 2022-09-15T00:00:00.000Z    2022-09-27T12:02:34.000Z    None    4fd6243600006400011afc2a    Ian Dunlop      12  GB  False   False   Hi Ian, thanks for taking the time to review us. We're really pleased this is how you feel after your recent experience. Thank you, Amy.    2022-09-27T12:19:55.899Z    None
11  6332e3161133a76521b938a7    False   False   Had a tooth  broken and went to Malmesbury Dental Facility, they fixed it on the day and submitted my claim through the Bupa app. Received confirmation immediately and my claim was paid within 3 days. Great and efficient service !  5   Had a tooth  broken and went to … 0   None    False   1   None    []  en  None    None    True    2022-09-27T13:48:39.000Z    BusinessGeneratedLink   invitation  invited 2022-09-09T00:00:00.000Z    2022-09-27T13:48:39.000Z    None    61939eeed5fd380012bff341    Mr Biggs        3   GB  False   False   Hi Mr Biggs. It's really pleasing to hear of the excellent service you received at a difficult time. Best wishes, Brian 2022-09-27T14:55:51.644Z    None
12  6332a70b5871ff1ef90b50a6    False   False   I broke my hand. First Bupa did not approve saying need to check if it's a pre-existing condition!? A broken hand? Then they called to say the cast is not covered!! It was of course not a pre-existing condition and the cast was covered but I guess common sense does not prevail.  2   I broke my hand 0   None    False   1   None    []  en  None    None    True    2022-09-27T09:32:27.000Z    BusinessGeneratedLink   invitation  invited 2022-08-29T00:00:00.000Z    2022-09-27T09:32:27.000Z    2022-09-27T11:41:26.000Z    54bdda760000ff0001a547f5    Suzie Pilkington        7   AE  False   False   Hi Suzie, sorry to se you're unhappy with the terms of your scheme. If there's anything you'd like to discuss further, please let us know. Amy  2022-09-27T09:45:46.722Z    None
13  6336060d4a5fff53cad25028    False   False   A very positive experience. \nI was seen by a consultant within days of my enquiry . It was a very positive experience and my surgery was scheduled for the following week. 5   A very positive experience  0   None    False   1   None    []  en  None    None    True    2022-09-29T22:54:37.000Z    BusinessGeneratedLink   invitation  invited 2022-09-29T00:00:00.000Z    2022-09-29T22:54:37.000Z    None    57a614090000ff000a386665    Sonia       7   GB  False   False   Hi Sonia. Thanks for the wonderful 5 star feedback. I wish you all the best with your surgery and recovery. Regards, Brian  2022-09-30T08:06:25.153Z    None
14  63333cb11133a76521b9a198    False   False   Contacted BUPA as having private Healthcare through work.\nExcellent communication and had a call from the Healthcare provider the following afternoon. All now sorted and appointment with a consultant in a couple of weeks.  5   Contacted BUPA as having private…   1   None    False   1   None    []  en  None    None    True    2022-09-27T20:10:57.000Z    BusinessGeneratedLink   invitation  invited 2022-09-19T00:00:00.000Z    2022-09-27T20:10:57.000Z    None    5d47efe56bc3c146a509621e    Marie Stott     11  GB  False   False   Thank you Marie, Amy.   2022-09-28T08:51:01.849Z    None
15  6332e07a1133a76521b935b3    False   False   Bupa like most insurers take an adversarial position in settling claims. They owe me 1500 pounds for 8 months and after arguing with them and spending 6 hours on the phone I finally gave up and forgot the money owed to me.  2   Bupa like most insurers take an…    0   None    False   1   None    []  en  None    None    True    2022-09-27T13:37:30.000Z    BusinessGeneratedLink   invitation  invited 2022-01-15T00:00:00.000Z    2022-09-27T13:37:30.000Z    None    62336118e7dd2a0013cfbac2    customergg      3   GB  False   False   Hi there. Thanks for getting in touch. I see this has already been looked into for you, but please give our Customer Relations team a call on 0345 606 6739 if you'd like to discuss this in more detail. Many thanks, Brian    2022-09-27T14:44:04.578Z    None
16  6332b5715871ff1ef90b5e03    False   False   Well, if it hadn't been for one particular individual, I would have given you five stars. Please feel free to contact me for further details.\n\nFurther to your response Amy, if you want further details, you contact me. You have my contact details in n file !!    1   Insensitive Personel    0   None    False   1   None    []  en  None    None    True    2022-09-27T10:33:53.000Z    BusinessGeneratedLink   invitation  invited 2022-09-02T00:00:00.000Z    2022-09-27T10:33:53.000Z    2022-09-27T11:33:48.000Z    57fcd0370000ff000a4c74ec    Mr Simon Belson     10  GB  False   False   Hi Simon, we really sorry this is the case, we'd like to look into this for you. Please contact our Customer Relations team on 0345 606 3739. Amy   2022-09-27T11:20:56.132Z    None
17  6335474e272def1ea67aafcd    False   False   To date Bupa have been slow and ineffective resulting in delays to a treatment I need. \nMy business moved to them recently and I am unimpressed and will review this when renewal is due.  1   To date Bupa have been slow and…    0   None    False   1   None    []  en  None    None    True    2022-09-29T09:20:46.000Z    BusinessGeneratedLink   invitation  invited 2022-09-08T00:00:00.000Z    2022-09-29T09:20:46.000Z    None    62156e4b648564001211ea2a    Mr Merton       2   GB  False   False   Hi David, we're really sorry to hear this. I can see this is something we've discussed with you. If you still have concerns please to contact us to discuss further. Amy    2022-09-29T09:42:48.269Z    None
18  63349ef3272def1ea67a6a15    False   False   When I first contacted BUPA to get authorisation for a procedure I could "talk" only to a chat bot on my iPhone; very difficult to get "her" to understand what I wanted. Difficult to see the conversation and unable to save & print it as I don't have a printer. This resulted in the incorrect code sent to me. It caused me some embarrassment with the clinic. I then phoned again and was able to speak to a person to whom I was able to converse and who eventually issued the correct procedure code. "Speaking" to a chat bot was ineffective. When one is anxious because of a health problem one does not welcome not being able to easily and simply talk to someone. I was relieved that this happened eventually but wonder why BUPA thinks that using chatbot is efficient and progressive. It is not suitable for elderly folk such as me, who is not tech savvy.    1   Contacting BUPA for help    0   None    False   1   None    []  en  None    None    True    2022-09-28T21:22:27.000Z    BusinessGeneratedLink   invitation  invited 2022-08-08T00:00:00.000Z    2022-09-28T21:22:27.000Z    None    52efe2d0000064000161f688    Angela Pitfield     4   GB  False   False   Hi Angela, we're really sorry this was your recent experience. We're working hard to improve our channels of communication but we appreciate we still have some work to do. We really appreciate your feedback so thank you. Amy    2022-09-29T08:26:43.053Z    None
19  6332d6741c24523f3c9f6dd8    False   False   Bupa were great from start to finish! \nEverything got sorted so quickly and Bupa were great at authorising treatment and any questions that I had, would definitely recommend Bupa to anyone!  5   Bupa were great from start to finish    0   None    False   1   None    []  en  None    None    True    2022-09-27T12:54:44.000Z    BusinessGeneratedLink   invitation  invited 2022-09-27T00:00:00.000Z    2022-09-27T12:54:44.000Z    None    6332d673e7e9140012411715    Sophie      1   GB  False   False   Thanks for taking the time to review us Sophie, we really appreciate it. Amy    2022-09-27T13:03:36.057Z    None

There is a lot of information in that dataframe, you may want to slice and dice it as you see fit. Also, there are many pages with reviews, so you may want to adjust your range accordingly (For some reason I got an error when trying to start from page 1, please investigate).
For TQDM visit https://pypi.org/project/tqdm/
For Requests documentation, see https://requests.readthedocs.io/en/latest/
Also for pandas: https://pandas.pydata.org/pandas-docs/stable/index.html


text:
Q: Is there such thing as a "free" equivalent to Microsoft Virtual Server? I'm a student, I'd love to play around with this technology without the fear of my licence disappearing the day I graduate from college (as it might with the Microsoft Virtual Server licence from Dream Spark.
Anyone any suggestions?

A: Currently VirtualBox is free of charge for personal use - including professional personal use. The latter has changed (to inclusion of professional personal use) when Oracle aquired Sun. It may change back any time.
Microsoft Virtual PC is still free - but I am not sure if it runs on Windows 7 or higher.
OpenSource is Linux-KVM. Not really OpenSource (just some Versions) is XEN. Most free OpenSource Linux distributions now include KVM (e.g. Ubuntu LTS).

A: The closest equivalents that I can think of are VirtualBox or Xen. Wikipedia has a list of virtual machine softwares.

A: Try Proxmox. It's special linux distribution dedicated for crating virtualization hosts. It's based on Debian and Supports KVM and OpenVZ. It has awesome web GUI that allows easy virtual machines managment.
I used it in my company for few months and I love it.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Unable to get selected value for DropDownListFor (MVC5) I am able to retrieve values from my database and display in the dropdownlist but I want to make it to have a selected value whereby my database has the ID value on it.
Here's my code:
AdminViewModel.cs
public IEnumerable<UserType> UserTypes { get; set; }
public int userTypeID { get; set; }

Controller
var userType = _context.UserTypes.ToList();
var viewModel = new AdminViewModel()
{
     UserTypes = userType
 };
 return View(viewModel);

View
@Html.DropDownListFor(m => m.userTypeID, new SelectList(Model.UserTypes, "userTypeID", "userTypeName", Model.userTypeID), new { @class = "form-control" })

Selected value should be Caregiver based on the database value:

A: Use SelectListItem instead and set the value true for selected item.
AdminViewModel.cs:
public IEnumerable<SelectListItem> UserTypes { get; set; }
public int userTypeID { get; set; }

Controller:
var viewModel = new AdminViewModel();
SelectListItem item;
var userType = _context.UserTypes.ToList();
foreach(var uType in userType)
  {
   item = new SelectListItem();
   item.Text = userType.userTypeName;
   item.Value = userType.userTypeID;
   if (item.Text == "Caregiver") // or any logic
     {
       item.Selected = true;
     }
     viewModel.UserTypes.Add(item);
   }

 return View(viewModel);

View:
@Html.DropDownListFor(m => m.userTypeID, Model.UserTypes , "Select", new { @class = "form-control" })


text:
Q: Is there a way to json serialize fields that aren't stored within a form in asp.net I am working on an Asp.net page and have fields that aren't organized inside a form.  Are there libraries that make it easier to serialize values to JSON elements that aren't in forms to a web method?

A: you might search for all inputs on the page or div and serialize them
using jquery :
jQuery.map($('input') , function(n, i){
      return {name:n.name,value:n.value};
    });

and then convert to json array using for example
http://code.google.com/p/jquery-json/
by adding before
$.toJSON( jQuery.map($('input') , function(n, i){
          return {name:n.name,value:n.value};
        }));


text:
Q: Forget Password Customized forget password in yii I am very new in YII framework. I want to add "Forget Password" along with the login form. When user click on it, system will fetch email address of that user from the database and send new Password to that user by email. I don't want to use any plug-ins for that.
This is my link code:-
        <?php echo CHtml::Link(Yii::t('job','Forgot Password ?'),
                                $this->createUrl('site/forgotpassword'),
                                array(
                                    'onclick'=>'$("#jobDialog").dialog("open"); return false;',
                                    'update'=>'#jobDialog'
                                ),
                                array('id'=>'showJobDialog'));?>

This is my site controller:-
public function actionForgotPassword()
{
    $model  = new User;
    $this->renderPartial('createDialog',array('model'=>$model,),false,true);
}

This is my createdialog.php:-
<?php

$this->beginWidget('zii.widgets.jui.CJuiDialog',array(
                'id'=>'jobDialog',
                'options'=>array(
                    'title'=>Yii::t('job','Fogot Password ?'),
                    'autoOpen'=>true,
                    'modal'=>'true',
                    'width'=>'auto',
                    'height'=>'auto',
                ),
                ));
echo $this->renderPartial('_formDialog', array('model'=>$model)); ?>
<?php $this->endWidget('zii.widgets.jui.CJuiDialog');?>

This is my _formDialog.php

<?php $form=$this->beginWidget('CActiveForm', array(
                                            'id'=>'job-form',
                                            'enableAjaxValidation'=>true,
                                ));
//I have enableAjaxValidation set to true so i can validate on the fly the
?>

Fields with * are required.

<?php if(Yii::app()->user->hasFlash('error')):?>

                <?php echo Yii::app()->user->getFlash('error'); ?>

<?php endif; ?>

    <?php echo $form->errorSummary($model); ?>

        <?php echo $form->labelEx($model,'email'); ?>
        <?php echo $form->textField($model,'email',array('size'=>60,'maxlength'=>180,'class'=>'forgot_password')); ?>
        <?php echo $form->error($model,'email'); ?>

        <?php echo CHtml::ajaxSubmitButton(Yii::t('job','Submit'),CHtml::normalizeUrl(array('site/forgotpassword1','render'=>false)),array('success'=>'js: function(data) {
                        $("#jobDialog").dialog("close");
                    }'),array('id'=>'closeJobDialog','onclick'=>'return forgotpassword()')); ?>

<?php $this->endWidget(); ?>

A: Put this in your controller,
private function randomPassword() {
    $alphabet = "abcdefghijklmnopqrstuwxyzABCDEFGHIJKLMNOPQRSTUWXYZ0123456789";
    $pass = array(); //remember to declare $pass as an array
    $alphaLength = strlen($alphabet) - 1; //put the length -1 in cache
    for ($i = 0; $i < 8; $i++) {
        $n = rand(0, $alphaLength);
        $pass[] = $alphabet[$n];
    }
    return implode($pass); //turn the array into a string
}

public function actionForgotPassword($email) {
    $user = User::model()->findAll('email=:email',
                array('email'=>$email);

    if(count($user) != 1) {
        Yii::app()->user->setFlash('user',
            Yii::t('messages', 'Unable to find user.'));
        );
        $this->refresh();
    }
    else {
        $user = $user[0];
        $user->password = $this->randomPassword();
        $user->update();

        // Send new password to email
        $from = 'Password Reset <admin@yoursite.com>';
        $to = $user->email;
        $name = $user->firstname.' '.$user->lastname;
        $subject = 'Reset Password';

        $message = Yii::t('user', 'Dear').' '.$user->username.',
'.Yii::t('user', 'A request has been made to reset your password.').'
'.Yii::t('user', 'Your new password is').': '.$user->password.'
'; // Our message above

        $headers = 'From: '.$from."\r\n"; // Set from headers
        mail($to, $subject, $message, $headers); // Send our email

        Yii::app()->user->setFlash('user',
            Yii::t('notices', 'A new password has been sent to your email address.')
        );
        $this->refresh();
    }

    $this->layout = '//layouts/main';
    $this->render('resetpassword');
}

Also add a view "resetpassword.php":

    <?= Yii::app()->user->getFlash('user') ?>


text:
Q: node.js mysql error: ECONNREFUSED Why can't I connect to the mysql server?
On the same server an Apache/PHP server is running and it connects without problems!?
var mysql_link = {
    host : 'localhost',
    port : 3308,
    database: 'nodetest',
    user : 'root',
    password : 'xxx'
};

var connection = mysql.createConnection(mysql_link);

connection.connect(function(err){
    console.log(err);
    if(err != null){
        response.write('Error connecting to mysql:' + err+'\n');
    }
});

connection.end();

error
{ [Error: connect ECONNREFUSED]
  code: 'ECONNREFUSED',
  errno: 'ECONNREFUSED',
  syscall: 'connect',
  fatal: true }

update
root@dyntest-amd-6000-8gb /var/www/node/dyntest # ps ax | grep mysqld
 7928 pts/0    S+     0:00 grep mysqld
28942 ?        S      0:00 /bin/sh /usr/local/mysql/bin/mysqld_safe --datadir=/var/lib/mysql --pid-file=/var/run/mysqld/mysqld.pid
29800 ?        Sl    17:31 /usr/local/mysql/bin/mysqld --basedir=/usr/local/mysql --datadir=/var/lib/mysql --plugin-dir=/usr/local/mysql/lib/plugin --user=mysql --log-error=/var/lib/mysql/mysql-error.log --open-files-limit=65535 --pid-file=/var/run/mysqld/mysqld.pid --socket=/var/run/mysqld/mysqld.sock --port=3306

A: I know this question has been answered, but for me the problem was that the mysql server listens on a Unix socket not on a tcp socket. So the solution was to add:
port: '/var/run/mysqld/mysqld.sock'

to the connection options.

A: For some very odd reason, my computer only allowed me to have port 3306 as default port for my connection in order for it to work.

A: Mac OS on M1 MacBook Pro here with MySQL installation via brew:
Changing the host from 'localhost' to '127.0.0.1' and creating a different user with a password solved this issue for me.
For some reason I cannot connect to my DB with root user and no password.
I created the new user on MySQL Workbench, but you can create a new user with admin privileges via the mysql CLI also.
Just google it.
This is how my backend looks:
const express = require('express');
const mysql = require('mysql');
const app = express();
const port = 3500;

const db = mysql.createConnection({
    host: '127.0.0.1',
    user: 'admin',
    password: 'admin',
});
db.connect((err) => {
    if (err) throw err;
    console.log('connected to database');
});

app.listen(port, () => {
    console.log('server listening on port 3500');
});

A: I wanted to comment my solution here, just in case there were people as newbie as me in databases.
I was getting this error because I had installed the mysql NPM package correctly but I hadn't installed any implementation of MySQL on my computer (I didn't know I had to).
I'm using Arch Linux so, in my case, with the NPM package already installed in my project, I did pacman -Syu mariadb (MariaDB is the default implementation of MySQL in Arch Linux) and then configured it following the guide.
Then, you can use the root user you just configured or create a new one to use in your project. For the latter:

*

*Enter mysql CLI by running mysql -u root -p.

*Enter the password for root user.

*Create a new database with CREATE DATABASE mydatabase;.

*Create a new user with CREATE USER test IDENTIFIED BY "testpass";.

*Grant privileges to test user to use your new database with GRANT ALL PRIVILEGES ON mydatabase.* TO test@localhost IDENTIFIED BY "testpass";. See for more information on this.
And then, in my project, I would have:
let connection = mysql.createConnection({
    host: "localhost",
    user: "test",
    password: "testpass",
    database: "mydatabase"
});

A: If this has worked before, my first guess would be that you've already got a copy of your node.js script running in the background which is holding the connection.
I believe connection refused is a tcp/ip error message, rather than something from MySQL which suggests that it is either not running or is running on another port or with sockets.
Could you try telnet'ing to port 3308? To see if the server is running on that port?
telnet localhost 3308

Can you also try:
mysql -hlocalhost -uroot -pxxx

A: Overview
For anyone else having this problem and is running mamp. I suspected the problem had to do with the network and not MySQL or Node.js.
Solution
If you open MAMP and click MySQL in the left navigation panel it will pull up the MySQL options page. In the center of the page you will see a checkbox that says,

"Allow network access to MySQL".

Check this box and then restart your MAMP. At this point you can now test your connection to MySQL with telnet or a node.js script.
Hint
Remember you can check which port your MySQL is running on by opening MAMP and clicking the ports link on the left navigation panel.
Visual Aid

A: If you are using MAMP please note that mysql default db_port is set to 8889 so you for this purpose I had to change it to 3306 (or whatever your app mysql db_port is set to).
My issue was that node server was connecting using port 3306, so it was giving the error below then crashing but mysql was up and seemed to establishing a connection through localhost, although I couldnt test it because node server was down.
errno: -61,
code: 'ECONNREFUSED',
syscall: 'connect',
address: '127.0.0.1',
port: 3306,
fatal: true
Once I changed the port on MAMP mysql from 8889 to 3306, node server established connection through port 3000 and giving the statement below:
server running on port 3000
The solution is:  2

A: I use Windows 10 and I have Windows Subsystem For Linux (WSFL). I can execute my project from the WSFL console, but my MySQL is installed in Windows and they can not connect, however when I execute my project from a Windows console then it works without any problems.


text:
Q: How to drag remote item from WPF onto desktop? In FileZilla, I can select a file on a remote site and drag it onto my desktop.  After I 'drop' the file on my desktop, FileZilla starts streaming the file.
I want to achieve similar functionality using WPF - is this possible and how can it be done?
Below is a snippet which shows how to drag a local file to the desktop using it's file path.  My scenario is different in that the file is not physically available when DragDrop.DoDragDrop is called.
//FileDetails holds information about where the file is downloaded from.
FileDetails fileDetails = (FileDetails)listView.ItemContainerGenerator.
    ItemFromContainer(listViewItem);

DataObject dragData = new DataObject(DataFormats.FileDrop, fileDetails);
DragDrop.DoDragDrop(listViewItem, dragData, DragDropEffects.Copy);
//At this point control goes to the OS.

Ideally I'd like to detect the 'drop' event with information about where the drop occured. Another option might be to pass a StreamWriter in to DoDragDrop() and write the bytes into it as they are received.

A: Have a look at this:
Creating something from nothing [Developer-friendly virtual file implementation for .NET!] - The blog of dlaa.me
I think that does what you require.


text:
Q: Is it possible to delete a monitor or change the name as shown in Display Preferences? I have a pair of the same model and size monitors at home, as I have in the office. They're all named "Company Model (1)" and "Company Model (2)".
It seems like the setup I have at home has them physically arranged from L -> R: 1 -> 2, but in the office, however, it's 2 -> 1.
The result is when I work from home, or work from the office, I need to constantly set the Display Arrangement in Preferences.
Is there a way to delete the displays, so I can reintroduce them to the computer in the right order, or just rename them so the one physically on the left is always 1, and the one on the right is always 2?

A: It turns out it's the dongle with which the monitors are connected. I have two different brands (Satechi and Anker) at home, and (Apple and Anker) at work. When I plug the monitors into the different dongles, it changes orientation. The reason the physical swap didn't work, was because I also unplugged the cables from the monitors in the office, and reconnected them to the different dongles. I tried unplugging the monitors from the dongles at home and swapping them, and and they indeed switched.
This is probably the most trivial of information, but it's at least answered!


text:
Q: Beautiful Soup-Regex-How to extract particular part from href in tag Hey so I am using Beautiful soup to make a scrapper which aims to extract the id of an app searched on playstore. The code:
def linkgen(name):
    base = "https://play.google.com/store/search?q="
    req = requests.get(base + name)
    soup = BeautifulSoup(req.content, "html.parser")
    soup2=soup.find( class_ = "Si6A0c Gy4nib" )
    print(soup2)

The output generated:

Facebook

Meta Platforms, Inc.

3.2star

Out of this output I want to extract the id present in the href link(For this case I want to extract "com.facebook.katana"). I have tried searching for href in a tag and tried using regex as well but couldn't get any output. Anyone?
Thank you

A: To get only href tag content you can try using this regex sample in your python code:
r"(?<=id=)(.*?)(\")"

Then remove the last char at the end of the string.
If you want to try the regex just go here :)
Hopes this will help you! Have a nice day.


text:
Q: Xamarin forms 3 color progress bar In a Xamarin form, I want to show three color progress bar about three numbers to show on progress bar:

*

*Number of available questions

*Number of passed uestions

*Number of failed questions

I want it to look like this:
Image showing progress bar with each categories
Can someone help me? Thanks in advance.

A: I prefer use Ncontrol for all such custom controls. It is crossplatform, so you will not need any renderers
1) Install NControll to PCL and your platform projects
2) Subclass NControlView
3) Override Draw method
public class MyControl: NControlView
{
  private int _sectionOneValue = 0;
  private int _sectionTwoValue = 0;
  private int _sectionThreeValue = 0;

  public void SetSectionValues(int one, int two, int three){
      _sectionOneValue = one;
      _sectionTwoValue = two;
      _sectionThreeValue =three;
      Invalidate();
  }

  public override void Draw(NGraphics.ICanvas canvas, NGraphics.Rect rect)
  {
     var sum = _sectionOneValue+_sectionTwoValue+_sectionThreeValue
     if(sum == 0)
         return;

     var wOne = (rect.Width*_sectionOneValue)/sum;
     var wTwo = (rect.Width*_sectionTwoValue)/sum;
     var wThree = (rect.Width*_sectionThreeValue)/sum;

     canvas.FillRectangle (new Rect (0, 0, wOne, rect.Height ), NGraphics.Colors.Red);
     canvas.FillRectangle (new Rect (wOne, 0, wTwo, rect.Height ), NGraphics.Colors.Blue);
     canvas.FillRectangle (new Rect (wOne+wTwo, 0, wThree, rect.Height ), NGraphics.Colors.Green);

  }
}

A: You can use my nugget package to implement this multi color progress bar.
https://www.nuget.org/packages/MultiColor.ProgressBar/
Documentation:
https://github.com/udayaugustin/ProgressBar/blob/master/README.md
You can just supply only one BarSegment to the list and create the view like your design.


text:
Q: How to clone github private repository in cpanel (shared host without terminal or ssh)? I have a shared host and they don't give me ssh or terminal for it.
I've tried to clone my private repos from git by Git™ Version Control so I am using ssh link because they need permission. I don't know how to make ssh key on cpanel so I can make it from my mac and upload to cpanel and also add to Github.
But when running, they give me error: Permission denied (publickey). fatal: Could not read from remote repository. Please make sure you have the correct access rights and the repository exists..
I'm a beginner for using Git & StackOverflow, so please let me know if there's anything wrong with the question I've asked. Thanks!
Tried Url with password
Cloning a private Github repo and
having a response "The clone URL cannot include a password."

A: This is different than what worked for the OP (hopefully they put their solution in an answer here).
I was able to solve this problem by installing an external SSH client (like PuTTY for Windows) and then SSH into my website using its IP address. Then I followed these steps from cPanel to connect the private repository.


text:
Q: Sound reverberation in a completely flat environnement I don't know much about physics but I have a question.
Let's say you were lost in a completely flat desert, with seemingly nothing else surrounding it, and you screamed at the top of your lungs: would you be able to hear any echo/reverberation ?

A: In the way you state it there would be no reverberation or echo since the (assumed/speculated) geometry (since you don't provide enough information) will not provide any reflections towards you.
Keep in mind though that another listener will "hear" (whether this will be sensed or not is another story though) some kind of "reverberation" (at least the direct sound and a reflection from the desert ground).


text:
Q: Time series daily data modeling I am looking to forecast my time series. I have the following period daily data 2021-Jan-1 to 2022-Jul-1.
So I have a column of observations for each day.
what I tried so far:
d1=zoo(data, seq(from = as.Date("2021-01-01"), to = as.Date("2022-07-01"), by = 1))
tsdata <- ts(d1, frequency = 365)
ddata <- decompose(tsdata, "multiplicative")

I get following error here:

Error in decompose(tsdata, "multiplicative") :
time series has no or less than 2 periods

From what i have read it seems like because I do not have two full years? is that correct? I have tried doing it weekly as well:
series <- ts(data, frequency = 52, start = c(2021, 1))

*

*getting the same issue.

How do I go about it without having to extend my dataset to two years since I do not have that, and still being able to decompose it?
Plus when I am actually trying to forecast it, it isn't giving me good enough forecast:
Plot with forecast
My data somewhat resembles a bell curve during that period. so is there a better fitting timeseries model I can apply instead?

A: A weekly frequency for daily data should have frequency = 7, not 52.  It's possible that this fix to your code will produce a model with a seasonal term.
I don't think you'll be able to produce a time series model with annual seasonality with less than 2 years of data.
You can either produce a model with only weekly seasonality (I expect this is what most folks would recommend), or if you truly believe in the annual seasonal pattern exhibited in your data, your "forecast" can be a seasonal naive forecast that is simply last year's value for that particular day.  I wouldn't recommend this, because it just seems risky, and I don't really see the same trajectory in your screenshot over 2022 that's apparent in 2021.

A: decompose requires two full cycles and that a full cycle represent 1 time unit.  ts class can't use Date class anyways.  To use frequency 7 we must use times 1/7th apart such as 1, 1+1/7, 1+2/7, etc. so that 1 cycle (7 days) covers 1 unit.  Then just label the plot appropriately rather than using those times on the X axis.  In the code below use %Y in place of %y if the years start in 19?? and end in 20?? so that tapply maintains the order.
# test data
set.seed(123)
s <- seq(from = as.Date("2021-01-01"), to = as.Date("2022-07-01"), by = 1)
data <- rnorm(length(s))
tsdata <- ts(data, freq = 7)

ddata <- decompose(tsdata, "multiplicative")

plot(ddata, xaxt = "n")
m <- tapply(time(tsdata), format(s, "%y/%m"), head, 1)
axis(1, m, names(m))


text:
Q: CM10.1 SDK Level? My app checks for the user's SDK level, for example, like this:
if(android.os.Build.VERSION.SDK_INT >= 18){ ... }
I've had reports of users running CM10.1 that this returns true(and consequently crashes my app), even though I had the impression that CM10.1 is based on 4.2.2, rather than 4.3 (which would be CM10.2)? Has anyone else encountered this?
Thanks!


text:
Q: extjs4 ajax api store update I'm trying to update my store and then database after using cellediting and a combobox in a gridpanel to update a record. The update operation.action in the ajax proxy is firing correctly, it just that the store and the grid aren't syncronizing, and the post tab in firebug says my json looks like this: 'data []'. How do I get the store record to create the json and update the record? Thanks for looking at this in advance...
Ext.Loader.setConfig({
    enabled: true
});
Ext.Loader.setPath('Ext.ux', '/extjs4/examples/ux');
Ext.require([
    'Ext.layout.container.Fit',
    'Ext.grid.*',
    'Ext.data.*',
    'Ext.util.*',
    'Ext.panel.*',
    'Ext.selection.CellModel',
    'Ext.state.*',
    'Ext.form.*',
    'Ext.ux.CheckColumn']);

Ext.define('Ext.app.HirePlanGrid', {
    extend: 'Ext.panel.Panel',
    alias: 'widget.hirePlangrid',
    hireplanstoreId: 'hireplanstore',
    hiremonthstoreId: 'hiremonthstore'

    ,
    renderMonth: function (value, p, record) {
        var fkStore = Ext.getStore(this.up('hirePlangrid').hiremonthstoreId);
        var rec = fkStore.findRecord("MONTH_ID", value);
        //return rec.get("ABBREVIATED_MONTH");
    }

    ,
    initComponent: function () {
        var rIdx = '';
        var cIdx = '';

        this.editing = Ext.create('Ext.grid.plugin.CellEditing', {
            clicksToEdit: 1,
            listeners: {
                'beforeedit': function (e) {
                    var me = this;
                    var allowed = !! me.isEditAllowed;
                    if (!me.isEditAllowed) Ext.Msg.confirm('confirm', 'Are you sure?', function (btn) {
                        if (btn !== 'yes') return;
                        me.isEditAllowed = true;
                        me.startEditByPosition({
                            row: e.rowIdx,
                            column: e.colIdx
                        });
                    });
                    rIdx = e.rowIdx;
                    cIdx = e.colIdx;
                    // alert('rIdx= ' + rIdx + ' cIdx = ' + cIdx);
                    return allowed;
                },
                    'edit': function (e) {
                    this.isEditAllowed = true;
                }
            }
        });

        var objMonthStore = Ext.getStore(this.hiremonthstoreId);
        objMonthStore.load();
        var objStore = Ext.getStore(this.hireplanstoreId);
        objStore.setProxy({
            type: 'ajax',
            url: 'hireplan.cfc?method=getEmployees'
        });

        objStore.load();

        var onDeleteClick = function (field, value, options) {
            // var objPanel = this.down('gridpanel');
            var selection = Ext.getCmp('grid').getSelectionModel().getSelection();
            // alert(selection);
            //var selection = getView().getSelectionModel().getSelection()[r];
            if (value) {
                //alert(value);
                objStore.remove(value);
                objStore.sync();
            }
        };
        var onUpdateClick = function (field, value, options) {
            alert('field= ' + field + ' value= ' + value + 'options= ' + options);
            objStore.update(this.hireplanstoreId, value, 'update', options);
            onSync();

        };
        var onSync = function () {
            objStore.sync();
        };

        Ext.apply(this, {
            layout: 'fit',
            width: 800,
            //height: 1500,
            items: [{
                xtype: 'grid',
                id: 'gridgrid',
                //height: 300,
                store: objStore,
                selModel: {
                    selType: 'cellmodel'
                },
                selType: 'rowmodel',
                plugins: [this.editing],
                // plugins: [cellEditing],
                columnLines: true,
                viewConfig: {
                    stripeRows: true
                },
                //loadMask: true,
                disableSelection: true,
                columns: [{
                    header: 'rowid',
                    hidden: true,
                    dataIndex: 'ROWID'
                }, {
                    header: 'Indicator',
                    id: 'chkcolumn',
                    xtype: 'checkcolumn',
                    dataIndex: 'CHK_COL',
                    editor: {
                        xtype: 'checkbox',
                        cls: 'x-grid-checkheader-editor'
                    },
                    listeners: {
                        checkchange: function (column, recordIndex, checked) {
                            alert('checked rindex= ' + recordIndex);
                            onDeleteClick(column, recordIndex, checked);
                            //or send a request
                        }
                    }
                }, {
                    id: 'employeeid',
                    header: 'employeeid',
                    width: 80,
                    hidden: false,
                    sortable: true,
                    dataIndex: 'EMPLOYEEID',
                    flex: 1
                }, {
                    id: 'NATIONALIDNUMBER',
                    header: 'NATIONALIDNUMBER',
                    width: 80,
                    sortable: true,
                    dataIndex: 'NATIONALIDNUMBER',
                    flex: 1
                }, {
                    id: 'MARITALSTATUS',
                    header: 'MARITALSTATUS',
                    width: 80,
                    sortable: true,
                    dataIndex: 'MARITALSTATUS',
                    flex: 1
                }, {
                    id: 'PotentialforInsourcingKV',
                    header: 'Potential for Insourcing',
                    width: 30,
                    sortable: true,
                    dataIndex: 'POTENTIAL_FOR_INSOURCING',
                    flex: 1,
                    editor: {
                        id: 'thiscombo',
                        xtype: 'combobox',
                        typeAhead: true,
                        triggerAction: 'all',
                        selectOnTab: true,
                        store: [
                            ['1', 'Yes'],
                            ['0', 'No']
                        ],
                        lazyRender: true,
                        listClass: 'x-combo-list-small',
                        listeners: {
                            scope: this,
                                'select': function () {
                                var selval = Ext.getCmp('thiscombo').getValue();
                                var row = rIdx;
                                //alert(selval + ' ' +  rIdx);
                                onUpdateClick('thiscombo', rIdx, selval);
                            }
                        }
                    }
                }, {
                    id: 'ABBREVIATED_MONTH',
                    header: 'ABBREVIATED_MONTH',
                    width: 80,
                    sortable: true,
                    dataIndex: 'ABBREVIATED_MONTH',
                    flex: 1,
                    renderer: this.renderMonth,
                    field: {
                        xtype: 'combobox',
                        store: Ext.getStore(this.hiremonthstoreId),
                        typeAhead: true,
                        lazyRender: true,
                        queryMode: 'local',
                        displayField: 'ABBREVIATED_MONTH',
                        valueField: 'MONTH_ID',
                        listClass: 'x-combo-list-small'

                    }
                }, {
                    id: 'SALARIEDFLAG',
                    header: 'SALARIEDFLAG',
                    width: 80,
                    sortable: true,
                    dataIndex: 'SALARIEDFLAG',
                    flex: 1
                }],

                features: [{
                    ftype: 'rowbody'
                }]
            }]
        });
        this.callParent(arguments);
    }, //initComponent
    onSelectChange: function (selModel, selections) {
        this.down('#delete').setDisabled(selections.length === 0);
    },
    viewConfig: {},
});
// JavaScript Document
// JavaScript Document
hireplanstore = Ext.create("Ext.data.Store", {
    model: 'HiringPlan',
    //autoLoad: true,
    //autoSync: true,
    buffered: true,
    storeId: 'hireplanstore',
    remoteFilter: true

    ,
    proxy: {
        type: 'ajax',
        simpleSortMode: true,
        api: {
            read: 'hireplan.cfc?method=GetEmployees',
            update: 'hireplan.cfc?method=upEmployees',
            destroy: 'hireplan.cfc?method=delEmployees'
        },
        reader: {
            type: 'json',
            messageProperty: 'message',
            successProperty: 'success',
            root: 'data'
        },
        writer: {
            type: 'json',
            writeAllFields: false,
            root: 'data'
        },
        listeners: {
            exception: function (proxy, response, operation) {
                Ext.MessageBox.show({
                    title: 'ERROR from store',
                    msg: operation.getError(),
                    icon: Ext.MessageBox.ERROR,
                    buttons: Ext.Msg.OK
                });
            }
        }
    }

});
//hireplanstore.pageSize = 10000;
Ext.define('HiringPlan', {
    extend: 'Ext.data.Model',
    fields: [{
        name: 'ROWID',
        type: 'string'
    }, {
        name: 'EMPLOYEEID',
        type: 'string'
    }, {
        name: 'NATIONALIDNUMBER',
        type: 'string'
    }, {
        name: 'MARITALSTATUS',
        type: 'string'
    }, {
        name: 'GENDER',
        type: 'string'
    }, {
        name: 'POTENTIAL_FOR_INSOURCING',
        type: 'integer'
    }, {
        name: 'ABBREVIATED_MONTH',
        type: 'string'
    }, {
        name: 'SALARIEDFLAG',
        type: 'string'
    }, {
        name: 'CHK_COL',
        type: 'bool'
    }]

});

A: In order to update correctly your ajax or rest call have to return an array containing the updated records, even if it's a single record, you have to return it inside an array, a sample json response (for the rest proxy) should be like this:
[{'id': 1, 'name': 'test', 'foo': 'bar'}]


text:
Q: Ubuntu 21.04. 2 apps no longer working, uninstall and reinstall doesn't fix Ubuntu 21.04. Two of my apps are no longer working. VLC and Flameshot stopped working. I uninstalled, rebooted and reinstalled them multiple times using the 'Ubuntu Software' app. It says they're both installed but when I double click on their icons, nothing happens. I also installed using the terminal (sudo apt-get install vlc). It installed but when I click on the VLC icon, again, nothing happens. Any way to do this? Are there some hidden VLC and Flamesnot files that need to be removed? If so, how to do this?

A: If I were in your shoes, and I have been, I'd uninstall and purge the config files then reinstall.
In a terminal:
sudo apt purge vlc
sudo apt install vlc

If that doesn't do the trick, I've found that nvidia 470 drivers are causing some very strange issues across the board.  I don't know if you have an nvidia card installed, but if you do, I'd revert to something earlier.
Hope this helps!

A: Issue Resolved.
I got it working. I took a deep breath and did my first Timeshift system restore and it worked! Flameshot and KDEConnect started working again, but my VLC snap was not working. I then removed the VLC snap and installed the VLC flatpak and that now is working normally. So I'm back to normal.
Thank goodness for Timeshift! Now I'll be doing system snapshots a lot more often (and properly commenting them).


text:
Q: tkinter threaded gui instance halts all further spawns When  I create a tkinter window instance using a thread, even though the window is destroyed after execution, and the thread is joined; I can't make another tkinter window later on in the program flow. Why?
def on_button_click(root):  //destroys window on button click
    root.destroy()

def init():  //thread calls this
    root=Tk()
    b = Button(root, text="OK", command=lambda:on_button_click(root))
    b.pack()
    root.mainloop()

t = Thread(target=init)
t.start()
t.join()

root=Tk() //program flow halts here with no window being displayed
root.mainloop()

A: From what I can gather using my Google-foo, the problem is that the Tk event loop (which is created during your call to root.mainloop()) is single-threaded and you can only have one instance of it at a time. So that's probably why its getting stuck at that location. Your thread is properly setting up the Tk subsystem but the program fails when you try to create a second Tk subsystem to run at the same time. Your call to root.destroy() is only destroying the windows that you created and not the entire Tk subsystem.
It's been a while since I used Tk but I'd suggest calling root.mainloop() once when you first start your program and then leave your functions to instantiate Tk windows only, not the entire Tk subsystem.


text:
Q: How to make text inside a button transparent on hover? background should remain the same though How can one make the text inside a button transparent on hover? the background should remain the same though. I tried opacity:0; but it made the whole button invisible. Help. I tried the below code.
<style>
.btn:hover {
    background-color: #ededed !important;
    color: #3c3c3c !important;
    opacity:0;
}
</style>

<button class=" btn btn-success  btn-lg">test button</button>

A: You need to use an rgba(color,color,color,opacity); for the color rule.
Try this fiddle:
https://jsfiddle.net/reala/5xq3mj66/
EDIT: Alright - I think I understand your request.
You want the text to be TRANSLUCENT on hover, (but not invisible, which is 'transparent'), so that you can see the background through the text.
Very similar solution, but change the opacity of rgba to something very low, like 0.3... for example:
.btn:hover {
   color: rgba(0,0,0,0.3);
}

And remember to remove your opacity: 0, or reset it to opacity: 1 - otherwise it will make the entire button transparent. That is not what you want.


text:
Q: Customers mandatory have to create an account to pay by cb? I'm implementing Paypal Express Checkout on my website and playing with it, I notice that we can freely pay by CB, just giving our email address on the english page and we mandatory have to create an account on the french page.
Is it a mistake or intentional?


text:
Q: Idiomatic setting of nicknames/aliases? On Unix systems, you have your username, say "johnsmith", and your full name, "John Smith". That's it.
Now, suppose I want to use a nickname or two - something which isn't my username, but is in a lot of use. For example, "jsmith" may be a nickname/alias for "johnsmith".
Obviously, this information can't be saved in /etc/passwd. But - is there some idiomatic/commonly used method for indicating these nicknames?

A: Not very official but you could create a user with the other name but with the same settings (UID, GID, $HOME, password). That would allow you to use e.g. ~jsmith and ~johnsmith.


text:
Q: Non-conservative electric fields When magnetic flux is changed linked with the coil the the electric field is produced inside the coil. But this electric field is non-conservative field whereas the electric field produced by the static charge is conservative. Why when the magnetic flux is changed linked with the coil electric field induced is nonconservative? Why a static charge produce conservative Field?

A: For a vector field to be conservative (in this case, the vector field will be your electric field), you want the circulation around any closed loop to be $0$. Mathematically, you want $$\oint_{\mathcal{C}} \mathbf{E} \cdot \mathrm{d}\mathbf{r} = 0$$ for any closed loop $\mathcal{C}$.
Faraday's law states the following for an electric field generated by a changing magnetic flux: $$\oint_{\mathcal{C}} \mathbf{E} \cdot \mathrm{d}\mathbf{r} = -\frac{\partial \Phi_B}{\partial t}$$
where $\Phi_B$ is the magnetic flux through the region bounded by $\mathcal{C}$. As you can see, in the presence of a changing magnetic flux, the circulation of your electric field will be non-zero. I.e., the electric field generated by the changing magnetic flux is non-conservative.


text:
Q: D3 v4 force directed graph with rectangles In the following force directed graph, I would like to have the rectangles closer to each other vertically while maintaining the same distance horizontally:

var data = {
   "nodes":[
      {
         "name":"Abc",
         "id":"1",
         "value":"1",
         "cvr":"123"
      },
      {
         "name":"Aaa",
         "id":"2",
         "value":"0.25",
         "cvr":"7445"
      },
      {
         "name":"JTY",
         "id":"3",
         "value":"0.25",
         "cvr":"24582"
      },
      {
         "name":"TTT",
         "id":"4",
         "value":"0.1",
         "cvr":"12351"
      },
      {
         "name":"MMM",
         "id":"5",
         "value":"0.15",
         "cvr":"783456"
      },
      {
         "name":"KLI",
         "id":"6",
         "value":"0.05"
      },
      {
         "name":"OTP",
         "id":"7",
         "value":"0.250"
      },
      {
         "name":"Tasqu",
         "id":"8",
         "value":"0.250"
      },
      {
         "name":"Mii",
         "id":"9",
         "value":"0.10"
      },
      {
         "name":"YrA",
         "id":"11",
         "value":"0.150",
         "cvr":"10096669"
      },
      {
         "name":"Tarb",
         "id":"10",
         "value":"0.1500"
      }
   ],
   "links":[
      {
         "source":"2",
         "target":"1"
      },
      {
         "source":"3",
         "target":"1"
      },
      {
         "source":"4",
         "target":"1"
      },
      {
         "source":"5",
         "target":"1"
      },
      {
         "source":"6",
         "target":"1"
      },
      {
         "source":"7",
         "target":"2"
      },
      {
         "source":"8",
         "target":"3"
      },
      {
         "source":"9",
         "target":"4"
      },
      {
         "source":"11",
         "target":"5"
      },
      {
         "source":"10",
         "target":"11"
      }
   ]
};

// Create somewhere to put the force directed graph
var svg = d3.select("svg"),
    width = +svg.attr("width"),
    height = +svg.attr("height");

var rectWidth = 240;
var rectHeight = 60;
var minDistance = Math.sqrt(rectWidth*rectWidth + rectHeight*rectHeight);

// Set up the simulation and add forces
var simulation = d3.forceSimulation()
 .nodes(data.nodes);

var link_force =  d3.forceLink(data.links)
 .id(function(d) { return d.id; }).distance(minDistance).strength(1);

var charge_force = d3.forceManyBody()
    .strength(-1000);

var center_force = d3.forceCenter(width / 2, height / 2);

simulation
    .force("charge_force", charge_force)
    .force("center_force", center_force)
    .force("links",link_force);

// Add tick instructions:
simulation.on("tick", tickActions );

// Add encompassing group for the zoom
var g = svg.append("g")
    .attr("class", "everything");

var div = g.select("body").append("div")
    .attr("class", "tooltip")
    .style("opacity", 0);

// Draw lines for the links
var link = g.append("g")
 .attr("class", "links")
  .selectAll("line")
  .data(data.links)
  .enter()
   .append("line")
    .attr("stroke-width", 2)
    .style("stroke", linkColour);

// Draw rects and texts for the nodes
var nodes = g.append("g")
 .attr("class", "nodes");

var node = nodes.selectAll("node")
 .data(data.nodes)
 .enter()
  .append("g");

node
 .on("mouseover", function(d) {
  d3.select(this).select("rect").style("fill", "red");
  div.transition()
   .duration(200)
   .style("opacity", .9);
  div.html("asdasd")
   .style("left", (d3.event.pageX) + "px")
   .style("top", (d3.event.pageY - 28) + "px");
 })
 .on("mouseout", function(d) {
  d3.select(this).select("rect").style("fill", rectColour);
  div.transition()
   .duration(500)
   .style("opacity", 0);
 });

var rect = node.append("rect")
  .attr("x", -rectWidth/2)
  .attr("y", -rectHeight/2)
  .attr("width", rectWidth)
  .attr("height", rectHeight)
  .attr("fill", rectColour);

var textName = node.append("text")
  .text(function (d) { return d.name; })
  .attr("y", -15)
  .style("text-anchor", "middle");

var textCvr = node.append("text")
  .text(function (d) { return d.cvr; })
  .attr("y", 0)
  .style("text-anchor", "middle");

var textOwned = node.append("text")
  .text(function (d) { return (parseFloat(d.value)*100).toFixed(2)+"%"; })
  .attr("y", 15)
  .style("text-anchor", "middle");

node.attr("transform", function(d) {
    return "translate(" + d.x + "," + d.y + ")"
});

// Add drag capabilities
var drag_handler = d3.drag()
 .on("start", drag_start)
 .on("drag", drag_drag)
 .on("end", drag_end);

drag_handler(node);

// Add zoom capabilities
var zoom_handler = d3.zoom()
    .on("zoom", zoom_actions);

zoom_handler(svg);

/** Functions **/

function rectColour(d){
 if(d.person){
  return "blue";
 } else {
  return "pink";
 }
}

// Function to choose the line colour and thickness
function linkColour(d){
 return "black";
}

// Drag functions
function drag_start(d) {
 if (!d3.event.active) simulation.alphaTarget(0.3).restart();
    d.fx = d.x;
    d.fy = d.y;
}

// Make sure you can't drag the rect outside the box
function drag_drag(d) {
  d.fx = d3.event.x;
  d.fy = d3.event.y;
}

function drag_end(d) {
  if (!d3.event.active) simulation.alphaTarget(0);
  d.fx = null;
  d.fy = null;
}

// Zoom functions
function zoom_actions(){
    g.attr("transform", d3.event.transform)
}

function tickActions() {
    // update node positions each tick of the simulation
 node.attr("transform", function(d) {
  return "translate(" + d.x + "," + d.y + ")"
 });
    // update link positions
 link
  .attr("x1", function(d) { return d.source.x; })
  .attr("y1", function(d) { return d.source.y; })
  .attr("x2", function(d) { return d.target.x; })
  .attr("y2", function(d) { return d.target.y; });
  }
<svg width="600" height="600"></svg>
<script src="https://d3js.org/d3.v4.min.js"></script>

How can I change it such that the minimum distance on the x-axis is based on rectWidth while minimum distance on the y-axis is based on rectHeight? Also, they should not be able to overlap diagonally.

A: You should change your simulation like this :
simulation
  .force("charge_force", charge_force)
  .force("center_force", center_force)
  .force("links",link_force)
  .force('y', d3.forceY(height / 2).strength(0.10));

Basically it will increase gravity for the Yaxis but not for the Xaxis.
More information on : https://github.com/d3/d3-force/blob/master/README.md#forceY
Updated fiddle : https://jsfiddle.net/oesgnzho/3/


text:
Q: why do i get the highest valued number in my array as my first element when i use bubble sort? I'm sorting some simple numbers using bubble sort with javascript and jquarry. The problem is that the number with the highest value will be sorted as the first element in the array.
Enter some numbers that need to be sorted  :

     Sort

<script>

    $(document).ready(function () {
        $("button").click(function () {

        var numbers = document.getElementById("numbers").value;
        var arr = numbers.split(",");
        var temp;

        arr.forEach(function(e) {
          arr.forEach(function (a, b) {

            if (arr[a] > arr[b]) {
              temp = arr[a];
              arr[a] = arr[b];
              arr[b] = temp;

            }
          })
        })

        $("h1").text(arr.join());
      })
    })

</script>

My input was 2,4,3,1 and i expected to get 1,2,3,4 as my output. But the end result was 4,1,2,3 .
There is no error message

A: Let me first fix your code, but you could write this sorting code using just for() loop. Anyway, your mistake is the assumption of a and b both as index, but you are wrong here. a is the element from the array, where b corresponds to the index of a in the arr. So a fix is:

var arr = [2, 4, 3, 1]

arr.forEach(function(e) {
    arr.forEach(function(a, i) {

        if (i + 1 <= arr.length && a > arr[i + 1]) {
            // You compare the current element a with the next element
            // at position i + 1 until i + 1 refers position outside the
            // arr bound.

            temp = a;
            arr[i] = arr[i + 1];
            arr[i + 1] = temp;

        }
    })
})

console.log(arr)

If you check the method definition you will get to know which parameter stands for what:

arr.forEach(callback(currentValue [, index [, array]])[, thisArg]);
callback is invoked with three arguments:

*

*the value of the element

*the index of the element

*the Array object being traversed

The temp variable is not needed here either, you can reduce code to below if you understand what temp is for there by removing temp.
arr[i] = arr[i + 1];
arr[i + 1] = a;


text:
Q: how to make a button on a popup window that closes that popup window I have made a popup window with a button that's supposed to close the window. However, it does not work. Here is the code:
 winpopup.document.write(<INPUT TYPE = "BUTTON" Value = "Close Window" onClick = "closeWindow();">)

 function closeWindow(){
    winpopup.close();
 }

A: Winpopup doesn't have closeWindow() method. Use opener's.
function closeWindow(){
    opener.winpopup.close();
}


text:
Q: ScaleOut vs Ncache? I'm evaluating both these third-party vendors for distributed cache. Has anyone already compared them and formed an opinion on which is better?

A: I just came this post and would like to add that I am an old user of NCache and have a very good expereince with the working and performance of this product.
William L. Bain's post was meant to give differences between the two reputed caching solutions but I dont see any mention about NCache so here are some features of NCache that probably will make it distinct from ScaleOut.

*

*NCache offers partioned-replica cache that gives you scalability through partitioning, reliability through replication and availability of data against data loss and node failure. You also have the option to use replicated, partitioned, local , client or mirror cache with NCache

*NCache allows you use read and write-through so that you can be sure your cache is never out of sync from database.

*With the Bulk operations features, you can combine multiple get or write calls, this reduces bandwidth consumptions and the operation is much faster than making many individual get or write calls.

*Event and polling based synchronization

*Object queries

*Pre-load cache with data

*Auto-start of cache on windows startup

*NCache also gives NHibernate support

*Client cache for faster results. The client cache sits with the application and hold most frequent used data. The client cache is synced with the master cache and  provides efficient and better read/write results

*Enahnced security features
NCache is also great for ASP.NET sessions. It lets you cache your session-state in cache without needing any code change. All you need is to modify Web.config and you are ready to use caching for your ASP.NET application.
NCache comes with a monitoring utility called NCache Monitor that lets you see Topology used, cache uptime, items count, port no, events history and more.
The NCache Manager (a GUI tool for managing caches) also integrates a statitics window where you can monitor real-time cache activity including evictions, additions, reads, writes, updates, expirations, read and write through requests and more.


text:
Q: Returning the first possible node's inner text in a XML file I wrote a method that specificly searches for a given full xpath and returns the inner text. But since the files I am working on all have unique node names, I want to do it somehow that only passing the node name do the job.
How my code looks like at the moment:
public string FileInfo(string info)
{
    switch (info)
    {
        //FileInfo
        case "fileCreator":
            fileCreator = ztr.SelectSingleNode("//Document/FileInfo/Creator").InnerText;
            return fileCreator;
        case "fileName":
            fileName = ztr.SelectSingleNode("//Document/FileInfo/Name").InnerText;
            return fileName;
      //And so on with lots of other cases!!!

How can I make it somehhow that it searches for the first occurance of info string that is a xml node so I dont have to be stupid and write all these switch statements...
UPDATE
please note not all the stuff I want are located in FileInfo node...I want the method to search for the node I pass to it! Or better to say I want to pass the name of the node itself into this method and get its value. Sorry if I was confusing prior to this edit!
some more examples in the xml file:
/Document/RuntimeInfo/Operator

So I want to pass in "Operator" into my method and I get its value! should be up to the method to discover the correct path. the pats are unique so it wouldnt be a bad idea to implement this method.

A: won't this do the job?
var value = ztr.SelectSingleNode(string.Format("//{0}", info).InnerText;

A: return ztr.SelectSingleNode(string.Format("//Document/FileInfo/{0}",
                            info.Replace("file", "").InnerText;

EDIT
if the searched node is always at the same nesting level, you could probably use a wild card
return ztr.SelectSingleNode(string.Format("//Document/*/{0}",
                                info).InnerText;

By the way, in your example, you pass fileCreator to find the Creator Node. Typo ?

A: Try,
return ztr.SelectSingleNode(string.Format("//{0}[contains(name(..),'Info')]", info));

If info is Operator it will return the first Operator node that has a parent node with Info in its name.

A: Use this XPath:
//Document/FileInfo/[0]

and your code can be like this:
public string FileInfo(string info)
{
    return ztr.SelectSingleNode("//Document/FileInfo/[0]").InnerText;
}

See more about xpath here.


text:
Q: Where does the systemd builtin 'kmod' gets the module aliases from udev is loading the necessary driver modules when plugging in a hotplug-capable device. This is done by the following udev-rule
DRIVER!="?*", ENV{MODALIAS}=="?*", RUN{builtin}="kmod load $env{MODALIAS}"

Therefore kmod gets invoked by e.g. kmod load hid:b0005g0001v0000045Ep000002E0
The source of the builtin kmod is documented here
hid:b0005g0001v0000045Ep000002E0 is just an alias for a module like hid_xpadneo.
I know that there is generated a file called modules.alias in /usr/lib/modules/$(uname -r)/modules.alias where those aliases are listed like this:
alias hid:b0005g*v0000045Ep000002E0 hid_xpadneo
alias hid:b0005g*v0000045Ep000002FD hid_xpadneo

This file is generated out of all drivers and their MODULE_DEVICE_TABLEs while compile-time.
Unfortunately I cannot find where exactly kmod does read in that file or where it gets the alias information from.
Therefore: How does kmod know which alias stands for which module?

A: From systemd/udev-builtin-kmod.c:
static int builtin_kmod_init(void) {
        ...
        kmod_load_resources(ctx);
        ...
}

From kmod/libkmod.c:
static struct _index_files {
    const char *fn;
    const char *prefix;
} index_files[] = {
    [KMOD_INDEX_MODULES_DEP] = { .fn = "modules.dep", .prefix = "" },
    [KMOD_INDEX_MODULES_ALIAS] = { .fn = "modules.alias", .prefix = "alias " },
    [KMOD_INDEX_MODULES_SYMBOL] = { .fn = "modules.symbols", .prefix = "alias "},
    [KMOD_INDEX_MODULES_BUILTIN] = { .fn = "modules.builtin", .prefix = ""},
};

...

KMOD_EXPORT int kmod_load_resources(struct kmod_ctx *ctx)
{
    for (i = 0; i < _KMOD_INDEX_MODULES_SIZE; i++) {
        ...
        snprintf(path, sizeof(path), "%s/%s.bin", ctx->dirname,
                            index_files[i].fn);
        ctx->indexes[i] = index_mm_open(ctx, path,
                        &ctx->indexes_stamp[i]);
        ...
    }
}

From kmon/libkmod-index.c:
struct index_mm *index_mm_open(struct kmod_ctx *ctx, const char *filename,
                        unsigned long long *stamp)
{
    ...
    if ((fd = open(filename, O_RDONLY|O_CLOEXEC)) < 0) {
    ...
}

kmod reads and indexes all the possible files modules.dep modules.alias modules.symbols and modules.builtin and it get's it's alias information from that files.
Then later in udev-buildin-kmod.c:
static int builtin_kmod(sd_device *dev, int argc, char *argv[], bool test) {
        ...
        for (i = 2; argv[i]; i++)
                (void) module_load_and_warn(ctx, argv[i], false);
        ...
}

And from systemd/module-util.c:
int module_load_and_warn(struct kmod_ctx *ctx, const char *module, bool verbose) {
    ...
    r = kmod_module_new_from_lookup(ctx, module, &modlist);
    if (r < 0)
            return log_full_errno(verbose ? LOG_ERR : LOG_DEBUG, r,
                                  "Failed to lookup module alias '%s': %m", module);

    ...
}

And inside kmod_module_new_from_lookup the lookup for module alias is performed, ie. the data read into kmod object is searched through.


text:
Q: Xamarin - break on handled exceptions I'm using Xamarin on my Mac, and I want to break on all exceptions. For that, I go to Run / Exceptions, and I select everything.
But now, Xamarin breaks in assembly code, which I don't want. I have checked in general preferences / debugger, the "debug project code only" is checked.
How do I tell Xamarin to only break on user code ?
I'm using Xamarin Studio 5.0.1 on Mac OS 10.9.3
Thank you!
Edit
To be clear, if I select all exceptions (or just System.Exception, it makes no difference) in run / exceptions, and then I try to debug a unit test that I know throws a handled exception somewhere, I get this:

If I click "continue execution", I get a thousand more exceptions. I don't care about Mono exceptions, I only want exceptions thrown from the code I write and the libraries I use.

A: *

*There's no need to select everything, just select System.Exception.

*It's not possible to stop on only exceptions that occur in user code. The setting "Debug project code only" defines whether the debugger will step into or step over calls into framework code.


text:
Q: Script não funciona no IE mas funciona nos outros navegadores Script não funciona no IE mas funciona normalmente nos outros navegadores, o erro ocorre em: jQuery(central).prop("disabled", false); e a mensagem que recebo é:

SCRIPT5009: 'central' não está definido.

Já tentei .prop e .attr.
JavaScript:
function carregarCentrais() {
  if (jQuery("#selectEmissor").val() != -1) {
    jQuery(central).prop("disabled", false);
    central.setAttribute('class', 'input g270');
    jQuery("select#central option").remove();
    var selectCentral = jQuery('#central');
    jQuery("#central").val(-1);
    if (jQuery("#selectEmissor").val() != null) {
      jQuery.ajax({
        type: "get",
        url: "preencheCentrais.do",
        data: 'selectEmissor=' + jQuery("#selectEmissor").val(),
        success: function(listaCentrais) {
          jQuery.each(listaCentrais, function(i, central) {
            selectCentral.append('<option value="' + central.codigo + '">' + central.descricao + '</option>');
          });
          jQuery("select#central").prepend("<option value='-1' selected='selected'></option>");
        },
        error: function() {
          alert("Erro ao pesquisar central pelo emissor");
        }
      });
    }
  } else {
    central.setAttribute('class', 'input g270 read-only');
    jQuery("select#central option").remove();
    jQuery(central).prop("disabled", true);
  }
  sucursal.setAttribute('class', 'input g270 read-only');
  jQuery("select#sucursal option").remove();
  jQuery(sucursal).prop("disabled", true);
}

HTML:
<td>
    <springform:select id="central" class="input g270 read-only" path="extratoLancamento.central" value="${form.extratoLancamento.central}" onchange="carregarSucursais();" style="width: 250px;" disabled="true"></springform:select>
</td>

A: Em alguns browsers pode aceder-se a elementos diretamente com o id, ou seja: havendo um elemento com id "central" ele pode ser acedido como uma variável global window.central. Isso é muito má ideia (já falei sobre isso aqui) e alguns browsers bloqueiam isso.
Em vêz de jQuery(central) deves usar jQuery('#central') que é um seletor CSS de id válido e vai selecionar o elemento que tens com esse id.


text:
Q: What should i have on windows to use std::mutex? I'm getting error on Windows 10 64-bits when trying to use the C++ std::mutex. The code was basically written for Linux but I'm trying to port it to Windows. (You can see compiler line in the error message that I added below.)
This is my code:
#ifndef UNTITLED_LIBRARY_H
#define UNTITLED_LIBRARY_H

#include <sys/types.h>
#include <Winsock2.h>
#include <mutex>
#include <thread>

class TCPServer
{
    static std::mutex mt;
};

#endif //UNTITLED_LIBRARY_H

Here is the error message:

g++ -Wall -std=c++14  -I./ library.h  -o libSimpleNetwork.so -fPIC -shared
library.h:11:17: error: 'mutex' in namespace 'std' does not name a type
   11 |     static std::mutex mt;
      |                 ^~~~~
library.h:8:1: note: 'std::mutex' is defined in header '<mutex>'; did you forget to '#include <mutex>'?
    7 | #include <thread>
  +++ |+#include <mutex>
    8 |

A: So the answer to this issue is to install mingw64 (not mingw32!): https://sourceforge.net/projects/mingw-w64/
This includes the posix x86_64-posix-seh that gcc needs for libstd


text:
Q: Echoing volume letter and volume name without WMIC I'm working on a WinPE disk which requires that I list the letters and labels of a disk in command prompt to the user. Unfortunately, WMIC logicaldisk ...  gives me an error in my WinPE environment, so I have pieced together a few lines of batch which "replicate" what WMIC does. The code is as follows:
for /f "delims=" %%i in ('echo :') do set colon=%%i
set drivetmp=%%a
set driveletter=%drivetmp%%colon%

echo Listing drives:
for %%a in (a b c d e f g h i j k l m n o p q r s t u v w x y z) do (
    fsutil fsinfo volumeinfo %driveletter% > tmpfile.t
    find "Volume Name" tmpfile.t >nul && set /p %vname% =< tmpfile.t
    find "Volume Name" tmpfile.t >nul && echo . Drive Letter: %driveletter% ..... %vname%
    del /q tmpfile.t
)

The code "works", however, for every line, it prints the same %vname% variable. For example, if my C: drive is named Deployed Drive C and I have drives C, D, E, F, H and I, the output will be like this:
C:\>test.cmd
Listing drives:
. Volume Label: c: ..... Volume Name : Deployed Drive C
. Volume Label: d: ..... Volume Name : Deployed Drive C
. Volume Label: e: ..... Volume Name : Deployed Drive C
. Volume Label: f: ..... Volume Name : Deployed Drive C
. Volume Label: h: ..... Volume Name : Deployed Drive C
. Volume Label: i: ..... Volume Name : Deployed Drive C

The drive letter changes as expected, the missing drives are excluded as expected, and if I type the commands manually, it also works! However, nomatter what I change the variables %vname% or %a% to, the script still performs the same. Is there something glaringly obvious that I am missing?

A: See if this does what you require:
@echo off
echo Listing drives:
for %%a in (a b c d e f g h i j k l m n o p q r s t u v w x y z) do (
    if exist "%%a:\" (
       for /f "tokens=5,*" %%b in ('vol %%a: ^|find /i /v " serial number "') do echo Drive Letter: %%a:      Volume Name: %%c
    )
)
pause


text:
Q: How To Check If Username Is Already Exists In a MySQL Table show hidden password field this is my html form .
<form id="login" action="">

            <input name="username" id="username" value="" maxlength="100" type="text" />

username:

            <input name="password" id="password" value="" type="password" />

password:

            <input type="submit" name="go" value="login" class="main_btn1" />

        </form>

i want to check if username already exists in mysql database show hidden password field if username not exists transmission user For example index.php . i want to use ajax check

A: 1)Create a new folder in your Root directory. Put inside it the 3 following files:
2)Create a HTML file name it "index.php" then copy/paste this code inside it and save it.
<!DOCTYPE html>

    <meta charset="utf-8">

    <title>Username check</title>

    <form id="login" action="" method="post">

username:

        <input name="username" id="username" value="" maxlength="100" type="text" onkeyup="checkUsername();" />

password:

        <input name="password" id="password" value="" type="password" />

      <input type="submit" name="go" value="login" class="main_btn1" />
    </form>

3)Create a javascript file and name it "check_username.js", then copy/paste this code inside it and save it.
$.customPOST = function(data,callback){
    $.post('check_username.php',data,callback,'json');
}
//when typing, the script checks if the username exists
function checkUsername() {
  $.customPOST({username: $('#username').val()},function(r){
    //username exists
    if(r.exists == 'yes'){
     $( "#lay_pw" ).toggle(400,function(){});
    }
    else{
     $( "#lay_pw" ).css("display", "none");
    }
  });
}

4)Create a PHP file, name it "check_username.php", copy/paste this code inside it and save it.
<?php
$link = mysql_connect('localhost','root','');
mysql_select_db('database');
$response = 'no';
if(isset($_POST['username']) && trim($_POST['username']) != ''){
 $query = mysql_query("SELECT * FROM table WHERE username = '".mysql_escape_string(trim($_POST['username']))."'", $link);
 if(mysql_num_rows($query) > 0){
  $response = 'yes';
 }
}
echo json_encode(array('exists' => $response));
?>

5)Use this sample database (i used it for testing this stuff)
CREATE TABLE IF NOT EXISTS `users` (
  `user` varchar(50) NOT NULL,
  `password` varchar(32) NOT NULL,
  PRIMARY KEY (`user`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;

INSERT INTO `users` (`user`, `password`) VALUES
('test1', '5a105e8b9d40e1329780d62ea2265d8a'),
('test2', 'ad0234829205b9033196ba818f7a872b'),
('alpha', '2c1743a391305fbf367df8e4f069f9f9'),
('beta', '987bcab01b929eb2c07877b224215c92');

A: this is my check.php file
<?php
session_start();
include_once('inc/dbConnect.inc.php');
$message=array();
if(isset($_POST['username']) && !empty($_POST['username'])){
    $username=mysql_real_escape_string($_POST['username']);
}else{
    $message[]='Please enter username';
}

if(isset($_POST['password']) && !empty($_POST['password'])){
    $password=mysql_real_escape_string($_POST['password']);
}else{
    $message[]='Please enter password';
}

$countError=count($message);

if($countError > 0){
     for($i=0;$i<$countError;$i++){
              echo ucwords($message[$i]).'

';
     }
}else{
    $query="select * from user where username='$username' and password='$password'";

    $res=mysql_query($query);
    $checkUser=mysql_num_rows($res);
    if($checkUser > 0){
         $_SESSION['LOGIN_STATUS']=true;
         $_SESSION['username']=$username;
         echo 'correct';
    }else{
         echo ucwords('please enter correct user details');
    }
}
?>


text:
Q: Using dynamic references in AWS CloudFormation I am trying to create an IAM Role using CloudFormation. The following snippet shows the trust policy :
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Principal": {
        "Federated": "arn:aws:iam::1234567890123:oidc-provider/oidc.eks.us-east-1.amazonaws.com/id/89ABCDWEFGHRRUUUR4DDF70C"
      },
      "Action": "sts:AssumeRoleWithWebIdentity",
      "Condition": {
        "StringEquals": {
          "oidc.eks.us-east-1.amazonaws.com/id/89ABCDWEFGHRRUUUR4DDF70C:sub": "system:serviceaccount:kube-system:aws-load-balancer-controller"
        }
      }
    }
  ]
}

I want to make it dynamic, as in it should pick the value for OIDC provider from either mappings or parameters.
Here is what I have done so far:
"AssumeRolePolicyDocument": {
          "Version": "2012-10-17",
          "Statement": [
            {
              "Effect": "Allow",
              "Principal": {
                "Federated": {
                  "Fn::Join": [
                    "",
                    [
                      {
                        "Fn::Sub": "arn:aws:iam::${AWS::AccountId}:oidc-provider/"
                      },
                      {
                        "Fn::FindInMap": [
                          "Environments",
                          {
                            "Ref": "EnvironUsed"
                          },
                          "OIDCProvider"
                        ]
                      }
                    ]
                  ]
                }
              },
              "Action": "sts:AssumeRoleWithWebIdentity",
              "Condition": {
                "StringEquals": {
                  "oidc.eks.us-east-1.amazonaws.com/id/89738A59036B9EB2704B9ABC44DDF70C:sub" : "system:serviceaccount:kube-system:aws-load-balancer-controller"
                }
              }
            }
          ]
        }

I am unable to make the last part (Condition section where OIDC provider is mentioned) dynamic. The JSON invalidates when I try to include a Fn::Join within curly braces in place of "oidc.eks.us-east-1.amazonaws.com/id/89ABCDWEFGHRRUUUR4DDF70C:sub"


text:
Q: How to cancel/abort jQuery AJAX request? I've an AJAX request which will be made every 5 seconds. But the problem is before the AJAX request if the previous request is not completed I've to abort that request and make a new request.
My code is something like this, how to resolve this issue?
$(document).ready(
    var fn = function(){
        $.ajax({
            url: 'ajax/progress.ftl',
            success: function(data) {
                //do something
            }
        });
    };

    var interval = setInterval(fn, 500);
);

A: When you make a request to a server, have it check to see if a progress is not null (or fetching that data) first. If it is fetching data, abort the previous request and initiate the new one.
var progress = null

function fn () {
    if (progress) {
        progress.abort();
    }
    progress = $.ajax('ajax/progress.ftl', {
        success: function(data) {
            //do something
            progress = null;
        }
    });
}

A: I know this might be a little late but i experience similar issues where calling the abort method didnt really aborted the request. instead the browser was still waiting for a response that it never uses.
this code resolved that issue.
 try {
        xhr.onreadystatechange = null;
        xhr.abort();
} catch (e) {}

A: The jquery ajax method returns a XMLHttpRequest object. You can use this object to cancel the request.
The XMLHttpRequest has a abort method, which cancels the request, but if the request has already been sent to the server then the server will process the request even if we abort the request but the client will not wait for/handle the response.
The xhr object also contains a readyState which contains the state of the request(UNSENT-0, OPENED-1, HEADERS_RECEIVED-2, LOADING-3 and DONE-4). we can use this to check whether the previous request was completed.
$(document).ready(
    var xhr;

    var fn = function(){
        if(xhr && xhr.readyState != 4){
            xhr.abort();
        }
        xhr = $.ajax({
            url: 'ajax/progress.ftl',
            success: function(data) {
                //do something
            }
        });
    };

    var interval = setInterval(fn, 500);
);

A: Why should you abort the request?
If each request takes more than five seconds, what will happen?
You shouldn't abort the request if the parameter passing with the request is not changing.
eg:- the request is for retrieving the notification data.
In such situations, The nice approach is that set a new request only after completing the previous Ajax request.
$(document).ready(

    var fn = function(){

        $.ajax({
            url: 'ajax/progress.ftl',
            success: function(data) {
                //do something
            },

            complete: function(){setTimeout(fn, 500);}
        });
    };

     var interval = setTimeout(fn, 500);

);

A: jQuery:
Use this as a starting point - as inspiration.
I solved it like this:
 (this is not a perfect solution, it just aborts the last instance and is WIP code)
var singleAjax = function singleAjax_constructor(url, params) {
    // remember last jQuery's get request
    if (this.lastInstance) {
        this.lastInstance.abort();  // triggers .always() and .fail()
        this.lastInstance = false;
    }

    // how to use Deferred : http://api.jquery.com/category/deferred-object/
    var $def = new $.Deferred();

    // pass the deferrer's request handlers into the get response handlers
    this.lastInstance = $.get(url, params)
        .fail($def.reject)         // triggers .always() and .fail()
        .success($def.resolve);    // triggers .always() and .done()

    // return the deferrer's "control object", the promise object
    return $def.promise();
}

// initiate first call
singleAjax('/ajax.php', {a: 1, b: 2})
    .always(function(a,b,c) {console && console.log(a,b,c);});

// second call kills first one
singleAjax('/ajax.php', {a: 1, b: 2})
    .always(function(a,b,c) {console && console.log(a,b,c);});
    // here you might use .always() .fail() .success() etc.

A: You can use jquery-validate.js . The following is the code snippet from jquery-validate.js.
// ajax mode: abort
// usage: $.ajax({ mode: "abort"[, port: "uniqueport"]});
// if mode:"abort" is used, the previous request on that port (port can be undefined) is aborted via XMLHttpRequest.abort()

var pendingRequests = {},
    ajax;
// Use a prefilter if available (1.5+)
if ( $.ajaxPrefilter ) {
    $.ajaxPrefilter(function( settings, _, xhr ) {
        var port = settings.port;
        if ( settings.mode === "abort" ) {
            if ( pendingRequests[port] ) {
                pendingRequests[port].abort();
            }
            pendingRequests[port] = xhr;
        }
    });
} else {
    // Proxy ajax
    ajax = $.ajax;
    $.ajax = function( settings ) {
        var mode = ( "mode" in settings ? settings : $.ajaxSettings ).mode,
            port = ( "port" in settings ? settings : $.ajaxSettings ).port;
        if ( mode === "abort" ) {
            if ( pendingRequests[port] ) {
                pendingRequests[port].abort();
            }
            pendingRequests[port] = ajax.apply(this, arguments);
            return pendingRequests[port];
        }
        return ajax.apply(this, arguments);
    };
}

So that you just only need to set the parameter mode to abort when you are making ajax request.
Ref:https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.14.0/jquery.validate.js

A: Create a function to call your API. Within this function we define request callApiRequest = $.get(... - even though this is a definition of a variable, the request is called immediately, but now we have the request defined as a variable. Before the request is called, we check if our variable is defined typeof(callApiRequest) != 'undefined' and also if it is pending suggestCategoryRequest.state() == 'pending' - if both are true, we .abort() the request which will prevent the success callback from running.
// We need to wrap the call in a function
callApi = function () {

    //check if request is defined, and status pending
    if (typeof(callApiRequest) != 'undefined'
        && suggestCategoryRequest.state() == 'pending') {

        //abort request
        callApiRequest.abort()

    }

    //define and make request
    callApiRequest = $.get("https://example.com", function (data) {

        data = JSON.parse(data); //optional (for JSON data format)
        //success callback

    });
}

Your server/API might not support aborting the request (what if API executed some code already?), but the javascript callback will not fire. This is useful, when for example you are providing input suggestions to a user, such as hashtags input.
You can further extend this function by adding definition of error callback - what should happen if request was aborted.
Common use-case for this snippet would be a text input that fires on keypress event. You can use a timeout, to prevent sending (some of) requests that you will have to cancel .abort().

A: You should also check for readyState 0. Because when you use xhr.abort() this function set readyState to 0 in this object, and your if check will be always true -  readyState !=4
$(document).ready(
    var xhr;

    var fn = function(){
        if(xhr && xhr.readyState != 4 && xhr.readyState != 0){
            xhr.abort();
        }
        xhr = $.ajax({
            url: 'ajax/progress.ftl',
            success: function(data) {
                //do something
            }
        });
    };

    var interval = setInterval(fn, 500);
);