text:
Q: Enqueueing scripts and styles multiple CPTS I am trying to load several scripts and stylesheets into a plugin I am creating. I want to load scripts into multiple CPTs within admin. I have got this far:
function fhaac_admin_enqueue_scripts(){
    global $pagenow, $typenow;

    if ( ($pagenow == 'post.php' || $pagenow == 'post-new.php') && $typenow == 'fhaac' ){}
}

The scripts are being loaded into the fhaac, but nothing else. I am not sure how to add multiple CPTs. I tried adding them in an array, but it didn't work.
Help would be greatly appreciated.
Cheers

A: There is a built-in function that you can use, instead of globals. The get_current_screen() function allows you to get the information associated with the current page.
One of its return values is post_type. So you can check against an array of post types to see if anyone matches.
function fhaac_admin_enqueue_scripts(){
    $screen = get_current_screen();
    if (
        in_array( $screen->post_type, array('fhaac','blabla')) &&
        $screen->base == 'post'
     ) { // Do something }
}

A: There's a really simple work around:
Load it everywhere and only run the code if the page matches
For example, on my site I have a CPT named projects and on the body tag I have the following:
<body
    class="wp-admin wp-core-ui js   jetpack-connected  edit-php auto-fold admin-bar post-type-project branch-4-8 version-4-8 admin-color-fresh locale-en-us multisite customize-support sticky-menu svg">

So I know that my posts listing will match body.edit-php, and body.post-type-project
So for CSS:
body.post-type-project.edit-php .... {
    ....
}

And I can do the same check in javascript be it with jQuery


text:
Q: Setting all struct pointer members to NULL If I set a pointer to a struct to point to a block of memory via malloc, will all the members initialize to their respective default values? Such as int's to 0 and pointer's to NULL? I'm seeing that they do based on this sample code I wrote, so I just wanted someone to please confirm my understanding. Thanks for the input.
#include <stdio.h>
#include <ctype.h>
#include <stdbool.h>
#include <stdlib.h>

typedef struct node
{
    bool value;
    struct node* next[5];
}
node;

int main(void)
{
    node* tNode = malloc(sizeof(node));

    printf("value = %i\n", tNode->value);

    for (int i = 0; i < 5; i++)
    {
        if (tNode->next[i] == NULL)
            printf("next[%i] = %p\n", i, tNode->next[i]);
    }
}

A: malloc() function never initializes the memory region. You have to use calloc() to specifically initialize a memory region to zeros. The reason you see initialized memory is explained here.

A: No. malloc never initializes the allocated memory. From the man page:

The memory is not initialized.

From the C standard, 7.20.3.3 The malloc function:

The malloc function allocates space for an object ... whose value is indeterminate.

A: You can use static const keywords to set the member variables of your struct.
#include
struct rabi
{
int i;
float f;
char c;
int *p;
};
int main ( void )
{

static const struct rabi enpty_struct;
struct rabi shaw = enpty_struct, shankar = enpty_struct;

printf ( "\n i = %d", shaw.i );
printf ( "\n f = %f", shaw.f );
printf ( "\n c = %d", shaw.c );
printf ( "\n p = %d",(shaw.p) );

printf ( "\n i = %d", shankar.i );
printf ( "\n f = %f", shankar.f );
printf ( "\n c = %d", shankar.c );
printf ( "\n p = %d",(shankar.p) );
return ( 0 );
}

Output:

 i = 0
 f = 0.000000
 c = 0
 p = 0

 i = 0
 f = 0.000000
 c = 0
 p = 0

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to apply a function on combining two columns in pandas dataframe? I have two columns "ColA" and "ColB" in a pandas dataframe like below:

I want apply a custom function on ColA and ColB, and update another column ColC. The custom function is like below:
def customFunc(file_name, pattern):
    match_index = -1
    with open(file_name) as f:
      data = f.read()
      for n, line in enumerate(data):
        match_index = line.find(pattern)
        if match_index != -1:
          break

    return match_index

For each row of the dataframe, the file_name will come from ColA and pattern will come from ColB and the returned match_index will be updated in ColC like below:

I have tried like below but the value of ColA and ColB of each row is not passed into the custom function.
df["ColC"] = df[["ColA", "ColB"]].apply(lambda x: customFunc(x.ColA, x.ColB))

How to pass ColA and ColB of each row into the custom function using apply()?

A: using axis = 1 did the trick.
df["ColC"] = df[["ColA", "ColB"]].apply(lambda x: customFunc(x.ColA, x.ColB), axis = 1)


text:
Q: What is the difference between "where are you living" and "where do you live" If I want to ask a friend of mine where he is living could I use both sentences below in the same context?

1 where are you living
2 where do you live

If both are wrong, then what is the difference between 1 and 2?

A: They are both OK English.
'Where are you living?' would be used more often when you know the other person is living somewhere temporarily for some reason, or does not have a fixed home. The verb form is the present continuous which we can use to talk about something which we think is temporary, for example: I'm working in London for the next two weeks.
'Where do you live?' would be used for a general enquiry about a person's home location, and uses the simple present.


text:
Q: Nunit c# csv testsource I am trying pass an argument to a NUnit test after reading a CSV file i.e.
[Test, TestCaseSource(typeof(RegistrationData), "GetTestData")]
public void RegisterUserTest(RegistrationData registrationData)
    {

        RegisterNewUser registration = new RegisterNewUser(this.driver);
        this.driver.Navigate().GoToUrl(baseURL + "/mercuryregister.php");

        registration.registerNewUser(registrationData);
    }

but I get the error:

System.InvalidCastException : Unable to cast object of type
  'RegisterUser.RegistrationData' to type
  'System.Collections.IEnumerable'.RegisterUser.UserRegistrationTest.RegisterUserTest

 private RegistrationData GetTestData()
    {
        DataTable dt = DataTable.New.ReadCsv(@"C:\datafolder\regdata.csv");
        RegistrationData registrationData = new RegistrationData();

        foreach (Row row in dt.Rows)
        {

            registrationData.setfirstName(row["FirstName"]);
            registrationData.setfirstName(row["LastName"]);
            registrationData.setPhone(row["Phone"]);
            registrationData.setUserName(row["UserName"]);
            registrationData.setAddress1(row["Add1"]);
            registrationData.setAddress2(row["Add2"]);
            registrationData.setCity(row["City"]);
            registrationData.setState(row["State"]);
            registrationData.setPostalcode(row["Postalcode"]);
            registrationData.setCountry(row["Country"]);
            registrationData.setEmail(row["Email"]);
            registrationData.setPassword(row["Password"]);
            registrationData.setConfimPassword(row["Cpassword"]);

        }
        // return new RegistrationData[][] { { registrationData } };
        return registrationData;
    }

A: Example of the ModelTestCaseSource:
public class ModelTestCaseSource
{
    public IEnumerable<TestCaseData> GetTestCases()
    {
        DataTable dt = DataTable.New.ReadCsv(@"C:\datafolder\regdata.csv");

        foreach (Row row in dt.Rows)
        {
            var registrationData = new RegistrationData();

            registrationData.setfirstName(row["FirstName"]);
            registrationData.setfirstName(row["LastName"]);
            registrationData.setPhone(row["Phone"]);
            registrationData.setUserName(row["UserName"]);
            registrationData.setAddress1(row["Add1"]);
            registrationData.setAddress2(row["Add2"]);
            registrationData.setCity(row["City"]);
            registrationData.setState(row["State"]);
            registrationData.setPostalcode(row["Postalcode"]);
            registrationData.setCountry(row["Country"]);
            registrationData.setEmail(row["Email"]);
            registrationData.setPassword(row["Password"]);
            registrationData.setConfimPassword(row["Cpassword"]);

            yield return new TestCaseData(new object[] { registrationData });
        }
    }
}

Usage:
[Test, TestCaseSource(typeof(ModelTestCaseSource), "GetTestCases")]
public void RegisterUserTest(RegistrationData registrationData)
{

    RegisterNewUser registration = new RegisterNewUser(this.driver);
    this.driver.Navigate().GoToUrl(baseURL + "/mercuryregister.php");

    registration.registerNewUser(registrationData);
}


text:
Q: Where does the Rust macOS pkg installer install to? I want to try the Eclipse-based Rust IDE RustDT and it asks for the Rust installation and source directories. I assume the source directory is relative to the installation directory, but I have no clue where it is installed.

A: Rust executable binaries (rustc, cargo, rustdoc) are installed to /usr/local/bin by default with the macOS installer. Rust libraries are installed to /usr/local/lib/rustlib/.
To use RustDT, you should install Racer following the instructions from the repository.
After Racer is installed, you should configure the path to rustc, racer, and the source files for Rust in the RustDT preferences.

A: I'm not sure of this, but I think you need to clone the source seperately. RustDT uses racer (I think) which needs uncompiled source code.
Cloning this branch on github and pointing to it should do the trick. No need to build.

A: The accepted answer is outdated. As of 9/29/2017 the following works for RustDT on a MacBook Pro running Sierra and using Eclipse Neon.
Install the configuration tools per this guide. As you install each package, the last line of output before your terminal exits the process is the directory you need to use for the Rust preferences in RustDT. Take note of these.
(I used the nightly build installer because there was a compiler error when installing 'Racer'. Your experience may vary.)
In the Rust preferences, configure as follows and Eclipse will let you know if you're wrong. If you took notes on your installation locations you should be fine. Note: I've blotted out my username on my computer because it's a work machine. It's /Users/your_username/path


text:
Q: MVC Form Submit ModelState Invalid- I am wanting to further my MVC learning. I do not understand why my form won't validate; well, actually I can read the message and it is straightforward enough but I can't find where I'm slipping up.
I'm only including what is relevant to the error message.
My model is this:
[Validator(typeof(ExtForumValidator))]
public partial class ExtrnlSubsModel : BaseEntityModel
{
   .....snip......
    public int ExtForumBoardId { get; set; }
}

My Validator:
public ExtForumValidator(ILocalizationService localizationService)
{
   RuleFor(x => x.ExtForumBoardId)
  .NotEqual(0).WithMessage(localizationService.GetResource("ExternalForumBoards.Fields.AvailBoard.Required"));

}

Razor:
<td>
   @Html.DropDownListFor(model => model.ExtForumBoardId, Model.AvailableForumBoards)
   @Html.RequiredHint()
   @Html.ValidationMessageFor(model => model.AvailableForumBoards)
</td>

On submit all my other elements check out except this one has the ModelState error. For attempted value it shows as a string array???? 0,11 or 0,12 or 0,4 etc. It always has a zero and a comma prepended. The second number is correct as that is the id of the item selected in the drop down.
For exception it says null and for error message it says...well it says what I have for the validation message.
So it seems to me that it is getting hung up on this string array 0, stuff and I am at a loss as for where it comes from to go looking for the fix.


text:
Q: Can SimpleXMLElement::children() have multiple prefixes? For SimpleXMLElement::children() method, can I include multiple prefixes as parameters.
Consider following xml. Here, the children('air',true) method can get child elements with "air" as prefix. Similarly, with children('universal',true), I can get child elements with "universal" prefix.
<universal:AirCreateReservationRsp xmlns:universal="http://www.travelport.com/schema/universal_v42_0" xmlns:common_v42_0="http://www.travelport.com/schema/common_v42_0" xmlns:air="http://www.travelport.com/schema/air_v42_0" TraceId="trace" TransactionId="6A97EC390A07643C43916EB9FA2934A1" ResponseTime="6143">
    <universal:UniversalRecord LocatorCode="FUEV5F" Version="0" Status="Active">
        <common_v42_0:BookingTraveler Key="gr8AVWGCR064r57Jt0+8bA==" TravelerType="ADT" DOB="1957-05-12" Gender="M" ElStat="A">
            <common_v42_0:BookingTravelerName Prefix="Herr" First="Frederick" Last="Heinrich"/>
            <common_v42_0:DeliveryInfo>
                <common_v42_0:ShippingAddress Key="2wokqt8Q2BKAfRGAAAAAAA==" ElStat="A">
                    <common_v42_0:AddressName>Residence</common_v42_0:AddressName>
                    <common_v42_0:Street>Rossmarkt 6</common_v42_0:Street>
                    <common_v42_0:City>Frankfurt</common_v42_0:City>
                    <common_v42_0:State>HESSE</common_v42_0:State>
                    <common_v42_0:PostalCode>60311</common_v42_0:PostalCode>
                    <common_v42_0:Country>DE</common_v42_0:Country>
                    <common_v42_0:ProviderReservationInfoRef Key="2wokqt8Q2BKARSGAAAAAAA=="/>
                </common_v42_0:ShippingAddress>
            </common_v42_0:DeliveryInfo>
            <common_v42_0:PhoneNumber Key="2wokqt8Q2BKAdRGAAAAAAA==" Type="None" Location="FRA" CountryCode="069" Number="261111111" AreaCode="49" ElStat="A">
                <common_v42_0:ProviderReservationInfoRef Key="2wokqt8Q2BKARSGAAAAAAA=="/>
            </common_v42_0:PhoneNumber>
            <common_v42_0:Email Key="2wokqt8Q2BKAeRGAAAAAAA==" Type="Home" EmailID="test@travelport.com" ElStat="A">
                <common_v42_0:ProviderReservationInfoRef Key="2wokqt8Q2BKARSGAAAAAAA=="/>
            </common_v42_0:Email>
            <common_v42_0:Address Key="2wokqt8Q2BKAgRGAAAAAAA==" ElStat="A">
                <common_v42_0:AddressName>Residence</common_v42_0:AddressName>
                <common_v42_0:Street>Rossmarkt 6</common_v42_0:Street>
                <common_v42_0:City>Frankfurt</common_v42_0:City>
                <common_v42_0:State>HESSE</common_v42_0:State>
                <common_v42_0:PostalCode>60311</common_v42_0:PostalCode>
                <common_v42_0:Country>DE</common_v42_0:Country>
                <common_v42_0:ProviderReservationInfoRef Key="2wokqt8Q2BKARSGAAAAAAA=="/>
            </common_v42_0:Address>
        </common_v42_0:BookingTraveler>
        <common_v42_0:ActionStatus Key="2wokqt8Q2BKAoRGAAAAAAA==" Type="TAW" TicketDate="2019-06-20T16:42:00.000+04:00" ProviderReservationInfoRef="2wokqt8Q2BKARSGAAAAAAA==" ProviderCode="1G" ElStat="A"/>
        <universal:ProviderReservationInfo Key="2wokqt8Q2BKARSGAAAAAAA==" ProviderCode="1G" LocatorCode="GQJ1R4" CreateDate="2019-06-18T12:37:55.676+00:00" ModifiedDate="2019-06-18T12:37:55.676+00:00" HostCreateDate="2019-06-18" OwningPCC="62RD"/>\n
        <air:AirReservation LocatorCode="CAUJ2A" CreateDate="2019-06-18T12:37:55.104+00:00" ModifiedDate="2019-06-18T12:37:55.676+00:00">
            <common_v42_0:SupplierLocator SupplierCode="EY" SupplierLocatorCode="QIEPVA" ProviderReservationInfoRef="2wokqt8Q2BKARSGAAAAAAA==" CreateDateTime="2019-06-18T12:37:00.000+00:00"/>
            <common_v42_0:BookingTravelerRef Key="gr8AVWGCR064r57Jt0+8bA=="/>
            <common_v42_0:ProviderReservationInfoRef Key="2wokqt8Q2BKARSGAAAAAAA=="/>
            <air:AirSegment Key="RzO2Zt3R2BKAb+f9BAAAAA==" Group="0" Carrier="EY" CabinClass="Economy" FlightNumber="5429" ProviderCode="1G" Origin="XNB" Destination="AUH" DepartureTime="2019-06-20T23:50:00.000+04:00" ArrivalTime="2019-06-21T01:10:00.000+04:00" TravelTime="80" Distance="67" ClassOfService="L" ETicketability="Yes" Equipment="BUS" MarriageGroup="1" Status="HK" ChangeOfPlane="false" GuaranteedPaymentCarrier="No" ProviderReservationInfoRef="2wokqt8Q2BKARSGAAAAAAA==" TravelOrder="1" ProviderSegmentOrder="1" OptionalServicesIndicator="false" ParticipantLevel="Secure Sell" LinkAvailability="true" ElStat="A">
                <air:FlightDetails Key="2wokqt8Q2BKALSGAAAAAAA==" Origin="XNB" Destination="AUH" DepartureTime="2019-06-20T23:50:00.000+04:00" ArrivalTime="2019-06-21T01:30:00.000+04:00" FlightTime="100" TravelTime="80" Equipment="BUS" DestinationTerminal="1" AutomatedCheckin="false" ElStat="C"/>
                <air:Connection Duration="105"/>
                <common_v42_0:SellMessage>ARRIVES AUH TERMINAL 1</common_v42_0:SellMessage>
                <common_v42_0:SellMessage>*010 9W 6567  AT 9285  AZ 5745  BT 5784  GA 9187  HM 6229  HU 87*</common_v42_0:SellMessage>
                <common_v42_0:SellMessage>* *</common_v42_0:SellMessage>
                <common_v42_0:SellMessage>*010 JU 8116  VA 7101  VN 3217*</common_v42_0:SellMessage>
            </air:AirSegment>
            <air:AirSegment Key="RzO2Zt3R2BKAd+f9BAAAAA==" Group="0" Carrier="EY" CabinClass="Economy" FlightNumber="246" ProviderCode="1G" Origin="AUH" Destination="COK" DepartureTime="2019-06-21T02:55:00.000+04:00" ArrivalTime="2019-06-21T08:30:00.000+05:30" TravelTime="245" Distance="1749" ClassOfService="L" ETicketability="Yes" Equipment="321" MarriageGroup="1" Status="HK" ChangeOfPlane="false" GuaranteedPaymentCarrier="No" ProviderReservationInfoRef="2wokqt8Q2BKARSGAAAAAAA==" TravelOrder="2" ProviderSegmentOrder="2" OptionalServicesIndicator="false" ParticipantLevel="Secure Sell" LinkAvailability="true" ElStat="A">
                <air:FlightDetails Key="2wokqt8Q2BKAMSGAAAAAAA==" Origin="AUH" Destination="COK" DepartureTime="2019-06-21T02:55:00.000+04:00" ArrivalTime="2019-06-21T08:30:00.000+05:30" FlightTime="245" TravelTime="245" Equipment="321" OriginTerminal="3" DestinationTerminal="3" AutomatedCheckin="false" ElStat="C"/>
                <common_v42_0:SellMessage>DEPARTS AUH TERMINAL 3  - ARRIVES COK TERMINAL 3</common_v42_0:SellMessage>
                <common_v42_0:SellMessage>*010 9W 6616  XY 3246*</common_v42_0:SellMessage>
                <common_v42_0:SellMessage>ADD ADVANCE PASSENGER INFORMATION SSRS DOCA/DOCO/DOCS</common_v42_0:SellMessage>
                <common_v42_0:SellMessage>PERSONAL DATA WHICH IS PROVIDED TO US IN CONNECTION</common_v42_0:SellMessage>
                <common_v42_0:SellMessage>WITH YOUR TRAVEL MAY BE PASSED TO GOVERNMENT AUTHORITIES</common_v42_0:SellMessage>
                <common_v42_0:SellMessage>FOR BORDER CONTROL AND AVIATION SECURITY PURPOSES</common_v42_0:SellMessage>
            </air:AirSegment>
            <air:AirSegment Key="RzO2Zt3R2BKAf+f9BAAAAA==" Group="1" Carrier="EY" CabinClass="Economy" FlightNumber="247" ProviderCode="1G" Origin="COK" Destination="AUH" DepartureTime="2019-06-23T10:00:00.000+05:30" ArrivalTime="2019-06-23T12:30:00.000+04:00" TravelTime="240" Distance="1749" ClassOfService="L" ETicketability="Yes" Equipment="321" MarriageGroup="2" Status="HK" ChangeOfPlane="false" GuaranteedPaymentCarrier="No" ProviderReservationInfoRef="2wokqt8Q2BKARSGAAAAAAA==" TravelOrder="3" ProviderSegmentOrder="3" OptionalServicesIndicator="false" ParticipantLevel="Secure Sell" LinkAvailability="true" ElStat="A">
                <air:FlightDetails Key="2wokqt8Q2BKANSGAAAAAAA==" Origin="COK" Destination="AUH" DepartureTime="2019-06-23T10:00:00.000+05:30" ArrivalTime="2019-06-23T12:30:00.000+04:00" FlightTime="240" TravelTime="240" Equipment="321" OriginTerminal="3" DestinationTerminal="1" AutomatedCheckin="false" ElStat="C"/>
                <common_v42_0:SellMessage>DEPARTS COK TERMINAL 3  - ARRIVES AUH TERMINAL 1</common_v42_0:SellMessage>
                <common_v42_0:SellMessage>*010 9W 6617  XY 3247*</common_v42_0:SellMessage>
                <common_v42_0:SellMessage>ADD ADVANCE PASSENGER INFORMATION SSRS DOCA/DOCO/DOCS</common_v42_0:SellMessage>
                <common_v42_0:SellMessage>PERSONAL DATA WHICH IS PROVIDED TO US IN CONNECTION</common_v42_0:SellMessage>
                <common_v42_0:SellMessage>WITH YOUR TRAVEL MAY BE PASSED TO GOVERNMENT AUTHORITIES</common_v42_0:SellMessage>
                <common_v42_0:SellMessage>FOR BORDER CONTROL AND AVIATION SECURITY PURPOSES</common_v42_0:SellMessage>
            </air:AirSegment>
            <air:AirSegment Key="RzO2Zt3R2BKAh+f9BAAAAA==" Group="2" Carrier="EY" CabinClass="Economy" FlightNumber="5426" ProviderCode="1G" Origin="AUH" Destination="XNB" DepartureTime="2019-06-23T20:30:00.000+04:00" ArrivalTime="2019-06-23T21:50:00.000+04:00" TravelTime="80" Distance="67" ClassOfService="L" ETicketability="Yes" Equipment="BUS" MarriageGroup="2" Status="HK" ChangeOfPlane="false" GuaranteedPaymentCarrier="No" ProviderReservationInfoRef="2wokqt8Q2BKARSGAAAAAAA==" TravelOrder="4" ProviderSegmentOrder="4" OptionalServicesIndicator="false" ParticipantLevel="Secure Sell" LinkAvailability="true" ElStat="A">
                <air:FlightDetails Key="2wokqt8Q2BKAOSGAAAAAAA==" Origin="AUH" Destination="XNB" DepartureTime="2019-06-23T20:30:00.000+04:00" ArrivalTime="2019-06-23T22:10:00.000+04:00" FlightTime="100" TravelTime="80" Equipment="BUS" OriginTerminal="1" AutomatedCheckin="false" ElStat="C"/>
                <common_v42_0:SellMessage>DEPARTS AUH TERMINAL 1</common_v42_0:SellMessage>
                <common_v42_0:SellMessage>*010 9W 6554  AZ 4158  BT 5749  JU 8114  VA 7154*</common_v42_0:SellMessage>
            </air:AirSegment>
            <air:AirPricingInfo Key="RzO2Zt3R2BKAk+f9BAAAAA==" TotalPrice="OMR150.800" BasePrice="AED760" ApproximateTotalPrice="OMR150.800" ApproximateBasePrice="OMR80.000" EquivalentBasePrice="OMR80.000" Taxes="OMR70.800" LatestTicketingTime="2019-06-18T23:59:00.000+04:00" TrueLastDateToTicket="2019-06-18T23:59:00.000+04:00" PricingMethod="Guaranteed" Refundable="true" Exchangeable="true" IncludesVAT="false" ETicketability="Yes" PlatingCarrier="EY" ProviderCode="1G" ProviderReservationInfoRef="2wokqt8Q2BKARSGAAAAAAA==" AirPricingInfoGroup="1" PricingType="StoredFare" ElStat="A" FareCalculationInd="G">
                <air:FareInfo Key="2wokqt8Q2BKAHSGAAAAAAA==" FareBasis="LLRM3AE/" PassengerTypeCode="ADT" Origin="XNB" Destination="AUH" EffectiveDate="2019-06-18T00:00:00.000+04:00" NotValidBefore="2019-06-20" NotValidAfter="2019-06-20" PseudoCityCode="62RD" ElStat="C">
                    <air:FareTicketDesignator Value="YV"/>
                    <common_v42_0:Endorsement Value="NON ENDO/ REF"/>
                    <air:BaggageAllowance>
                        <air:MaxWeight Value="30" Unit="Kilograms"/>
                    </air:BaggageAllowance>
                </air:FareInfo>
                <air:FareInfo Key="2wokqt8Q2BKAISGAAAAAAA==" FareBasis="LLRM3AE/" PassengerTypeCode="ADT" Origin="AUH" Destination="COK" EffectiveDate="2019-06-18T00:00:00.000+04:00" Amount="NUC148.65" NotValidBefore="2019-06-21" NotValidAfter="2019-06-21" PseudoCityCode="62RD" ElStat="C">
                    <air:FareTicketDesignator Value="YV"/>
                    <air:FareSurcharge Key="2wokqt8Q2BKAWSGAAAAAAA==" Type="Other" Amount="NUC3.00" ElStat="A" SegmentRef="RzO2Zt3R2BKAd+f9BAAAAA=="/>
                    <air:FareSurcharge Key="2wokqt8Q2BKAXSGAAAAAAA==" Type="Weekend Surcharge" Amount="NUC13.61" ElStat="A" SegmentRef="RzO2Zt3R2BKAd+f9BAAAAA=="/>
                    <air:FareSurcharge Key="2wokqt8Q2BKAYSGAAAAAAA==" Type="Other" Amount="NUC6.80" ElStat="A" SegmentRef="RzO2Zt3R2BKAd+f9BAAAAA=="/>
                    <common_v42_0:Endorsement Value="NON ENDO/ REF"/>
                    <air:BaggageAllowance>
                        <air:MaxWeight Value="30" Unit="Kilograms"/>
                    </air:BaggageAllowance>
                </air:FareInfo>
                <air:FareInfo Key="2wokqt8Q2BKAJSGAAAAAAA==" FareBasis="LLRM1AE/" PassengerTypeCode="ADT" Origin="COK" Destination="AUH" EffectiveDate="2019-06-18T00:00:00.000+04:00" NotValidBefore="2019-06-23" NotValidAfter="2019-06-23" PseudoCityCode="62RD" ElStat="C">
                    <air:FareTicketDesignator Value="YV"/>
                    <common_v42_0:Endorsement Value="NON ENDO/ REF"/>
                    <air:BaggageAllowance>
                        <air:MaxWeight Value="30" Unit="Kilograms"/>
                    </air:BaggageAllowance>
                </air:FareInfo>
                <air:FareInfo Key="2wokqt8Q2BKAKSGAAAAAAA==" FareBasis="LLRM1AE/" PassengerTypeCode="ADT" Origin="AUH" Destination="XNB" EffectiveDate="2019-06-18T00:00:00.000+04:00" Amount="NUC56.08" NotValidBefore="2019-06-23" NotValidAfter="2019-06-23" PseudoCityCode="62RD" ElStat="C">
                    <air:FareTicketDesignator Value="YV"/>
                    <air:FareSurcharge Key="2wokqt8Q2BKAdSGAAAAAAA==" Type="Other" Amount="NUC3.00" ElStat="A" SegmentRef="RzO2Zt3R2BKAh+f9BAAAAA=="/>
                    <air:FareSurcharge Key="2wokqt8Q2BKAeSGAAAAAAA==" Type="Other" Amount="NUC6.80" ElStat="A" SegmentRef="RzO2Zt3R2BKAh+f9BAAAAA=="/>
                    <common_v42_0:Endorsement Value="NON ENDO/ REF"/>
                    <air:BaggageAllowance>
                        <air:MaxWeight Value="30" Unit="Kilograms"/>
                    </air:BaggageAllowance>
                </air:FareInfo>
                <air:BookingInfo BookingCode="L" CabinClass="Economy" FareInfoRef="2wokqt8Q2BKAHSGAAAAAAA==" SegmentRef="RzO2Zt3R2BKAb+f9BAAAAA=="/>
                <air:BookingInfo BookingCode="L" CabinClass="Economy" FareInfoRef="2wokqt8Q2BKAISGAAAAAAA==" SegmentRef="RzO2Zt3R2BKAd+f9BAAAAA=="/>
                <air:BookingInfo BookingCode="L" CabinClass="Economy" FareInfoRef="2wokqt8Q2BKAJSGAAAAAAA==" SegmentRef="RzO2Zt3R2BKAf+f9BAAAAA=="/>
                <air:BookingInfo BookingCode="L" CabinClass="Economy" FareInfoRef="2wokqt8Q2BKAKSGAAAAAAA==" SegmentRef="RzO2Zt3R2BKAh+f9BAAAAA=="/>
                <air:TaxInfo Category="AE" Amount="OMR7.900" Key="RzO2Zt3R2BKAl+f9BAAAAA=="/>
                <air:TaxInfo Category="F6" Amount="OMR3.700" Key="RzO2Zt3R2BKAm+f9BAAAAA=="/>
                <air:TaxInfo Category="TP" Amount="OMR0.600" Key="RzO2Zt3R2BKAn+f9BAAAAA=="/>
                <air:TaxInfo Category="ZR" Amount="OMR1.200" Key="RzO2Zt3R2BKAo+f9BAAAAA=="/>
                <air:TaxInfo Category="WO" Amount="OMR2.300" Key="RzO2Zt3R2BKAp+f9BAAAAA=="/>
                <air:TaxInfo Category="YQ" Amount="OMR54.600" Key="RzO2Zt3R2BKAq+f9BAAAAA=="/>
                <air:TaxInfo Category="YR" Amount="OMR0.500" Key="RzO2Zt3R2BKAr+f9BAAAAA=="/>
                <air:FareCalc>DXB EY X/AUH EY COK Q DXBCOK3.00Q DXBCOK13.61Q DXBCOK6.80 125.24LLRM3AE/YV EY X/AUH EY DXB Q COKDXB3.00Q COKDXB6.80 46.29LLRM1AE/YV NUC204.74END ROE3.67275</air:FareCalc>
                <air:PassengerType Code="ADT" BookingTravelerRef="gr8AVWGCR064r57Jt0+8bA==">
                    <air:FareGuaranteeInfo GuaranteeDate="2019-06-18" GuaranteeType="Guaranteed"/>
                </air:PassengerType>
                <common_v42_0:BookingTravelerRef Key="gr8AVWGCR064r57Jt0+8bA=="/>
                <air:ChangePenalty>
                    <air:Amount>OMR10.00</air:Amount>
                </air:ChangePenalty>
                <air:CancelPenalty>
                    <air:Amount>OMR21.00</air:Amount>
                </air:CancelPenalty>
                <air:TicketingModifiersRef Key="2wokqt8Q2BKAhSGAAAAAAA=="/>
            </air:AirPricingInfo>
            <air:TicketingModifiers PlatingCarrier="EY" Key="2wokqt8Q2BKAhSGAAAAAAA==" ElStat="A">
                <air:DocumentSelect IssueElectronicTicket="true"/>
            </air:TicketingModifiers>
        </air:AirReservation>
        <common_v42_0:AgencyInfo>
            <common_v42_0:AgentAction ActionType="Created" AgentCode="uAPI4777060768-7d89df01" BranchCode="P7099377" AgencyCode="S7099370" EventTime="2019-06-18T12:37:50.178+00:00"/>
        </common_v42_0:AgencyInfo>
        <common_v42_0:FormOfPayment Key="jwt2mcK1Qp27I2xfpcCtAw==" Type="Cash" Reusable="false" ProfileKey="+gr4dnY9RJG00MovXy6nJg==" ElStat="A">
            <common_v42_0:ProviderReservationInfoRef Key="2wokqt8Q2BKARSGAAAAAAA=="/>
        </common_v42_0:FormOfPayment>
    </universal:UniversalRecord>
    <air:AirSolutionChangedInfo ReasonCode="Schedule">
        <air:AirPricingSolution Key="2wokqt8Q2BKAXRGAAAAAAA==">
            <air:AirSegment Key="RzO2Zt3R2BKAb+f9BAAAAA==" Group="0" Carrier="EY" FlightNumber="5429" ProviderCode="1G" Origin="XNB" Destination="AUH" DepartureTime="2019-06-20T23:40:00.000+04:00" ArrivalTime="2019-06-21T01:20:00.000+04:00" FlightTime="100" TravelTime="100" Distance="67" ClassOfService="L" Equipment="BUS" Status="NN" ParticipantLevel="Secure Sell" LinkAvailability="true" PolledAvailabilityOption="O and D cache or polled status used with different local status" AvailabilitySource="S" AvailabilityDisplayType="Fare Specific Fare Quote Unbooked" OptionalServicesIndicator="false">
                <air:CodeshareInfo OperatingCarrier="EY">ETIHAD AIRWAYS</air:CodeshareInfo>
                <air:FlightDetails Key="RzO2Zt3R2BKAc+f9BAAAAA==" Origin="XNB" Destination="AUH" DepartureTime="2019-06-20T23:40:00.000+04:00" ArrivalTime="2019-06-21T01:20:00.000+04:00" FlightTime="100" TravelTime="100" Distance="67"/>
            </air:AirSegment>
            <air:AirSegment Key="RzO2Zt3R2BKAd+f9BAAAAA==" Group="0" Carrier="EY" FlightNumber="246" ProviderCode="1G" Origin="AUH" Destination="COK" DepartureTime="2019-06-21T02:55:00.000+04:00" ArrivalTime="2019-06-21T08:30:00.000+05:30" FlightTime="245" TravelTime="245" Distance="1749" ClassOfService="L" Equipment="321" Status="NN" ParticipantLevel="Secure Sell" LinkAvailability="true" PolledAvailabilityOption="O and D cache or polled status used with different local status" TravelOrder="1" AvailabilitySource="S" AvailabilityDisplayType="Fare Specific Fare Quote Unbooked" OptionalServicesIndicator="false">
                <air:CodeshareInfo OperatingCarrier="EY">ETIHAD AIRWAYS</air:CodeshareInfo>
                <air:FlightDetails Key="RzO2Zt3R2BKAe+f9BAAAAA==" Origin="AUH" Destination="COK" DepartureTime="2019-06-21T02:55:00.000+04:00" ArrivalTime="2019-06-21T08:30:00.000+05:30" FlightTime="245" TravelTime="245" Distance="1749"/>
            </air:AirSegment>
            <air:AirSegment Key="RzO2Zt3R2BKAf+f9BAAAAA==" Group="1" Carrier="EY" FlightNumber="247" ProviderCode="1G" Origin="COK" Destination="AUH" DepartureTime="2019-06-23T09:35:00.000+05:30" ArrivalTime="2019-06-23T12:05:00.000+04:00" FlightTime="240" TravelTime="240" Distance="1749" ClassOfService="L" Equipment="321" Status="NN" ParticipantLevel="Secure Sell" LinkAvailability="true" PolledAvailabilityOption="O and D cache or polled status used with different local status" TravelOrder="2" AvailabilitySource="S" AvailabilityDisplayType="Fare Specific Fare Quote Unbooked" OptionalServicesIndicator="false">
                <air:CodeshareInfo OperatingCarrier="EY">ETIHAD AIRWAYS</air:CodeshareInfo>
                <air:FlightDetails Key="RzO2Zt3R2BKAg+f9BAAAAA==" Origin="COK" Destination="AUH" DepartureTime="2019-06-23T09:35:00.000+05:30" ArrivalTime="2019-06-23T12:05:00.000+04:00" FlightTime="240" TravelTime="240" Distance="1749"/>
            </air:AirSegment>
            <air:AirSegment Key="RzO2Zt3R2BKAh+f9BAAAAA==" Group="1" Carrier="EY" FlightNumber="5426" ProviderCode="1G" Origin="AUH" Destination="XNB" DepartureTime="2019-06-23T20:00:00.000+04:00" ArrivalTime="2019-06-23T21:40:00.000+04:00" FlightTime="100" TravelTime="100" Distance="67" ClassOfService="L" Equipment="BUS" Status="NN" ParticipantLevel="Secure Sell" LinkAvailability="true" PolledAvailabilityOption="O and D cache or polled status used with different local status" TravelOrder="3" AvailabilitySource="S" AvailabilityDisplayType="Fare Specific Fare Quote Unbooked" OptionalServicesIndicator="false">
                <air:CodeshareInfo OperatingCarrier="EY">ETIHAD AIRWAYS</air:CodeshareInfo>
                <air:FlightDetails Key="RzO2Zt3R2BKAi+f9BAAAAA==" Origin="AUH" Destination="XNB" DepartureTime="2019-06-23T20:00:00.000+04:00" ArrivalTime="2019-06-23T21:40:00.000+04:00" FlightTime="100" TravelTime="100" Distance="67"/>
            </air:AirSegment>
        </air:AirPricingSolution>
    </air:AirSolutionChangedInfo>
</universal:AirCreateReservationRsp>

What I actually need is a way to use single children() method with "air" and "universal" prefix. Is something like children('air,universal',true) possible?


text:
Q: Getting object as a result from func/proc in Delphi What is the best practice for returning simple objects from functions / procedures in delphi?
eg. 2 kinds of code:
pass created object as reference, populate object in Proc, destroy it afterwards
procedure Proc(var Obj: TMyObject);
begin
  // populate Obj
end;

O := TMyObject.Create;
try
  Proc(O);
  // manipulate populated object
finally
  O.Free;
end;

or
get created object as result from function, destroy after manipulation
function Func: TMyObj;
begin
  Result := TMyObj.Create;
end;

O := Func;
if O <> nil then
begin
  try
    // manipulate
  finally
    O.Free;
  end;
end;

A: There is no best practice. The primary thing you should do, though, is to make sure it's always clear who is responsible for destroying the object at any given time, even when an exception occurs.
There's nothing wrong with a function creating a new instance and returning it. Such a function is a factory. You can treat it just like a class's constructor, so you should make sure that it behaves like a constructor: Either return a valid object or throw an exception. It never returns a null reference.
function Func: TMyObj;
begin
  Result := TMyObj.Create;
  try
    Result.X := Y;
  except
    Result.Free;
    raise;
  end;
end;

That's an exception-handling pattern you don't see very often, but it's important for this style of function. Returning the object transfers ownership from the function to the caller, but only if it manages to execute completely. If it has to leave early because of an exception, it frees the object because the caller has no way to free it itself. (Functions that terminate due to an exception do not have return values.) The caller will use it like this:
O := Func;
try
  writeln(O.X);
finally
  O.Free;
end;

If there's an exception in Func then O never gets assigned, so there's nothing available for the caller to free.

When the caller creates the object and you pass it to another function to initialize it, do not make the parameter a "var" parameter. That places certain restrictions on the caller, who must use a variable of exactly the type requested by the function, even if some descendant type was created instead.
Such a function should not free the object. The caller doesn't grant ownership responsibility to the functions it calls, especially when it plans on using the object after the function returns.

A: It depends on the lifetime of the object and on who is responsible for it.
Most of the time objects should be created and destroyed by the same entity.
Let's say your method  fills a TStringList with results from parsing a file.
Should you let that function create the TStringList, or should you create it and pass as a reference?
I find it more readable to create it, pass it as reference, and later destroy, all in consecutive lines of code.
Now let's consider that you have a function that returns a TCustomer, for each customer added. In that case I would use a function, because I suppose that my entity would have a list, or something, of customers responsible for destroying them when not needed.

A: It is a common Delphi idiom to let the caller create the object and pass it as a parameter. Note that you don't have to declare it var in almost all cases.
procedure Proc (Obj : TMyObject)
begin
  Obj.SomeProperty := 'SomeValue';
  ...
end;

Calling Code:
Obj := TMyObject.Create;
try
  Proc (Obj);
finally
  FreeAndNil (Obj);
end;

This avoids confusion about who has to free the object. Note that if you have a chain of method calls it can quicky become very complicated to keep track of objects that need to be freed somewhere along the line.
One more drawback: having creation and destruction scattered in the code makes it impossible to use try...finally blocks, which is just another helpful idiom to avoid resource leaks.
If you want your method to create the object,  I would make it explicit in the function name, something like CreateAndInitializeList sounds right to me.

A: My rule is to have ownership and creation altogether. I always have the creator be the owner and thus have the responsability of destroying the object. The creation of the object is explicit in the invocation code, it is never a side effect of the invocation.
So the usual signatures of my functions are
function Func(o:tMyO): TMyO;
begin
  // ....
  Result := o;
end;

this way I may do either
   o := func(TMyO.create);

or
  o := TMyO.create;
  // ...
  func(o);

A: As mentioned, in general the same entity that created the object should free it and that means that the caller should create the object reference rather than having it done inside the function.
However, this is only possible if the caller knows the exact type of the item to be returned rather than a supertype.  For instance:
var E: TEmployee;

E := CreateEmployee(EmployeeID);  // Could return TEmployee or subclasses TManager or TRetiredEmployee

try

    E.SendEmail(MessageText);
    if (E is TRetiredEmployee) then
        E.PrintLetter;

finally

    E.Free;

end;

In cases like this, I find it's helpful to include the word "Create", or other indicator, in the name of the factory function I'm calling.

A: I often use the construct
FUNCTION SomeFunction(SL : TStrings = NIL) : TStrings;
  BEGIN
    IF Assigned(SL) THEN Result:=SL ELSE Result:=TStringList.Create;
    // Use Result for the remainder of the function
  END;

That way, I can use it both as a PROCEDURE with a passed-in reference, and as a FUNCTION which creates the instance itself.


text:
Q: How to get the instance of JpaRepository? I am new to Spring, this is maybe newbie question.
I create a Repository:
import org.springframework.data.jpa.repository.JpaRepository;

public interface TaskRepository extends JpaRepository<Task, String>{
}

The Repository work fine with my RestController
import org.springframework.web.bind.annotation.*;

@RestController
public class TaskController {
    private final TaskRepository repository;

    TaskController(TaskRepository repository) {
        this.repository = repository;
    }

    // Aggregate root
    // tag::get-aggregate-root[]
    @GetMapping("/Tasks")
    public List<Task> all() {
        return repository.findAll();
    }
    // end::get-aggregate-root[]

    @PostMapping("/Tasks")
    public Task newTask(@RequestBody Task newTask) {
        return repository.save(newTask);
    }

    // Single item

    @GetMapping("/Tasks/{id}")
    public Task one(@PathVariable String id) {

        return repository.findById(id)
                .orElseThrow(() -> new TaskNotFoundException(id));
    }

    @PutMapping("/Tasks/{id}")
    public Task replaceTask(@RequestBody Task newTask, @PathVariable String id) {

        return repository.findById(id)
                .map(Task -> {
                    Task.setSparkAppId(newTask.getSparkAppId());
                    Task.setValue(newTask.getValue());
                    return repository.save(Task);
                })
                .orElseGet(() -> {
                    return repository.save(newTask);
                });
    }

    @DeleteMapping("/Tasks/{id}")
    public void deleteTask(@PathVariable String id) {
        repository.deleteById(id);
    }
}

However, I want to use that JpaRepository for my internal logic. I create a TaskHandler listener, that will update new Task in the database.
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.spark.launcher.SparkAppHandle;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.Optional;
import java.util.List;
public class TaskListener implements SparkAppHandle.Listener {
    @Autowired
    private TaskRepository repository;

    private static final Logger logger = LoggerFactory.getLogger(TaskListener.class);

    public Task task;

    public TaskListener(Task task) {
        this.task = task;
    }

    @Override
    public void stateChanged(SparkAppHandle handle) {
        String curAppId = handle.getAppId();
        SparkAppHandle.State curState = handle.getState();

        String curStateStr = curState.toString();
        logger.info("app id " + curAppId + " state " + curStateStr);
        Optional<Throwable> opErr = handle.getError();
        opErr.ifPresent(throwable -> logger.error(throwable.getMessage()));
        this.task.setSparkAppId(curAppId);
        this.task.setState(curStateStr);
        //replaceTask(task, task.getTaskId());
    }

    @Override
    public void infoChanged(SparkAppHandle handle) {
        String curAppId = handle.getAppId();
        SparkAppHandle.State curState = handle.getState();
        String curStateStr = curState.toString();
        logger.info("app id " + curAppId + " state " + curStateStr);
//        SparkTaskModel.getInstance().executeUpdateTask(this.taskId, curAppId, curStateStr);
        Optional<Throwable> opErr = handle.getError();
        if (opErr.isPresent()){
            logger.error(opErr.get().getMessage());
        }

        this.task.setSparkAppId(curAppId);
        this.task.setState(curStateStr);
        //replaceTask(task, task.getTaskId());
    }

    // not work because repository is null
    public Task replaceTask(Task newTask, String id) {

        return repository.findById(id)
                .map(Task -> {
                    Task.setSparkAppId(newTask.getSparkAppId());
                    Task.setValue(newTask.getValue());
                    return repository.save(Task);
                })
                .orElseGet(() -> {
                    return repository.save(newTask);
                });
    }
}

I cannot put the Repository into Contructor because I create the TaskListener object in my program, and I don't know what to put in place of Repository should it in TaskListener contructor.
Error: (xxx was my project name censored...)
java.lang.NullPointerException
    at xxx.xxx.xxx.xxx.spark_launcher_for_meow.xxx.tasksparklauncher.TaskListener.replaceTask(TaskListener.java:70)
    at xxx.xxx.xxx.xxx.spark_launcher_for_meow.xxx.tasksparklauncher.TaskListener.stateChanged(TaskListener.java:47)
    at org.apache.spark.launcher.AbstractAppHandle.fireEvent(AbstractAppHandle.java:160)
    at org.apache.spark.launcher.AbstractAppHandle.setState(AbstractAppHandle.java:137)
    at org.apache.spark.launcher.AbstractAppHandle.setState(AbstractAppHandle.java:124)
    at org.apache.spark.launcher.LauncherServer$ServerConnection.handle(LauncherServer.java:315)
    at org.apache.spark.launcher.LauncherConnection.run(LauncherConnection.java:58)
    at java.base/java.lang.Thread.run(Thread.java:829)

The error point to:
repository.findById(id)....

in function
replaceTask

Said that repository is null.

A: @Autowired won't work since TaskListener is not a bean managed by Spring, but a bean that you instantiate manually.
You can simply pass TaskRepository as 2nd constructor argument
public class TaskListener implements SparkAppHandle.Listener {

    private final TaskRepository repository;
    public final Task task;

    public TaskListener(TaskRepository repository, Task task) {
        this.repository = repository;
        this.task = task;
    }

    // other stuff
}

And then somewhere in your code your that instantiates TaskListener you autowire TaskRepository and use it as constructor parameter
@Service // << this means that bean is managed by Spring
// and all autowirings will be automatically done by Spring
// therefore taskRepository will be NOT null
public class SomeTaskListenerService {

    @Autowired
    private TaskRepository taskRepository;

    public void someMethod() {
        Task task = ... // obtain task
        TaskListener listener = new TaskListener(taskRepository, task);
        // do some actions with the listener
    }
}

A: You can use multiple constructors in your TaskListener class. But in this case, you have to add @Autowired for the constructor where spring injection is required.
So your TaskListener class, you can modify like this.
private final TaskRepository repository;

public Task task;

public TaskListener(Task task) {
    this.task = task;
}

@Autowired
TaskListener(TaskRepository repository) {
    this.repository = repository;
}


text:
Q: Custom ModRewrite to redirect to controller method I am currently using Alipay which POSTs responses to my OpenCart website URL [on success] that is this http://192.168.16.58:8080/index.php?route=api/order/callback.
However, one condition for Alipay is that it stops reading the URL after the ? separator, so instead of POSTing data to my route, it instead POSTs to http://192.168.16.58:8080/index.php
Because of this, I am interested in using RewriteEngine to write a custom rule where when I set the notify_url as http://192.168.16.58:8080/index.php/api/order/callback, it actually redirects to http://192.168.16.58:8080/index.php?route=api/order/callback
What I have is the following:
RewriteRule ^index.php/api/order/callback.$ index.php?route=api/order/callback [L]
My logic is that if Alipay is going to index.php/api/order/callback, I would instead be redirected to index.php?route=api/order/callback, however, using both GET and POST, I am instead redirect to my OpenCart homepage.

A: RewriteRule ^api/order/callback$ index.php?route=api/order/callback [L]
This would enable:
http://192.168.16.58:8080/api/order/callback
to:
http://192.168.16.58:8080/index.php?route=api/order/callback


text:
Q: How do I write a cloud function that monitors a storage bucket? I have set up a Google Cloud Storage bucket to send notifications to a Pub/Sub topic:
gsutil notification create -t my-topic -f json gs://test-bucket
I have created a subscription to this topic to push messages to a cloud function endpoint:
gcloud pubsub subscriptions create my-sub --topic my-topic
And the cloud function is deployed with:
gcloud functions deploy promo_received --region europe-west1 --runtime python37 --trigger-topic my-topic
The purpose of the function (right now), is to check if a file being created in the test-bucket matches a specific file name, and to fire a message off to Slack when it does. Currently the function looks like this:
def promo_received(data):
    date_str = datetime.today().strftime('%Y%m%d')
    filename = json.loads(data)["name"]
    bucket = json.loads(data)["bucket"]

    if filename == 'PROM_DTLS_{}.txt.gz'.format(date_str):
        msg = ":heavy_check_mark: *{}* has been uploaded to *{}*. Awaiting instructions.".format(filename, bucket)
        post_to_slack(url, msg)

When I test this by dropping a file named PROM_DTLS_20190913.txt.gz, I can see the function fires, however it crashes with 2 errors:
TypeError: promo_received() takes 1 positional argument but 2 were given
TypeError: the JSON object must be str, bytes or bytearray, not LocalProxy
This is my first time attempting to do this, and I'm not sure where to start with troubleshooting. Any help would be greatly appreciated!

A: You need to add the context as argument for your function, that will solve the first error:
def promo_received(data, context):
    [...]

Also, you don't need json.loads to retrieve the name of the file or the bucket:
data['name']
data['bucket']

This should get rid of the second error.
Check the example in the Google Cloud Storage Triggers documentation page

A: To write a Python Cloud Function, look at this example. Note that Cloud Storage serializes the object into a utf-8 JSON string, which Cloud Functions then base64-encodes. So you need to first base64-decode the payload, then utf8-decode it, then JSON parse it.
def promo_received(event, context):
  obj = json.loads(base64.b64decode(event['data']).decode('utf-8'))
  filename = obj["name"]
  bucket = obj["bucket"]

  # the rest of your code goes here


text:
Q: Got this error ='MultinomialNB' object has no attribute 'coef_' 'MultinomialNB' object has no attribute 'coef_'
i tried this=
#adj = list(zip(model.coef_[0], cv.get_feature_names()))

but got the error saying that =multinomialNB object has no attribute coef_

A: .coef_ for multinomialNB has been deprecated since version 0.24 and it has been removed in 1.1 (renaming of 0.26).
By reading https://github.com/scikit-learn/scikit-learn/issues/7233 you get that coef_ is just taken from the .feature_log_prob_ method. So basically if you use:
list(zip(model.feature_log_prob_[0], cv.get_feature_names()))

you should get the same result.
If you are wondering why .coef_ has been deprecated, you can find your answer in this issue: https://github.com/scikit-learn/scikit-learn/issues/2237 i.e. "The coef_ and intercept_ on MultinomialNB don't behave like other linear models because they contain probabilities even in the binary case. They should contain log-odds ratios."


text:
Q: functional array list search Having issues displaying what I am searching for in my array list. When I search the array it finds the information but it prints the whole list do to all the objects being named fisherman. It will search for the item and if found will print the items I am wanting but it prints ALL the instances of fisherman.  But the search is clunky and doesnt work in some instances. So, I am needing help with the search function to do a proper search and output of that search. I am not sure how I would go about changing the object name from "fisherman" to the SSN of each fisherman then that would help in the searching parameters. But I couldn't figure out a way to change the object name for each individual fisherman. Thank you for any help you can provide.
public static void fishermanMenu() {
    // declare variables and array
    int selection;
    String fName;
    String lName;
    String ssn;
    String number;
    String email;
    String searchSSN;
    String menuFisherman[] = {"Register New Fisherman", "Search Fisherman", "Return to Main Menu"};

    System.out.println("\nFisherman Menu");
    // for loop to print menu from array
    for(int i = 0, k = 1; i < menuFisherman.length; i++, k++) {
        System.out.println("("+ k + ") " + (menuFisherman[i]));
    }
    System.out.print("Selection: ");
    selection = input.nextInt();
    input.nextLine();
    if (selection == 1) {
        $Fisherman fisherman = new $Fisherman();
        fishermen.add(fisherman);

        System.out.print("Enter First Name: ");
        fName = input.next();
        fisherman.setFirstName(fName);

        System.out.print("Enter Last Name: ");
        lName = input.next();
        fisherman.setLastName(lName);

        System.out.print("Enter Phone Number...ie 904-560-7896: ");
        number = input.next();
        fisherman.setPhoneNumber(number);

        System.out.print("Enter SSN...ie 123-45-6789: ");
        ssn = input.next();
        fisherman.setSSN(ssn);

        System.out.print("Enter email address: ");
        email = input.next();
        fisherman.setEmailAddress(email);

        System.out.print(fishermen.toString());

        fishermanMenu();
    }

    else if (selection == 2) {
        System.out.println("Enter Social Security Number of fisherman to search for below.");
        System.out.print("SSN: ");
        searchSSN = input.nextLine();

        for ($Fisherman fisherman : fishermen) {
            if (fisherman.getSSN().equals(searchSSN)) {
                System.out.println(fishermen.toString());
                fishermanMenu();
            }
            else {
                System.out.println("No match for that fisherman");
                fishermanMenu();
            }
        }
    }
}

here is the output. As you can see when I searched for "123" it returned the whole list and when I searched for "456" it said "No match for that fisherman".
    Main Menu
    (1) Fisherman Menu
    (2) Tournament Menu
    (3) Fish Menu
    (4) Close Tournament
    (5) Quit Program
    Selection: 1

    Fisherman Menu
    (1) Register New Fisherman
    (2) Search Fisherman
    (3) Return to Main Menu
    Selection: 1
    Enter First Name: Matt
    Enter Last Name: P
    Enter Phone Number...ie 904-560-7896: 123
    Enter SSN...ie 123-45-6789: 123
    Enter email address: 123

    [fisherman{SSN=123, firstName='Matt', lastName='P', phoneNumber='123', emailAddress='123'}]

    Fisherman Menu
    (1) Register New Fisherman
    (2) Search Fisherman
    (3) Return to Main Menu
    Selection: 1
    Enter First Name: Joe
    Enter Last Name: K
    Enter Phone Number...ie 904-560-7896: 456
    Enter SSN...ie 123-45-6789: 456
    Enter email address: 456

    [fisherman{SSN=123, firstName='Matt', lastName='P', phoneNumber='123', emailAddress='123'}, fisherman{SSN=456, firstName='Joe', lastName='K', phoneNumber='456', emailAddress='456'}]

    Fisherman Menu
    (1) Register New Fisherman
    (2) Search Fisherman
    (3) Return to Main Menu
    Selection: 2
    Enter Social Security Number of fisherman to search for below.
    SSN: 123
    [fisherman{SSN=123, firstName='Matt', lastName='P', phoneNumber='123', emailAddress='123'}, fisherman{SSN=456, firstName='Joe', lastName='K', phoneNumber='456', emailAddress='456'}]

    Fisherman Menu
    (1) Register New Fisherman
    (2) Search Fisherman
    (3) Return to Main Menu
    Selection: 2
    Enter Social Security Number of fisherman to search for below.
    SSN: 456
    No match for that fisherman

    Fisherman Menu
    (1) Register New Fisherman
    (2) Search Fisherman
    (3) Return to Main Menu
    Selection:

A: This is because you are printing fishermen.toString() which is the whole list.
System.out.println(fishermen.toString());

Change the above to print fisherman.toString() instead
EDIT:
You are using if-else for each fisherman in the loop, you need to fix that as the following:
int found = 0;
for ($Fisherman fisherman : fishermen) {
    if (fisherman.getSSN().equals(searchSSN)) {
        found = 1;
        System.out.println(fisherman);
        break;
    }
if (found == 0) {
    System.out.println("No match for that fisherman");
    fishermanMenu();
}
else {
    found = 0;
    fishermanMenu();
}

A: public class Main {

    private static List<Fisherman> allFisherpeople = new ArrayList<Fisherman>();

    public static void main(String... args) {
        while (true) {
            printMenu();

            String selection = getInput();
            if ("1".equals(selection)) {
                addFisherman();
            } else if ("2".equals(selection)) {
                searchFishermen();
            } else {
                System.out.println("Not a vaild selection: " + selection);
            }
        }
    }

    private static String getInput() {
        try {
            String string = new String();
            char character;
            while ((character = (char) System.in.read()) != '\n')
                string += character;
            return string;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    private static void printMenu() {
        String menuFisherman[] = { "Register New Fisherman", "Search Fisherman", "Return to Main Menu" };
        System.out.println("\nFisherman Menu");
        for (int i = 0; i < menuFisherman.length; i++) {
            System.out.println("(" + (i + 1) + ") " + (menuFisherman[i]));
        }
        System.out.print("Selection: ");
    }

    private static void addFisherman() {
        Fisherman fisherman = new Fisherman();
        System.out.print("Enter First Name: ");
        fisherman.setFirstName(getInput());
        System.out.print("Enter Last Name: ");
        fisherman.setLastName(getInput());
        System.out.print("Enter Phone Number...ie 904-560-7896: ");
        fisherman.setPhoneNumber(getInput());
        System.out.print("Enter SSN...ie 123-45-6789: ");
        fisherman.setSsn(getInput());
        System.out.print("Enter email address: ");
        fisherman.setEmail(getInput());
        System.out.print(fisherman);
        allFisherpeople.add(fisherman);
    }

    private static void searchFishermen() {
        System.out.println("Enter Social Security Number of fisherman to search for below.");
        System.out.print("SSN: ");
        String search = getInput();

        for (Fisherman fisherman : allFisherpeople) {
            if (fisherman.getSsn().equals(search)) {
                System.out.println("You must be looking for: " + fisherman);
            } else {
                System.out.println("No match for that fisherman");
            }
        }
    }

    private static class Fisherman {
        private String firstName;
        private String lastName;
        private String ssn;
        private String phoneNumber;
        private String email;

        public String getFirstName() {
            return firstName;
        }

        public void setFirstName(String firstName) {
            this.firstName = firstName;
        }

        public String getLastName() {
            return lastName;
        }

        public void setLastName(String lastName) {
            this.lastName = lastName;
        }

        public String getSsn() {
            return ssn;
        }

        public void setSsn(String ssn) {
            this.ssn = ssn;
        }

        public String getPhoneNumber() {
            return phoneNumber;
        }

        public void setPhoneNumber(String phoneNumber) {
            this.phoneNumber = phoneNumber;
        }

        public String getEmail() {
            return email;
        }

        public void setEmail(String email) {
            this.email = email;
        }

        public String toString() {
            return firstName + " " + lastName + " (" + phoneNumber + ")";
        }
    }
}

A: Thank you for the help. After a few hours away and a fresh set of eyes and your comment I was able to see the issues. I changed the code on lines 44 and 56 from (fishermen.toString()) to just (fisherman) and that fixed the issue of printing ALL the fisherman each time. Also changed that else statement to a single print statement outside the for loop. This allowed the search to go through the entire list and not just the first fisherman before printing the "No match for that fisherman".
    else if (selection == 2) {
        System.out.println("Enter Social Security Number of fisherman to search for below.");
        System.out.print("SSN: ");
        searchSSN = input.nextLine();

        for ($Fisherman fisherman : fishermen) {
            if (fisherman.getSSN().equals(searchSSN)) {
                System.out.println(fisherman);
                fishermanMenu();
            }
        }
        System.out.println("No match for that fisherman");
        fishermanMenu();
    }


text:
Q: Proof: For any positive integer $n$, there exists a prime whose first digits are the digits of $n$ Conjecture:

For any positive integer $n$, there exists a prime whose first digits
  are the digits of $n$.

Proof:
The infinite set of integers starting with the digits of integer $n$ is distributed as $1$ sequence of consecutive integers for each power of $10$. For example, the integers starting with the same digits as $2$ are those between $20$ and $30$, between $200$ and $300$, between $2000$ and $3000$ $…$
Now let's say $n=1245$, and let's look at much larger integers than $n$. For example, all integers $x$ in the following interval starts with digits $1245$:
$$ 12450000000000000000000000000 ≤ x <12460000000000000000000000000 $$
A range of this magnitude is proven to contain at least $1$ prime number, so whether $n$ is a single digit or a million digits long, we only need to add the proper number of zeros to reach an interval where having no prime is impossible.
Questions:

*

*Is my proof valid ? Did I miss something ?

*Is there other existing proofs of that ?

Of course any suggestions/edits to make it more clear or professional are welcome, I'm still a newbie at proof writing!


text:
Q: Module not found: Can't resolve 'react-native' error when adding SafeAreaView I used the following commands to create a react app:
npm install react-native
npx create-react-app my-app
cd my-app
npm start

The I added the following line of code in the App.js and reloaded the browser.
import {SafeAreaView} from 'react-native';

But it keeps showing the error:
./src/App.js
Module not found: Can't resolve 'react-native' in '/Users/sdan/Documents/Projects/my-app/src'

A: You are using react not react-native if you want to create and run react-native just flow document https://reactnative.dev/docs/environment-setup and then you can create react-native app like that:
npx react-native init AwesomeProject


text:
Q: Convert Office Documents to XPS File Programatically or Third Party tool I have an application that i am working on which needs actually a file preview in a preview pane so because of that after searching a lot on google found that there are some ways to actually preview the files using PreviewHandlers but management does not want that to be a solution.
So without that we can only be left with converting the documents to XPS and use them to preview in DocumentViewer where all the tools are available.
For PDF file Acrobat provides a COM component that is fine. The problem here is i am able to convert doc,docx files to xps to show them as preview but not able to convert anyother files to xps.
Or a library that converts all files to pdf that also is fine.
if someone has faced this before or know the solution/Third party library that does the work to convert the documents then the help is really appreciated.
Thanks

A: Try Microsoft 2007 Microsoft Office Add-in: Microsoft Save as PDF or XPS. Chect out this example


text:
Q: If sequences $x_n$ and $y_n$ in a metric space converge to the same limit, does $d(x_n, y_n)$ converge? $(x_n)$ and $(y_n)$ are sequences in a metric space $M$ with $\lim_{n\to\infty} x_n = \lim_{n\to\infty} y_n = a$. Show that given $\varepsilon>0$ there exists $n_0$ such that $d(x_n, y_n)<\varepsilon$ $\forall n≥n_0$
Hello, this is from my course in general topology. I know I'm supposed to use the definition of convergence for $x_n$ and $y_n$ and the triangle inequality, but I can't seem to get it right. Any help?

A: Let $\varepsilon > 0.$
Since we know that $x_n \to L$, we know that there exists $N_x$ such that when $n>N_x,$ then $d(x_n,L)<\frac{\varepsilon}{2}$.
Likewise, since $y_n \to L$, we know that there exists $N_y$ such that when $n>N_y$, $ $ $d(y_n,L)< \frac{\varepsilon}{2}.$
Set $N =$max$\{N_x,N_y\}$.
Then when $n >N,$ by the Triangle Inequality: $$d(x_n,y_n) \leq d(x_n,L) + d(y_n,L) = \frac{\varepsilon}{2} + \frac{\varepsilon}{2} = \varepsilon.$$
Thus, we have shown that if $x_n \to L$ and $y_n \to L,$ $d(x_n,y_n) \to 0.$ $\square$


text:
Q: How does Wordpress support Unicode? I've been looking through Wordpress' codes and they're mostly using PHP's regular string functions, like strlen, strpos, etc. Yet I know Wordpress supports utf8, so how does it do that?
Does it overload the regular string functions with multibyte string functions?
If so, is that a good idea in practice? If not, then how do they do it?

A: Wordpress is written in PHP. As far as I know, PHP doesn't support any character encoding (UTF-8, UTF-16, ...). It just assumes the text to be ASCII encoded.
The actual encoding and decoding is done by your browser. When you write a post, your browser sends the text you just entered as UTF-8 to the server. Wordpress just stores it in the database.
The encoding is specified in Wordpress' HTML code:
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />

This instructs the browser to use "UTF-8" for all text on the page. This includes the actual text on the page as well as all input fields.
So, Wordpress doesn't handle UTF-8 itself. It let's the browser handle it. (This is also means, if you'd specify a different encoding for the backend and the frontend pages, you'd get garbage text on the frontend.)
As a note: Unlike PHP, MySQL is UTF-8 aware. So, for example, a search for non-ASCII characters yields the correct result because the search is handled by MySQL rather than Wordpress.

A: No, WordPress doesn't support unicode natively.  But it's an easy fix.
Open up your wp.config in your root.
Find these lines:
/** Database Charset to use in creating database tables. */
define('DB_CHARSET', 'utf8');

/** The Database Collate type. Don't change this if in doubt. */
define('DB_COLLATE', '');

Just comment 'em out:
/** Database Charset to use in creating database tables. */
//define('DB_CHARSET', 'utf8');

/** The Database Collate type. Don't change this if in doubt. */
//define('DB_COLLATE', '');

Now it won't display unicode as a ? ... so you're all set.


text:
Q: Counting problem about housing suppose there are 3 rooms in a dormitory: one single, one double, and one for four students. How many ways are there to house 7 students in these rooms?
The answer is 7$\times$(5+4+3+2+1), but I don't understand why, can anyone explain this to me?

A: The reasoning behind the answer $7\times(5+4+3+2+1)$ must be something like this:
First we choose which student to put in the single room. There are $7$ possible choices for this.
Then we choose the older of the two students in the double room. The youngest of 6 students left by now cannot possibly be the older in the double room, but the 5 others are fair game. That gives of $5$ possible choices in each phase. But depending on which student we chose to be the older, there's a different number of possible choices for the younger student in the double room, so instead of just multiplying something by $5$ we need to add the number of choice-of-younger-student for each choice-of-older-student, giving $5+4+3+2+1$ ways to fill the double room.
Once the single and double room are occupied, the 4 remaining students go in the last room, and there's only one way to do that.

A: One way to arrange the students is to first choose the students who will inhabit the four-student room in $\binom{7}{4}$ ways, then choose two of the remaining students to inhabit the two-student room in $\binom{3}{2}$ ways. The remaining student will be forced into the single-student room. Since we made one choice followed by another choice, the total number of outcomes is $\binom{7}{4} \binom{3}{2} = 105$.


text:
Q: Update pandas df with new values I am trying to merge two dataframes together but when I do it, it seems to replace the existing values with blanks, which isn't really ideal.
df1

col1      col2
'house1'  300
'house2'  450
'house3'  750

df2

col1      col2
'house4'  600

the code I'm using to concat is:
df = pd.concat([df2, df1], sort=False, ignore_index=True)

which yields:
col1      col2
'house4'  600
'house1'
'house2'
'house3'

Is concat the wrong choice? I want to update all the values, but as said, it's overwriting the existing data. I'm sorry if I'm doing a terrible job at explaining this.

A: You should try append:
df = df1.append(df2, ignore_index=True)

A: Since you want to add a row, you'll probably want to use pandas append function.
Try this:
df = df1.append(df2)


text:
Q: How to manually configure a ThreadContext in a multi-tenant app? I'm developing a multi tenant app on the SAP BTP and I need to process webhook events that I receive from a non-SAP system. More specifically, upon receiving an event, I need to access a destination in my tenant's sub account and query some data from the system configured behind this destination.
The endpoint on which I receive the webhook events on is secured via basic authentication with my own user database. So that means the incoming webhook request never passes the sdk's RequestFilter which would usually extract the JWT token (which in my case wouldn't be present anyways) and set the ThreadContext.
I tried the following code (the webhook payload contains the correct tenant id):
 @Override
public void handleWebhook(WebhookEvent webhookEvent) {
    TenantAccessor.executeWithTenant(tenantOfString(webhookEvent.getTenantId()), () -> {
        Destination destination = DestinationAccessor.getDestination("MyDestination");

        //Do some stuff with the destination
    });
}

private Tenant tenantOfString(String tenantId) {
    return new Tenant() {
        @Nonnull
        @Override
        public String getTenantId() {
            return tenantId;
        }
    };
}

Unfortunately, this code results in the following error:
com.sap.cloud.sdk.cloudplatform.connectivity.exception.DestinationAccessException: com.sap.cloud.sdk.cloudplatform.connectivity.exception.DestinationNotFoundException: No destination for name 'MyDestination' could be found in any of the registered loaders. When your app runs on SAP Cloud Platform, make sure you have one of the following modules in your dependency tree: com.sap.cloud.sdk.cloudplatform:scp-neo or com.sap.cloud.sdk.cloudplatform:scp-cf, depending on your SCP landscape.

What could be a solution to solve this kind of issue? It seems to me that I somehow have to manually configure a proper ThreadContext in order to perform such kind of operations.
EDIT:
The destination exists in the tenant's sub account and I also set up a test endpoint with oAuth and an JWT token retrieved from the tenant's authentication endpoint, with which i can successfully access the tenant's destination from my provider account. So I assume the the entire saas provisioning process works correctly.


text:
Q: Ada code instrumentation as GNAT compilation part? I'm looking for a best way to integrate GNAT compiler with our custom code analysis/modification tools. We are using custom tools to perform different code metrics (like execution time, test coverage and etc) and even do some code obfuscation. So for example for measuring code execution time I need to insert 2 procedure calls into each function/procedure (the first one where the function starts, and the other one for each function exit). The code for these 2 procedures are implemented in a separate translation unit. What is the best way to do these code instrumentations (insert/modify code) with GNAT compiler in terms of simplicity and performance?  I can think of these several ways:

*

*Does GNAT compiler support code generation plugins of any kind? Seem's that it doesn't, but maybe I missed something while googling about it. Maybe there is a way to do it using some metaprogramming tricks (like in some modern programming languages like Nimrod and D), but I couldn't find if Ada even supports metaprogramming at all.

*Looks like the ASIS library can help me out, but it is made for creating separate tools. Is it possible to integrate ASIS-based tool with GNAT? So for example to write a tool that would be loaded by GNAT during compilation, and would modify nodes in the AST before it (the AST) is about to be transformed into GIMPLE. Using the ASIS-based tool separately (for example by preprocessing each source file before passing it to compiler) may reduce compilation time, as source code will need to be parsed twice (by the tool and by the compiler) and be saved/loaded to/from some temporary location on disk.

*Is it possible to get GIMPLE from GNAT compiler, modify and pass it to GCC? I couldn't find if there is a working GIMPLE front-end inside GCC, but it seems that GIMPLE is used internally only. I can dump it with GCC compiler, but I can't recompile modified GIMPLE afterwards (seems that there is no GIMPLE front-end for GCC).


text:
Q: My facebook "like" function is every time need to login to the facebook. How can I solve it? I used the following codes in my android app that can "like" to a specific link via facebook. But when I task, it asked me to login even though I already logged into facebook android app and web browser also. I don't know why. Can anybody answer me?
 private void appendUrl(String url, String appId,
        FacebookLikeOptions options, StringBuilder sb)
{
    sb.append("<iframe ");
    sb.append("style='");
    sb.append("display:block;clear:both;border:none;overflow:hidden;");
    sb.append("width:100%;");
    sb.append("'");

    sb.append("src='//www.facebook.com/plugins/like.php");
    //noinspection deprecation
    sb.append("?href=").append(URLEncoder.encode(url));
    sb.append("&layout=").append(options.getLayoutString());
    sb.append("&action=").append(options.getActionString());
    sb.append("&show_faces=").append(options.showFaces);
    sb.append("&share=").append(options.share);

    if (appId != null && appId.trim().length() > 0)
    {
        sb.append("&appId=").append(appId);
    }

    sb.append("'");

    sb.append("scrolling='no'");
    sb.append("frameborder='0'");
    sb.append("allowTransparency='true'");
    sb.append("></iframe>");
}


text:
Q: Regular expressions: Differences between browsers I'm increasingly becoming aware that there must be major differences in the ways that regular expressions will be interpreted by browsers.
As an example, a co-worker had written this regular expression, to validate that a file being uploaded would have a PDF extension:
^(([a-zA-Z]:)|(\\{2}\w+)\$?)(\\(\w[\w].*))(.pdf)$

This works in Internet Explorer, and in Google Chrome, but does NOT work in Firefox.  The test always fails, even for an actual PDF.  So I decided that the extra stuff was irrelevant and simplified it to:
^.+\.pdf$

and now it works fine in Firefox, as well as continuing to work in IE and Chrome.
Is this a quirk specific to asp:FileUpload and RegularExpressionValidator controls in ASP.NET, or is it simply due to different browsers supporting regex in different ways?  Either way, what are some of the latter that you've encountered?

A: Regarding the actual question:  The original regex requires the value to start with a drive letter or UNC device name.  It's quite possible that Firefox simply doesn't include that with the filename.  Note also that, if you have any intention of being cross-platform, that regex would fail on any non-Windows system, regardless of browser, as they don't use drive letters or UNC paths.  Your simplified regex ("accept anything, so long as it ends with .pdf") is about as good of a filename check as you're going to get.
However, Jonathan's comment to the original question cannot be overemphasized.  Never, ever, ever trust the filename as an adequate means of determining its contents.  Or the MIME type, for that matter.  The client software talking to your web server (which might not even be a browser) can lie to you about anything and you'll never know unless you verify it.  In this case, that means feeding the received file into some code that understands the PDF format and having that code tell you whether it's a valid PDF or not.  Checking the filename may help to prevent people from trying to submit obviously incorrect files, but it is not a sufficient test of the files that are received.
(I realize that you may know about the need for additional validation, but the next person who has a similar situation and finds your question may not.)

A: As far as I know firefox doesn't let you have the full path of an upload. Interpretation of regular expressions seems irrelevant in this case. I have yet to see any difference between modern browsers in regular expression execution.

A: If you're using javascript, not enclosing the regex with slashes causes error in Firefox.
Try doing var regex = /^(([a-zA-Z]:)|(\\{2}\w+)\$?)(\\(\w[\w].*))(.pdf)$/;

A: As Dave mentioned, Firefox does not give the path, only the file name.  Also as he mentioned, it doesn't account for differences between operating systems.  I think the best check you could do would be to check if the file name ends with PDF.  Also, this doesn't ensure it's a valid PDF, just that the file name ends with PDF.  Depending on your needs, you may want to verify that it's actually a PDF by checking the content.

A: I have not noticed a difference between browsers in regards to the pattern syntax.  However, I have noticed a difference between C# and Javascript as C#'s implementation allows back references and Javascript's implementation does not.

A: I believe JavaScript REs are defined by the ECMA standard, and I doubt there are many differences between JS interpreters. I haven't found any, in my programs, or seen mentioned in an article.
Your message is actually a bit confusing, since you throw ASP stuff in there. I don't see how you conclude it is the browser's fault when you talk about server-side technology or generated code. Actually, we don't even know if you are talking about JS on the browser, validation of upload field (you can no longer do it, at least in a simple way, with FF3) or on the server side (neither FF nor Opera nor Safari upload the full path of the uploaded file. I am surprised to learn that Chrome does like IE...).


text:
Q: Jquery Problem.For More that 1 Image upload Preview I have an issue. I want to see Preview of my selected Image before upload.
My Codes are working perfect for Only 1 Image upload. When i make 4 Places to upload photos. 4 Different 4 photos, Then This not work. I tried to change IDs, Classes also for each upload. But Failed.
My Codes are here..
HTML

                    Rear

                    <input type="file" id="rear" name="rear" value="" onchange="loadFile(event)" style="color:white;">

CSS is Here
.input-sec > input[type="file"]
{
    display: none;
}

.input-sec img
{
    height: 200px;
    cursor: pointer;
}

Jquery Is Here.
function readURL(input) {
        if (input.files && input.files[0]) {
            var reader = new FileReader();

            reader.onload = function (e) {
                $('#frontpre').attr('src', e.target.result);
            }

            reader.readAsDataURL(input.files[0]);
        }
    }

    $("#front").change(function(){
        readURL(this);
    });

My Problem is When i add only 1 Photo upload field on a page, It works. But when i try to add More than 1 Image upload fields on same, Then no one work.I also tried changing its IDs for each upload and Jquery. but failed. Please help me.

A: I got it Fixed.

And THIS HTML is Here..

                    Front

                    <input type="file" id="file1" name="file1" value="" accept="image/x-png, image/gif, image/jpeg" required onchange="readURL(this);"  style="color:white;">

                    Rear

                    <input type="file" id="file2" name="file2" value="" accept="image/x-png, image/gif, image/jpeg" required onchange="readURL1(this);" style="color:white;">

                    Driver Side

                    <input type="file" id="file3" name="file3" value="" accept="image/x-png, image/gif, image/jpeg" required onchange="readURL2(this);" style="color:white;">

                    Customer Side

                    <input type="file" id="file4" name="file4" value="" accept="image/x-png, image/gif, image/jpeg" required onchange="readURL3(this);" style="color:white;">

Fixed It.

A: change the id to frontpre1, frontpre2, frontpre3, frontpre4 and front1, front2, front3, front4 and create 4 different function to call.
Also you can go for
http://codepedia.info/html5-filereader-preview-image-show-thumbnail-image-before-uploading-on-server-in-jquery/


text:
Q: Difference in calculating derivative of RBM while using ContrastiveDivergence could anybody explain me difference between calculating derivative in RBM with -h_j * x_k and - h_j(x) * x_k? I found source codes with both implementations and I am not sure which one is better (and why?)

A: By h_j and h_j(x) are you referring to the j^th hidden neuron sample or the j^th hidden neuron sigmoidal activation? Assuming so, if you calculate the derivative of the negative log-likelihood function, it turns out to be P(h_j = 1) * x_k.


text:
Q: document.getElementById(name).options[0] work in IE but doesnt work in Chrome I use the tree in project but it is working in IE but isn't working in Chrome. I saw this code document.getElementById(name).options[0] it doesnt work in Chrome and Firefox. How can i pass the this problem or alternative this code ?
My js code
function bosalt(elm)
{
    alert("bosalt function");
    while(document.getElementById(elm).options[0]!=null)
        document.getElementById(elm).options[0]=null;
}

and another place;
function listele(elm,val,txt)
{
    alert("fasa fiso");
    document.getElementById(elm).options[document.getElementById(elm).length]=new Option(txt,val);
}

I saw it isnt working because when i add block comment this code the project is running.
Please help me. And thank you so much everything.


text:
Q: Why would SendAsync on my DelegatingHandler injected in Startup of my Function App never be called? I have the following configuration for an Azure Function App using .Net 3.1:
public override void Configure(IFunctionsHostBuilder builder)
{
    Config = CdrConfigurationBuilder.BuildConfiguration<Startup>(approotpath: builder.GetContext().ApplicationRootPath);
    builder.Services.AddSingleton(Config);
    builder.Services.AddAzureAppConfiguration();
    builder.Services.AddSingleton(CdrConfigurationBuilder.ConfigurationRefresher);

    builder.Services.AddSingleton((c) => new AuthHeaderHandler(Config, apisection: string.Empty, securitysection: "CDR:Services:Security"));

    builder.Services.AddHttpClient<IHtmlDocumentService, HtmlDocumentService>()
        .AddHttpMessageHandler<AuthHeaderHandler>()
        .SetHandlerLifetime(TimeSpan.FromMinutes(5))
        .AddPolicyHandler(GetRetryPolicy());

    builder.Services.AddSingleton<IHtmlDocumentService, HtmlDocumentService>();

    builder.Services.AddLogging();
}

This compiles and runs but SendAsync() on my AuthHeaderHandler is never called.
What am I missing?

A: You are injecting IHtmlDocumentService twice.
The second registration is overriding the first registration.
Remove the code line builder.Services.AddSingleton<IHtmlDocumentService, HtmlDocumentService>();


text:
Q: Access constant field in annotation processor Suppose a class defines a constant field:
public class Foo {
  public static final int CONSTANT_FIELD = 3;
}

And suppose an annotation interface is declared like the following:
public @interface Something {
  int value();
}

Finally, suppose the annotation is used as follows:
@Something(Foo.CONSTANT_FIELD)

Question: In an annotation processor, how can I get the element for CONSTANT_FIELD from its use in setting the value of @Something?

Edit: Including a concrete example in the question itself.
I have an annotation that gets used like this:
@RuleDependency(recognizer = BQLParser.class,
                rule = BQLParser.RULE_statement,
                version = 0)

The annotation processor needs to know that RULE_statement is a constant defined in the BQLParser class. If I could access the Element for BQLParser.RULE_statement directly from setting the rule property of the annotation, it would eliminate the need for the recognizer property. This annotation is used thousands of times within real applications, and the recognizer is always just the declaring type of the rule constant. Resolving this question would simplify the annotation usage to just this:
@RuleDependency(rule = BQLParser.RULE_statement, version = 0)

A: I was able to implement this feature using the Compiler Trees API.

*

*Update the pom.xml to include the following profiles to make sure tools.jar is referenced on systems where it is not referenced by default.
<profiles>
    <profile>
        <!-- Java 6 and earlier have java.vendor set to "Sun Microsystems Inc." -->
        <id>default-tools-6.jar</id>
        <activation>
            <property>
                <name>java.vendor</name>
                <value>Sun Microsystems Inc.</value>
            </property>
        </activation>
        <dependencies>
            <dependency>
                <groupId>com.sun</groupId>
                <artifactId>tools</artifactId>
                <version>1.6</version>
                <scope>system</scope>
                <systemPath>${java.home}/../lib/tools.jar</systemPath>
            </dependency>
        </dependencies>
    </profile>

    <profile>
        <!-- Java 7 and later have java.vendor set to "Oracle Corporation" -->
        <id>default-tools.jar</id>
        <activation>
            <property>
                <name>java.vendor</name>
                <value>Oracle Corporation</value>
            </property>
        </activation>
        <dependencies>
            <dependency>
                <groupId>com.sun</groupId>
                <artifactId>tools</artifactId>
                <version>1.6</version>
                <scope>system</scope>
                <systemPath>${java.home}/../lib/tools.jar</systemPath>
            </dependency>
        </dependencies>
    </profile>
</profiles>

*Override Processor.init to get an instance of Trees.
@Override
public void init(ProcessingEnvironment processingEnv) {
    super.init(processingEnv);
    this.trees = Trees.instance(processingEnv);
}

*Implement a TreePathScanner<TypeMirror, Void>, which is used to obtain the TypeMirror of the declaring type assigned to the rule property in an annotation.
private class AnnotationVisitor extends TreePathScanner<TypeMirror, Void> {
    @Override
    public TypeMirror visitAnnotation(AnnotationTree node, Void p) {
        for (ExpressionTree expressionTree : node.getArguments()) {
            if (!(expressionTree instanceof AssignmentTree)) {
                continue;
            }

            AssignmentTree assignmentTree = (AssignmentTree)expressionTree;
            ExpressionTree variable = assignmentTree.getVariable();
            if (!(variable instanceof IdentifierTree) || !((IdentifierTree)variable).getName().contentEquals("rule")) {
                continue;
            }

            return scan(expressionTree, p);
        }

        return null;
    }

    @Override
    public TypeMirror visitAssignment(AssignmentTree at, Void p) {
        return scan(at.getExpression(), p);
    }

    @Override
    public TypeMirror visitMemberSelect(MemberSelectTree mst, Void p) {
        return scan(mst.getExpression(), p);
    }

    @Override
    public TypeMirror visitIdentifier(IdentifierTree it, Void p) {
        return trees.getTypeMirror(this.getCurrentPath());
    }
}

*Provide a default value for the recognizer property. I wish this could be null but Java explicitly forbids that...
/**
 * Gets the recognizer class where the dependent parser rules are defined.
 * This may reference the generated parser class directly, or for simplicity
 * in certain cases, any class derived from it.
 * <p>
 * If this value is not specified, the default value {@link Parser}
 * indicates that the declaring type of the constant value specified for
 * {@link #rule} should be used as the recognizer type.
 * </p>
 */
Class<? extends Recognizer<?, ?>> recognizer() default Parser.class;

*Update the code that gathers information about about the RuleDependency annotations applied to particular Element instances in the code to first try accessing the recognizer property, and if it's not specified, use the declaring type of the constant in the rule property instead. Error handling is omitted from this code sample for brevity.
RuleDependency dependency = element.getAnnotation(RuleDependency.class);

// first try to get the parser type from the annotation
TypeMirror recognizerType = getRecognizerType(dependency);
if (recognizerType != null && !recognizerType.toString().equals(Parser.class.getName())) {
    result.add(new Triple<RuleDependency, TypeMirror, Element>(dependency, recognizerType, element));
    continue;
}

// fallback to compiler tree API
AnnotationMirror annotationMirror = null;
for (AnnotationMirror mirror : element.getAnnotationMirrors()) {
    if (processingEnv.getTypeUtils().isSameType(ruleDependencyTypeElement.asType(), mirror.getAnnotationType())) {
        annotationMirror = mirror;
        break;
    }
}

AnnotationValue annotationValue = null;
for (Map.Entry<? extends ExecutableElement, ? extends AnnotationValue> entry : annotationMirror.getElementValues().entrySet()) {
    if (entry.getKey().getSimpleName().contentEquals("rule")) {
        annotationValue = entry.getValue();
        break;
    }
}

TreePath treePath = trees.getPath(element, annotationMirror, annotationValue);
AnnotationVisitor visitor = new AnnotationVisitor();
recognizerType = visitor.scan(treePath, null);

result.add(new Triple<RuleDependency, TypeMirror, Element>(dependency, recognizerType, element));

A: If rule is an int, it's not going to be possible for the annotation processor to find out where that int was defined. However, you could use an enum instead of an int for the rule field and group your rules in there with references to their parsers. Maybe something like this:
Parser interface:
public interface RuleParser {
}

Example implementation:
public class RuleParserImpl implements RuleParser {
}

Rule enum:
public enum Rule {

    RULE_STATEMENT(RuleParserImpl.class);

    private final Class<? extends RuleParser> ruleParserClass;

    private Rule(Class<? extends RuleParser> ruleParser) {
        this.ruleParserClass = ruleParser;
    }

    public Class<? extends RuleParser> getRuleParserClass() {
        return ruleParserClass;
    }
}

Annotation with enum instead of int field:
@Retention(RetentionPolicy.RUNTIME)
public @interface RuleDependency {
    Rule rule();
}

Usage example:
@RuleDependency(rule = Rule.RULE_STATEMENT)
public class RuleProcessor {

    public static void main(String[] args) {
        RuleDependency ruleDependency = RuleProcessor.class.getAnnotation(RuleDependency.class);
        Rule rule = ruleDependency.rule();
        Class<? extends RuleParser> ruleParserClass = rule.getRuleParserClass();
        System.out.println(ruleParserClass); //Prints "class RuleParserImpl"
    }
}

Hope that gives you some ideas.


text:
Q: Formatting broken HDD and reinstalling Ubuntu I bought Dell Inspiron N5010 in 2011. In 2018, I installed Ubuntu 18.04 on Windows 10. Since then, in Ubuntu, PC is heating up a lot and hence I used only Windows 10 all along. But in between I faced GRUB issues many times and fixed using fsck or set commands. But now the machine won't start. I tried installing GRUB and reinstalling Ubuntu as well, but nothing worked. When I ran diagnostics from BIOS, then I got HDD error 2000:0146.
I will be glad if you can help me with fixing HDD  from Ubuntu live USB. If this doesn't work, I would like to format my PC and reinstall Ubuntu. Can this be done on HDD with errors?

A: There's no point to installing Ubuntu on a failed HDD that has errors especially when SSDs are so cheap. SSDs last much longer than HDDs because as the name suggests an SSD is a Solid State Drive. If your stored data on the HDD matters to you, back it up and upgrade your storage device.

A: The hard drive is well past its expected life.

HDDs wear out and fail over time, taking their data with them. Any
files residing on a single HDD that's a few years old is destined to
be lost – not 'if' but 'when'.

(Citation from this article)
My personal experience is after 5 to 7 years its a game of roulette.


text:
Q: ¿Cómo verificar si el dato ingresado en un JOptionPane es una letra?
Buenos días, tardes o noches, quiero intentar verificar que lo ingresado en el JOptionPane sea letra, si en caso no sea así (número y caracter), quiero me arroje un error después de verificar.

En este caso es que si se desea, registrar personal o ver personales registrados.

    public class Proyecto {

    public static void main(String[] args) {
    String decision = JOptionPane.showInputDialog("    -----Bienvenido al sistema de registro de personal-----"
                                 + "\nDesea registrar personal o ver los personales registrados: ");

        }

    }

A: Existe la clase stringUtils, tiene varias funciones para validar cadenas y determinar si es numerico.
http://commons.apache.org/proper/commons-lang/javadocs/api-release/org/apache/commons/lang3/StringUtils.html#isNumericSpace-java.lang.CharSequence-
Para arrojar el error puede ser con un if en caso de que devuelva que es un numero
Si es true significa que si es numérico
if(StringUtils.isNumeric(yourvar)) {
 //Lanzar mensaje de error
}


text:
Q: Issue with haskell install using stack I tried installing Haskell using stack as given on this page https://docs.haskellstack.org/en/stable/install_and_upgrade/#windows
I have downloaded and installed Haskell.
When I try to run stack, it just runs through and closes in less than a second. Can somebody please clarify as to what is happening?

A: From the webpage you linked to:
"Unpack the archive and place stack.exe somewhere on your %PATH% (see Path section below) and you can then run stack on the command line."
If you double click on "stack"(.exe), it opens a command window, executes the program and closes again.
In other words, store "stack" in a directory that is in your PATH environment variable, then open cmd.exe and run stack.exe from there.
Usually if you run such a program without any parameters, some information should appear about how to proceed from there.


text:
Q: Concatenate .mp4 videos of different encoding parameters using avconv without losing quality? How can I use the avconv tool to concatenate multiple .mp4 videos of different encoding parameters in a single container, without losing quality?

A: The commands given here will not work when videos have different encoding parameters. In fact, you can only concatenate them by bringing them to the same parameters first, working in the decoded (pixel) domain, and then losslessly storing them.
For example, harmonizing the framerate and video dimensions, audio sampling rate and audio channels:
avconv -i input_1.mp4 -s 1920x1080 -r 25 -c:v ffv1 -c:a pcm_s16le -ac 2 -ar 44100 out_1.avi
avconv -i input_2.mp4 -s 1920x1080 -r 25 -c:v ffv1 -c:a pcm_s16le -ac 2 -ar 44100 out_2.avi
avconv -i "concat:out_1.mp4|out_1.mp4" -c copy output.avi

This uses ffv1 as lossless codec, but any other lossless codec would work fine (e.g., huffyuv in an AVI or libx264 with -crf 0 in an MP4).
If you want a "small" output file again, you have no other choice than compressing output.avi with some lossy encoder.


text:
Q: Removing GB from PC Windows 7 My PC says that it has 29.2 GB free of 59.5 GB. How do I remove say, 10GB? I go to my IOBit uninstaller, but I've removed everything that's a GB or more or 500 MB's.
How do I free 10 GBs?

A: Did you clean the Temp folders , and make sure you clean up the Recycle bin also.
Also , if your machine is accessing by multiple users , there profiles also consume some amount of space , their desktop might contains the big file available.


text:
Q: Retrieving data from html forms with php I'm working on an assignment where I'm supposed to build a set of web forms so you can submit data to a database and add an entry to a specific table. I built a field that helps the user with suggestions retrieved from the db through a php request, basically while the user types into the field, a list of suggestions pops up and he/she can select an option.
Let's say I'm adding a new entry in a 'books' table and I can fill the 'author' form only with elements from the 'authors' table (so the user can't put an arbitrary author). To do that I used the autosuggestion method.
The 'books' table has a foreign key 'aut_id' which is the id attribute (primary key) of the 'authors' table.
As I said before I'm using php to retrieve the list of suggestions (author name, author surname and author id as well). But once the user clicks on a suggestion the web form is filled with the author name and surname and I don't know how to take advantage of this query so that when the user clicks "Submit" the aut_id field is properly filled.
I'll put some code, here is the HTML + Script:

...more hrml...

        Author
        <input type="text" class="form-control" id="inputAuthor" placeholder="Author name" onkeyup="lookup(this.value);" onblur="fill();">

And here is the php I'm using to retrieve the suggestion list:
if(!$db) {
    echo 'ERROR: Could not connect to the database.';
} else {
    if(isset($_POST['queryString'])) {
        $queryString = $db->real_escape_string($_POST['queryString']);
        if(strlen($queryString) >0) {

            $query = $db->query("SELECT aut_name, aut_surname, aut_id FROM author WHERE aut_name LIKE '$queryString%' LIMIT 10");
//I could echo the aut_id but I wouldn't know how to retrieve it on Submit with php
            if($query) {
                while ($result = $query ->fetch_object()) {
                    if(!$result->aut_surname){
                        echo '
aut_name.'\'); return false">'.$result->aut_name.'
';
                    }else{
                        echo '
aut_name.' ' .$result->aut_surname.'\'); return false">'.$result->aut_name.' ' .$result->aut_surname.'
';
                    }
                }
            } else {
                echo 'ERROR: There was a problem with the query.';
            }
        } else {
            // Dont do anything.
        }
    } else {
        echo 'There should be no direct access to this script!';
    }
}

The form is then filled with the proper name and surname but that's not what I need. So I can't use the $_POST php function as I do for any other field. I know I can solve this problem somehow, but I'd like to know the most proper way to do it. I'm kind of new to php so I might be missing something, I read some people using the DOM to retrieve the proper content. I could do another query to the db on submit so that it would look for the id of the author the user typed and then INSERT the proper data, but I think there might be a way to take advantage of the query I already did to retrieve the suggestions list. I just don't know how.
If I didn't make the problem clear enough please ask me anything and I'll try to do better. Thanks in advance for your time.

A: I would return the aut_id in the php script such as
PHP:
if($query) {
                while ($result = $query ->fetch_object()) {
                    if(!$result->aut_surname){
                        echo '
aut_name.'\', \'' + $result->aut_id + '\''); return false">'.$result->aut_name.'
';
                    }else{
                        echo '
aut_name.' ' .$result->aut_surname.'\', \'' + $result->aut_id + '\''); return false">'.$result->aut_name.' ' .$result->aut_surname.'
';
                    }
                }

You could add a hidden field and then on the form which you would set the value of the hidden field in the fill function.
HTML:

        Author
        <input type="text" class="form-control" id="inputAuthor" placeholder="Author name" onkeyup="lookup(this.value);" onblur="fill();">
        <input type="hidden" id="hiddenAutId"/>

Javascript:
function fill(thisValue, autId) {
        $('#inputAuthor').val(thisValue);
        $('#hiddenAutId').val(autId);
        setTimeout("$('#suggestions').hide();", 200);
    }

Also have a look at this question, if you return your authors in JSON format you can skip the hidden field.
how to set id in jquery ui autocomplete source event