text:
Q: how to convert sql to query builder laravel Can anyone help me out to convert this SQL to query builder!
SELECT topwords.*,
       mw.word AS my_word
FROM   topwords
       LEFT JOIN (SELECT DISTINCT words.word
                  FROM   definition_word
                         JOIN words
                           ON words.id = definition_word.word_id
                  WHERE  definition_word.user_id = $user) AS mw
              ON topwords.word = mw.word

I have a problem with how to use a subquery in leftjoin!
I tried something like this but it has error!
See error as image
DB::table('topwords')
                    ->leftJoin(DB::raw("SELECT DISTINCT
                    words.word
                    FROM definition_word
                    JOIN words ON words.id = definition_word.word_id
                    WHERE definition_word.user_id = $user as mw"),"topwords.word", "=", "mw.word" )
                    ->select(
                        "topwords.*",
                        "mw.word AS my_word"
                    )->orderBy('id','desc')->paginate(15);

A: You have this error because of paginate and aggregation
Try to make custom pagination, using LengthAwarePaginator
Here is example: Laracast
So you need to make something like this:
  $query = DB::table('topwords')
                        ->leftJoin(DB::raw("SELECT DISTINCT
                        words.word
                        FROM definition_word
                        JOIN words ON words.id = definition_word.word_id
                        WHERE definition_word.user_id = $user as mw"),"topwords.word", "=", "mw.word" )
                        ->select(
                            "topwords.*",
                            "mw.word AS my_word"
                        );

    $paginator = new LengthAwarePaginator($query->get(), $query->count(), $request->input('per_page', 15), $request->input('page', 1));

And then you can use it in the collection

A: you can use Join Sub query official document subquery-joins
$mw = DB::table('words')
        ->select('DISTINCT words.word')
        ->join('definition_word', function($join) use ($user)
        {
            $join->on('wordss.id', '=', 'definition_word.word_id')
                 ->where('definition_word.user_id',  $user);
        });

$topwords = DB::table('topwords')
        ->joinSub($mw, 'mw',function ($join) {
            $join->on('topwords.word', '=', 'mw.word');
        })
        ->select('topwords.*','mw.word AS my_word')
        ->orderBy('id','desc')
        ->paginate(15);


text:
Q: Is it necessary for a uml state machine to have a shallow history? Our supervisor said it is necessary for a composite state to have a shallow history..otherwise your tool that you are building does not make sense? Is this correct?
The tool is an undergraduate project that allows a subset of class and state machine diagrams to be built..you can see screenshot on cyrusuml.com

A: It depends on the context, if the state machine needs to roll-back for any reason then the answer is yes.  A example would be Parser for an LALR (Look-Ahead/Left to Right) Grammar were it is essential.  However if there are is no need for roll-back then the answer would be no.
In this case since you are modeling state machines you need to be able to handle both kinds, those with and without roll-back; other wise as he says your tool is useless.

redpajama_set_name: RedPajamaStackExchange


text:
Q: jqgrid inlineNav cloneToTop? I am playing with jqGrid and I have a combination of both a pager (with View and Refresh) and an inlineNav (with Add, Edit, Save, Cancel).
I have toppager:true and cloneToTop:true which places the pager controls, both at top and bottom. However I can't seem to do the same with my inlineNav.
Full code follows, but I tried to do the following, but the top buttons do not respond properly and it's a bit of a mess:
$("#pager_left").clone().appendTo("#list_toppager_left");

Can anyone help?
    $(document).ready(function() {

        var lastSel;

  $("#list").jqGrid({
    url:'db.php',
    datatype: 'json',
    mtype: 'GET',
    colNames:[
    /*...*/
    ],
    colModel :[
      /*...*/
    ],
    pager: '#pager',
    autowidth:true,
    height: "100%",
    rowNum:20,
    rowList:[20,50,100,1000],
    loadtext: 'Loading...',
    viewrecords: true,
    sortname:'BUSINESS',
    sortorder:"ASC",
    multiselect:false,
    sortable:true,
    toppager:true,
    ignorecase:true,
    gridview: true,
    editurl:"db_edit.php",
    caption: 'Bath BID',
    onSelectRow: function(id) {
        if(id && id!==lastSel){
            $('#list').saveRow(lastSel);
            lastSel=id;
        }
        }
  }).navGrid('#pager', {
    edit:false,
    add:false,
    del:true,
    view:true,
    search:false,
    viewtext:"View",
    closeOnEscape:true,
    edittext:"Edit",
    refreshtext:"Refresh",
    addtext:"Add",
    deltext:"Delete",
    searchtext:"Search",
    cloneToTop:true},{},{},{},{multipleSearch:true});

    $("#list").jqGrid('filterToolbar',{stringResult: true,searchOnEnter : true});
    $("#list").jqGrid('inlineNav','#pager', {
        edittext:"Edit",
        addtext:"Add",
        savetext:"Save",
        canceltext:"Cancel",
        cloneToTop:true
    });

Thanks in advance!

A: I analysed your problem. First of all the option cloneToTop: true is supported by navGrid, but not by inlineNav. Moreover the ids of the buttons of will be constructed using the grid id as the prefix. As the result one will have
list_iladd, list_iledit, list_ilsave, list_ilcancel

as ids. On the other side the ids of the standard navGrid buttons from will have the following ids after cloneToTop: true:
view_list, del_list,
view_list_top, del_list_top

So one can't just call navGrid twice with both pager:
$("#list").jqGrid('inlineNav', '#list_toppager', {
    edittext: "Edit",
    addtext: "Add",
    savetext: "Save",
    canceltext: "Cancel"
});
$("#list").jqGrid('inlineNav', '#pager', {
    edittext: "Edit",
    addtext: "Add",
    savetext: "Save",
    canceltext: "Cancel"
});

One will receive as the results id duplicates (see the demo).
Making manual id modifications before calling the inlineNav at the second time will also not really help (see the next demo) because the code which will be executed after clicking on the inline buttons use the same rules of id building. So only the buttons having original ids will be disabled or enabled.
I can summarize: the current implementation of inlineNav don't support the top pager. I would recommend you use inlineNav only once. If you need to have the icons in the second pager you should better examine the source code of inlineNav (see here for example) and add in the same way new buttons with respect of navButtonAdd and using another ids.
I hope that in the next version the code of inlineNav will be extended to support two pager at the same time.
UPDATED: I forgot to mention, that I fixed a little position of the text relative to icons in the navigator bars. It is not the main subject of your question, but probably it will be interesting for you too:
.ui-jqgrid .ui-jqgrid-toppager .ui-pg-div {
    margin-top: 2px;
    padding-right: 5px;
}
.ui-jqgrid .ui-jqgrid-toppager .ui-pg-div span.ui-icon {
    margin-top: -2px;
}
.ui-jqgrid .ui-jqgrid-pager .ui-pg-div {
    margin-top: 2px;
    padding-right: 5px;
}
.ui-jqgrid .ui-jqgrid-pager .ui-pg-div span.ui-icon {
    margin-top: -2px;
}

A: It's a little bit clunky, but for a quick win I just duplicated the code within grid.inlinedit.js in order to recreate buttons that do the same thing in both top and bottom bars... it seems to work.
            if(o.add) {
            $($t).jqGrid('navButtonAdd', elem,{
                caption : o.addtext,
                title : o.addtitle,
                buttonicon : o.addicon,
                id : $t.p.id+"_iladd",
                onClickButton : function ( e ) {
                    $($t).jqGrid('addRow', o.addParams);
                    if(!o.addParams.useFormatter) {
                        $("#"+$t.p.id+"_top_ilsave").removeClass('ui-state-disabled');
                        $("#"+$t.p.id+"_top_ilcancel").removeClass('ui-state-disabled');
                        $("#"+$t.p.id+"_top_iladd").addClass('ui-state-disabled');
                        $("#"+$t.p.id+"_top_iledit").addClass('ui-state-disabled');
                        $("#"+$t.p.id+"_ilsave").removeClass('ui-state-disabled');
                        $("#"+$t.p.id+"_ilcancel").removeClass('ui-state-disabled');
                        $("#"+$t.p.id+"_iladd").addClass('ui-state-disabled');
                        $("#"+$t.p.id+"_iledit").addClass('ui-state-disabled');
                    }
                }
            });

            $($t).jqGrid('navButtonAdd', '#' + $($t)[0].id + '_toppager_left',{
                caption : o.addtext,
                title : o.addtitle,
                buttonicon : o.addicon,
                id : $t.p.id+"_top_iladd",
                onClickButton : function ( e ) {
                    $($t).jqGrid('addRow', o.addParams);
                    if(!o.addParams.useFormatter) {
                        $("#"+$t.p.id+"_top_ilsave").removeClass('ui-state-disabled');
                        $("#"+$t.p.id+"_top_ilcancel").removeClass('ui-state-disabled');
                        $("#"+$t.p.id+"_top_iladd").addClass('ui-state-disabled');
                        $("#"+$t.p.id+"_top_iledit").addClass('ui-state-disabled');
                        $("#"+$t.p.id+"_ilsave").removeClass('ui-state-disabled');
                        $("#"+$t.p.id+"_ilcancel").removeClass('ui-state-disabled');
                        $("#"+$t.p.id+"_iladd").addClass('ui-state-disabled');
                        $("#"+$t.p.id+"_iledit").addClass('ui-state-disabled');
                    }
                }
            });

        }
        if(o.edit) {
            $($t).jqGrid('navButtonAdd', elem,{
                caption : o.edittext,
                title : o.edittitle,
                buttonicon : o.editicon,
                id : $t.p.id+"_iledit",
                onClickButton : function ( e ) {
                    var sr = $($t).jqGrid('getGridParam','selrow');
                    if(sr) {
                        $($t).jqGrid('editRow', sr, o.editParams);
                        $("#"+$t.p.id+"_ilsave").removeClass('ui-state-disabled');
                        $("#"+$t.p.id+"_ilcancel").removeClass('ui-state-disabled');
                        $("#"+$t.p.id+"_iladd").addClass('ui-state-disabled');
                        $("#"+$t.p.id+"_iledit").addClass('ui-state-disabled');
                        $("#"+$t.p.id+"_top_ilsave").removeClass('ui-state-disabled');
                        $("#"+$t.p.id+"_top_ilcancel").removeClass('ui-state-disabled');
                        $("#"+$t.p.id+"_top_iladd").addClass('ui-state-disabled');
                        $("#"+$t.p.id+"_top_iledit").addClass('ui-state-disabled');
                    } else {
                        $.jgrid.viewModal("#alertmod",{gbox:"#gbox_"+$t.p.id,jqm:true});$("#jqg_alrt").focus();
                    }
                }
            });

            $($t).jqGrid('navButtonAdd', '#' + $($t)[0].id + '_toppager_left',{
                caption : o.edittext,
                title : o.edittitle,
                buttonicon : o.editicon,
                id : $t.p.id+"_top_iledit",
                onClickButton : function ( e ) {
                    var sr = $($t).jqGrid('getGridParam','selrow');
                    if(sr) {
                        $($t).jqGrid('editRow', sr, o.editParams);
                        $("#"+$t.p.id+"_ilsave").removeClass('ui-state-disabled');
                        $("#"+$t.p.id+"_ilcancel").removeClass('ui-state-disabled');
                        $("#"+$t.p.id+"_iladd").addClass('ui-state-disabled');
                        $("#"+$t.p.id+"_iledit").addClass('ui-state-disabled');
                        $("#"+$t.p.id+"_top_ilsave").removeClass('ui-state-disabled');
                        $("#"+$t.p.id+"_top_ilcancel").removeClass('ui-state-disabled');
                        $("#"+$t.p.id+"_top_iladd").addClass('ui-state-disabled');
                        $("#"+$t.p.id+"_top_iledit").addClass('ui-state-disabled');
                    } else {
                        $.jgrid.viewModal("#alertmod",{gbox:"#gbox_"+$t.p.id,jqm:true});$("#jqg_alrt").focus();
                    }
                }
            });

        }
        if(o.save) {
            $($t).jqGrid('navButtonAdd', elem,{
                caption : o.savetext || '',
                title : o.savetitle || 'Save row',
                buttonicon : o.saveicon,
                id : $t.p.id+"_ilsave",
                onClickButton : function ( e ) {
                    var sr = $($t).jqGrid('getGridParam','selrow');
                    if(sr) {
                        if($("#"+$.jgrid.jqID(sr), "#"+$.jgrid.jqID($t.p.id) ).hasClass("jqgrid-new-row")) {
                            var opers = $t.p.prmNames,
                            oper = opers.oper;
                            if(!o.editParams.extraparam) {
                                o.editParams.extraparam = {};
                            }
                            o.editParams.extraparam[oper] = opers.addoper;
                        }
                        $($t).jqGrid('saveRow', sr, o.editParams);
                        $("#"+$t.p.id+"_ilsave").addClass('ui-state-disabled');
                        $("#"+$t.p.id+"_ilcancel").addClass('ui-state-disabled');
                        $("#"+$t.p.id+"_iladd").removeClass('ui-state-disabled');
                        $("#"+$t.p.id+"_iledit").removeClass('ui-state-disabled');
                        $("#"+$t.p.id+"_top_ilsave").addClass('ui-state-disabled');
                        $("#"+$t.p.id+"_top_ilcancel").addClass('ui-state-disabled');
                        $("#"+$t.p.id+"_top_iladd").removeClass('ui-state-disabled');
                        $("#"+$t.p.id+"_top_iledit").removeClass('ui-state-disabled');
                    } else {
                        $.jgrid.viewModal("#alertmod",{gbox:"#gbox_"+$t.p.id,jqm:true});$("#jqg_alrt").focus();
                    }
                }
            });
            $("#"+$t.p.id+"_ilsave").addClass('ui-state-disabled');

            $($t).jqGrid('navButtonAdd', '#' + $($t)[0].id + '_toppager_left',{
                caption : o.savetext || '',
                title : o.savetitle || 'Save row',
                buttonicon : o.saveicon,
                id : $t.p.id+"_top_ilsave",
                onClickButton : function ( e ) {
                    var sr = $($t).jqGrid('getGridParam','selrow');
                    if(sr) {
                        if($("#"+$.jgrid.jqID(sr), "#"+$.jgrid.jqID($t.p.id) ).hasClass("jqgrid-new-row")) {
                            var opers = $t.p.prmNames,
                            oper = opers.oper;
                            if(!o.editParams.extraparam) {
                                o.editParams.extraparam = {};
                            }
                            o.editParams.extraparam[oper] = opers.addoper;
                        }
                        $($t).jqGrid('saveRow', sr, o.editParams);
                        $("#"+$t.p.id+"_ilsave").addClass('ui-state-disabled');
                        $("#"+$t.p.id+"_ilcancel").addClass('ui-state-disabled');
                        $("#"+$t.p.id+"_iladd").removeClass('ui-state-disabled');
                        $("#"+$t.p.id+"_iledit").removeClass('ui-state-disabled');
                        $("#"+$t.p.id+"_top_ilsave").addClass('ui-state-disabled');
                        $("#"+$t.p.id+"_top_ilcancel").addClass('ui-state-disabled');
                        $("#"+$t.p.id+"_top_iladd").removeClass('ui-state-disabled');
                        $("#"+$t.p.id+"_top_iledit").removeClass('ui-state-disabled');
                    } else {
                        $.jgrid.viewModal("#alertmod",{gbox:"#gbox_"+$t.p.id,jqm:true});$("#jqg_alrt").focus();
                    }
                }
            });
            $("#"+$t.p.id+"_top_ilsave").addClass('ui-state-disabled');
        }
        if(o.cancel) {
            $($t).jqGrid('navButtonAdd', elem,{
                caption : o.canceltext || '',
                title : o.canceltitle || 'Cancel row editing',
                buttonicon : o.cancelicon,
                id : $t.p.id+"_ilcancel",
                onClickButton : function ( e ) {
                    var sr = $($t).jqGrid('getGridParam','selrow');
                    if(sr) {
                        $($t).jqGrid('restoreRow', sr, o.editParams);
                        $("#"+$t.p.id+"_ilsave").addClass('ui-state-disabled');
                        $("#"+$t.p.id+"_ilcancel").addClass('ui-state-disabled');
                        $("#"+$t.p.id+"_iladd").removeClass('ui-state-disabled');
                        $("#"+$t.p.id+"_iledit").removeClass('ui-state-disabled');
                        $("#"+$t.p.id+"_top_ilsave").addClass('ui-state-disabled');
                        $("#"+$t.p.id+"_top_ilcancel").addClass('ui-state-disabled');
                        $("#"+$t.p.id+"_top_iladd").removeClass('ui-state-disabled');
                        $("#"+$t.p.id+"_top_iledit").removeClass('ui-state-disabled');
                    } else {
                        $.jgrid.viewModal("#alertmod",{gbox:"#gbox_"+$t.p.id,jqm:true});$("#jqg_alrt").focus();
                    }
                }
            });
            $("#"+$t.p.id+"_ilcancel").addClass('ui-state-disabled');

            $($t).jqGrid('navButtonAdd', '#' + $($t)[0].id + '_toppager_left',{
                caption : o.canceltext || '',
                title : o.canceltitle || 'Cancel row editing',
                buttonicon : o.cancelicon,
                id : $t.p.id+"_top_ilcancel",
                onClickButton : function ( e ) {
                    var sr = $($t).jqGrid('getGridParam','selrow');
                    if(sr) {
                        $($t).jqGrid('restoreRow', sr, o.editParams);
                        $("#"+$t.p.id+"_ilsave").addClass('ui-state-disabled');
                        $("#"+$t.p.id+"_ilcancel").addClass('ui-state-disabled');
                        $("#"+$t.p.id+"_iladd").removeClass('ui-state-disabled');
                        $("#"+$t.p.id+"_iledit").removeClass('ui-state-disabled');
                        $("#"+$t.p.id+"_top_ilsave").addClass('ui-state-disabled');
                        $("#"+$t.p.id+"_top_ilcancel").addClass('ui-state-disabled');
                        $("#"+$t.p.id+"_top_iladd").removeClass('ui-state-disabled');
                        $("#"+$t.p.id+"_top_iledit").removeClass('ui-state-disabled');
                    } else {
                        $.jgrid.viewModal("#alertmod",{gbox:"#gbox_"+$t.p.id,jqm:true});$("#jqg_alrt").focus();
                    }
                }
            });
            $("#"+$t.p.id+"_top_ilcancel").addClass('ui-state-disabled');
        }


text:
Q: How to fetch mongo db data and pass in jmeter request I have one post call that response is like this.
{
  "status":0,
  "message":"Prescription Created",
  "jsonResponse":{},
  "cid":"C5975K",
  "pid":"Rx5975K-175A",
  "prescriptionSource":"GO_RX_CTO",
  "imageStatus":[]
}

By taking this pid , I have to do the query for the one more record. For example:
db.order.find({"pid":"Rx5975K-175A"})

and the result of this query should pass in one more jmeter request.
I have used MongoDB Script (DEPRECATED) .. But this wont work as its deprecated ..
Tried with JSR223 Sampler, but its not working in new jmeter 3.2
import com.mongodb.*
import com.mongodb.BasicDBObject

    MongoCredential coreCredential = MongoCredential.createCredential("${mongodb_user}", "${mongodb_database}", "${mongodb_password}".toCharArray());
    MongoClient coreMongoClient = new MongoClient(new ServerAddress("${mongodb_server}", 13017), Arrays.asList(coreCredential));
    DB coreDB = coreMongoClient.getDB("${mongodb_database}");
    DBCollection coll = coreDB.getCollection("order");
    coll.find();

A: You have to find your result based on "pid" and you are nowhere passing it. After finding you collection you need to create a query and searching using that query.
import com.mongodb.*
import com.mongodb.BasicDBObject
MongoCredential coreCredential = MongoCredential.createCredential("${mongodb_user}", "${mongodb_database}", "${mongodb_password}".toCharArray());
MongoClient coreMongoClient = new MongoClient(new ServerAddress("${mongodb_server}", 13017), Arrays.asList(coreCredential));
DB coreDB = coreMongoClient.getDB("${mongodb_database}");
DBCollection coll = coreDB.getCollection("order");
BasicDBObject query = new BasicDBObject();
query.put("pid", "Rx5975K-175A");
DBObject  getData= coll.findOne(query);

and this will give you the desire result


text:
Q: Token based authentication using ADFS I am working with the functionality to integrate ADFS login page with my application.
Flow
User will try to visit page. Here system will try to authenticate user.
System will redirect user to ADFS login page.
User will enter login information. If user is authenticated then user will be redirected back to the application with authorized token information.
I am facing difficulties to read the token information when the page is redirected back.
I tried
I am able to redirect page to ADFS login page and also can redirect back to my system if the user is authenticated using below url format:
https://adfs-domain-name/adfs/ls
Please find the below code snippet which I am using after getting back the page to read token information.
ClaimsPrincipal claimsPrincipal = Thread.CurrentPrincipal as ClaimsPrincipal;
bool IsAuthenticated = claimsPrincipal.Identity.IsAuthenticated;
int ClaimCount = claimsPrincipal.Claims.Count();

Here I am getting IsAuthenticated as false and ClaimCount as 0 result.
Is there anything incorrect in my code or way to connect ADFS login page ?
Can anyone help me to fix this ?
Please let me know if you have any concern or query or if I am missing something.

A: In short, I would recommend following this tutorial:
https://learn.microsoft.com/en-us/windows-server/identity/ad-fs/development/enabling-openid-connect-with-ad-fs-2016
I followed the steps in there and got it to work (using OAuth2 / OpenID connect). There are some other interesting resources on that site, too.
Some more pointers:
1) For using OAuth2 the login URL on the ADFS server should be something like:
  https://adfs.contoso.com/adfs/oauth2/authorize?[parameters]
The URL parameters are nicely documented here:
https://learn.microsoft.com/en-us/azure/active-directory/develop/active-directory-protocols-oauth-code
2) You can then use the ADAL libraries for the frontend and backend code. In essence, the frontend code will put together the aforementioned login URL and keep the token in the browser's session storage to be sent with each request. The backend library will verify and decode the tokens (into ClaimsPrincipal) for you. You can find the appropriate library components here:
https://learn.microsoft.com/en-us/azure/active-directory/develop/active-directory-authentication-libraries
Ah, yeah, I know these components and docs describe Azure AD (ADFS in the cloud), but what they run there is essentially the same as ADFS 4.0 on Windows Server 2016.


text:
Q: Accessing LinkedIn API using OAuth 2.0 I want to access my top 5 linkedIn posts. I have generated the oauth access token from the admin user id but when I hit LinkedIn API with that generated token, it gives me permission error "Member does not have permission to get company." Please assist if I am missing anything

A: Referring to their API change logs, it seems you need to be flagged as an admin of the company's linkedin page to access the company REST api.
New requirement for Companies API

All calls to Companies API endpoints will require the authenticated user to be flagged as an administrator of the LinkedIn Company Page that is the target of the API call.  You become the administrator of a page when you create it.  If the page already exists, you will have to contact the existing administrator to grant admin access to other LinkedIn members.
Your API call will return a 403 Forbidden error if you do not have the appropriate admin permission to interact with the target company.

Source: https://developer.linkedin.com/support/developer-program-transition


text:
Q: Protractor Accept a Prompt My AngularJS application uses Keycloak for auth. and it opens a window prompt to ask the user to enter a domain name.
angular.element(document).ready(function () {
var domain;
if (Modernizr.localstorage) {
    domain = window.localStorage['com.example.domain'];
}
if (!domain) {
    domain = window.prompt("Enter your customer domain:\n\nNote: This has to be entered only once.", "example.com");
    if (domain && Modernizr.localstorage) {
        window.localStorage['com.example.domain'] = domain;
    }
}

If I run my test with safari, I can close this prompt once, login using Keycloak and every other test runs succesfully. But in chrome this prompt opens everytime running the test.
How can I get Chrome to close this prompt and continue to the login page?
I tried
 browser.wait(EC.alertIsPresent()).then(function () {
        browser.driver.switchTo().alert().then(function (alert) {
            alert.accept();
        });
    });

or
 browser.wait(EC.alertIsPresent()).then(function () {
        browser.driver.switchTo().alert().then(function (alert) {
            alert.accept();
        });
    });

But I still get the unexpected alert error

A: I'm not sure what version of protractor you are running but ever since 2.0 the time on browser.waits have changed
"Due to changes in WebDriverJS, wait without a timeout will now default
to waiting for 0 ms instead of waiting indefinitely."
https://github.com/angular/protractor/blob/master/CHANGELOG.md#breaking-changes
you might be able to try it without a .then() as below
browser.wait(EC.alertIsPresent(), 5000);
browser.switchTo().alert().accept();

also I noticed you mention trying two different things but I believe you made a typo because they are both the same.

I tried
 browser.wait(EC.alertIsPresent()).then(function () {
        browser.driver.switchTo().alert().then(function (alert) {
            alert.accept();
        });
    });

or
 browser.wait(EC.alertIsPresent()).then(function () {
        browser.driver.switchTo().alert().then(function (alert) {
            alert.accept();
        });
    });

But I still get the unexpected alert error

And you mention closing the prompt once in Safari, Is this manually or via the test? If it's via the test, what code are you using to do that


text:
Q: how to display images from (block content) rich text in portable text how to display images from (block content) rich text in portable text using sanity as backend and next js as front end.
my portable text look like this
<PortableText
 value={blog.body}
/>

no variable or const are associated with it.
display all text and other fields expect images.

A: You can pass an object of components to render your custom content types such as images.
First, create an object for your PortableText custom components, and return your image component for the image type.
const myPortableTextComponents = {
  types: {
    image: ({ value }) => {
      return (
        <SanityImage {...value} />
      );
    },
  },
};

Second: Create your ImageComponent. I'm using the next-sanity-image plugin here to use the image with NextJS Image component.
import {useNextSanityImage} from 'next-sanity-image'
import Image from 'next/image';

const sanityConfig = sanityClient({
  projectId: process.env.NEXT_PUBLIC_SANITY_PROJECT_ID,
  dataset: process.env.NEXT_PUBLIC_SANITY_DATASET,
  useCdn: true
});

const SanityImage = ({ asset }) => {
  const imageProps = useNextSanityImage(sanityConfig, asset);

  if (!imageProps) return null;

  return (<Image
    {...imageProps}
    layout='responsive'
    sizes='(max-width: 800px) 100vw, 800px'
  />);
}

Finally, pass the custom components object to your PortableText component via the components prop.
<PortableText
  value={body}
  components={myPortableTextComponents}
/>

You can learn more about rendering PortableText in React here and more about the next-sanity-image plugin here


text:
Q: Como pausar a execução por um tempo (similar a um "wait" ou "sleep")? Esse código está funcionando e rodando em uma conta existente nesse site, o que eu quero fazer é: Adicionar uma pausa, um tipo de While, Wait, Sleep ou ReadyState, após o login e antes de ir para a nova aba. Essa linha substituiria a linha do window.close().
<html>
    <head>
      <title>L2 CR AUTO LOGIN</title>
    </head>
    <body>
      <form id="loginForm" name="loginForm" method="post"    action="http://zionweb.l2cr.com/gamecpc6/index.php">
        <select name="uni_url" id="logServer" class="validate[required]">
          <option  class=""  value="http://zionweb.l2cr.com/gamecpc6/index.php" fbUrl=""  cookieName=""  >
             Personagem1
          </option>
        </select>
        <input id="username" name="username" type="text" value="CHECKBOSS" class="" />
        <input id="password" name="password" type="password" value="123456" class="" />
        <input type="hidden" id="loginKid" name="kid" value=""/>
        <button onclick="myFunction()">Enter</button>
      </form>

      <script> function myFunction() {
         document.loginForm.submit();
         window.close();
         window.open("http://zionweb.l2cr.com/gamecpc6/classes/view_templates/rbs.php");
      } </script>
    </body>
</html>

A: Como nao ficou especificado se voce faz o login da conta por um ajax ou por uma api vou deixar uma solução  simples, porem não a mais aconselhável, voce pode usar o setTimeout para determinar um tempo para executar uma função x, mas acredito que o mais aconselhavel neste caso e analisar qual e o callback possível do ajax/api para poder realizar outra ação.

setTimeout(alerta, 3000); // segundo parámetro e o timing para executar a função

function alerta() {
  alert("LOL");
}


text:
Q: Is it possible to use Firebase Realtime Database to implement a distributed mutex? I was thinking of using a transaction like so to implement a kind of distributed lock:
const lockId = 'myLock';
const lockRef = firebaseAdmin.database().ref(`/locks/${lockId}`);
lockRef.transaction(function(current) {
  if (current === null) {
    return '1';
  }
}, function(error, committed) {
  if (committed) {
    // .... Do the synchronized work I need ...
    lockRef.remove();
  }
});

The question I have is: will the update function be called with null only if the data does not exist?
Generally, is this a valid way to implement a distributed lock?

A: Your initial attempt would not work for reasons @FrankvanPuffelen stated in their answer.
But it is possible (although not really that straightforward) to accomplish this. I battled quite a long with different edge cases, and finally came up with this solution that passes a myriad of different tests which verify that this prevents all possible race conditions and deadlocks:
import crypto from 'crypto';
import { promisify } from 'util';

import * as firebaseAdmin from 'firebase-admin';

const randomBytes = promisify(crypto.randomBytes);

// A string which is stored in the place of the value to signal that the mutex holder has
// encountered an error. This must be unique value for each mutex so that we can distinguish old,
// stale rejection states from the failures of the mutex that we are currently waiting for.
const rejectionSignal = (mutexId: string): string => `rejected${mutexId}`;

const isValidValue = (value: unknown): boolean => {
  // `value` could be string in the form `rejected...` which signals failure,
  // using this function makes sure we don't return that as "valid" value.
  return !!value && (typeof value !== 'string' || !value.startsWith('rejected'));
};

export const getOrSetValueWithLocking = async <T>(id: string, value: T): Promise<T> => {
  const ref = firebaseAdmin.database().ref(`/myValues/${id}`);

  const mutexRef = firebaseAdmin.database().ref(`/mutexes/myValues/${id}`);

  const attemptingMutexId = (await randomBytes(16)).toString('hex');

  const mutexTransaction = await mutexRef.transaction((data) => {
    if (data === null) {
      return attemptingMutexId;
    }
  });

  const owningMutexId = mutexTransaction.snapshot.val();

  if (mutexTransaction.committed) {
    // We own the mutex (meaning that `attemptingMutexId` equals `owningMutexId`).
    try {
      const existing = (await ref.once('value')).val();
      if (isValidValue(existing)) {
        return existing;
      }
      /*
        --- YOU CAN DO ANYTHING HERE ---
        E.g. create `value` here instead of passing it as an argument.
      */
      await ref.set(value);
      return value;
    } catch (e) {
      await ref.set(rejectionSignal(owningMutexId));
      throw e;
    } finally {
      // Since we own the mutex, we MUST make sure to release it, no matter what happens.
      await mutexRef.remove();
    }
  } else {
    // Some other caller owns the mutex -> if the value is not yet
    // available, wait for them to insert it or to signal a failure.
    return new Promise((resolve, reject) => {
      ref.on('value', (snapshot) => {
        const val = snapshot.val();
        if (isValidValue(val)) {
          resolve(val);
        } else if (val === rejectionSignal(owningMutexId)) {
          reject(new Error('Mutex holder encountered an error and was not able to set a value.'));
        } // else: Wait for a new value.
      });
    });
  }
};

My use case for this was that I had Next.js API routes running in Vercel, where the only shared state of the parallelly executing serverless functions was a Firebase Realtime Database.

A: A transaction will be called initially with the client's best guess to the current value. If the client doesn't have a current value in memory, its best guess is that there is no current value.
That means that there is no guarantee whatsoever that no value actually exists in the database if you get a null.
Also see:

*

*Firebase transaction api call current data is null

*Firebase runTransaction not working - MutableData is null


text:
Q: Override Activity from Android Library project I have an Android project.  Now I need to create a second edition of that project.
What will differ:
New edition of the Project should have different content in one of the Activities.
I was thinking about creating a library project and two new projects(project1 and project2) which will use library project, but I don't really understand how to setup this.
Should I just convert the original project into library, then create two new projects and then what? How to make project1 use activity1 and project2 use activity2 in  the same place?
EDIT
What I've set up so far:
MainProject, a library has MainActivity.java and ChildActivity.java

AndroidManifest.xml
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.mainproject">
    <application>
        <activity
            android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name=".ChildActivity">
        </activity>
    </application>
</manifest>

MainActivity.java
   public class MainActivity extends Activity {

        @Override
        public void onCreate(Bundle savedInstanceState) {

            ((Button)findViewById(R.id.button1)).setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(MainActivity.this, ChildActivity.class);
                    startActivity(intent);
                }
            });
        }
}

StandAloneProject: it has only ChildActivity.java

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.standaloneproject">
    <application>
        <activity
             android:name="com.example.mainproject.MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name=".ChildActivity" >
        </activity>
    </application>
</manifest>

What I expect:
When I launch StandAloneProject and click button, I want ChildActivity from StandAloneProject(not from MainProject) to be launched.
What I get:
When I launch StandAloneProject, I see MainActivity from MainProject, click button and get:
android.content.ActivityNotFoundException: Unable to find explicit activity class {com.example.standaloneproject/com.example.mainproject.ChildActivity}; have you declared this activity in your AndroidManifest.xml?

A: The problem is how you start the child activity in MainActivity.java.
You need to 'manually' make sure that the correct ChildActivity is started.
One way to do this is to explicitly set the component for the intent.  The Context.getPackageName() function returns the package name of the application you are running in and you can use this to identify the 'correct instance' of ChildActivity you want to start.  Try this in your onClick() handler in MainActivity.java:
    Intent intent = new Intent();
    intent.setComponent(new ComponentName(getPackageName(), getPackageName() + ".ChildActivity"));
    startActivity(intent);

A: Your approach is the correct one.

*

*Create your library project.

*Create a new project, create the activity that you need and add your library project to it.

*Copy the AndroidManifest.xml from your library project into your new project but point the activity that differs to the projects activity instead of the activity in the library project.

A: You are on the right track. Set up a library project and two standard android projects which include the lib project.
Remember to copy your manifest activitys to the new projects. When you want to separate the activitys, you can extend the ones from your lib project. project1: MyActivty extends Activit1 .. project 2 MyActivit


text:
Q: C: Weird behavior after calling realloc() when using fgets() to store strings in a dynamic buffer The following code loads in a text file called gasses.txt that has 16 terms, each on its own line, and stores these terms one at a time in the buffer search_terms.
#define MAX_LINE_LEN 40
FILE *dict_fp;
int term_len;
int j;

size_t number_search_terms = 10;
int i;
char **search_terms = malloc(sizeof(char *) * number_search_terms);
for (i=0; i < number_search_terms; i++)
    search_terms[i] = malloc(MAX_LINE_LEN);

dict_fp = fopen("gasses.txt", "r");
for (i=0; fgets(search_terms[i], MAX_LINE_LEN, dict_fp) != NULL; i++){

    // get rid of the newline.
    term_len = strlen(search_terms[i]);
    search_terms[i][term_len-1] = 0;

    // resize buffer when it gets full
    if (i == number_search_terms-1){
        number_search_terms *= 2;
        search_terms = realloc(search_terms, number_search_terms);
        for (j = number_search_terms/2; j < number_search_terms; j++)
            search_terms[j] = malloc(MAX_LINE_LEN);
    }

    printf("%s\n", search_terms[i]);

    printf("%s\n\n", search_terms[0]);

}

The output looks like this. After the first memory reallocation, the string stored in search_terms[0] gets corrupted.
nitrogen
nitrogen

oxygen
nitrogen

argon
nitrogen

carbon dioxide
nitrogen

neon
nitrogen

helium
nitrogen

methane
nitrogen

krypton
nitrogen

hydogen
nitrogen

nitrous oxide
���

xenon
���

ozone
���

nitrogen dioxide
���

iodine
���

ammonia
���

water vapour
���

This is gasses.txt:
oxygen
argon
carbon dioxide
neon
helium
methane
krypton
hydogen
nitrous oxide
xenon
ozone
nitrogen dioxide
iodine
ammonia
water vapour

A: When you first malloc for search_terms, you correctly use sizeof(char *) * number_search_terms for the size.
However, when you realloc, you use number_search_terms instead. This new size is 1/4 or 1/8 the correct size (depending on your pointer size) and so you end up writing past the end of this buffer.


text:
Q: how to understand Artin-Rees lemma I know this lemma is very important.it can be used to prove Krull Intersection Theorem.but I think maybe this is very difficult to understand.And I also do not know how to use this lemma.

 -
What is the most importance of this?
-how to understand the meaning of this lemma?


text:
Q: Find posterior distribution of $\varepsilon$ in a uniform distribution on $[0, \frac{1}{6}]$
An unfair die rolls "6" with a probability $\frac{1}{6} + \varepsilon$, where $\varepsilon$ has a priori uniform distribution on $[0, \frac{1}{6}]$. Find posterior distribution of $\varepsilon$ knowing that the first toss was "6" and the second toss was "2".

A priori density function is $f_0(x) = \frac{1}{6} \chi_{[0, \frac{1}{6}]}(x)$ and the probabilities of tossing a six and a "non-six" are $\frac{1}{6} + \varepsilon$ and $\frac{5}{6} - \varepsilon$ respectively, so the probability of obtaining such sample is
$$P_\varepsilon(\underline{X}) = P(X_1 = \text{"6"}, X_2 = \text{not "6"}) = (\frac{1}{6} + \varepsilon)(\frac{5}{6} - \varepsilon)$$
Therefore the posterior density function would be (please correct me if I'm wrong):
$$f_1(\varepsilon) = \frac{P_\varepsilon(\underline{X}) \cdot f_0(\varepsilon)}{\int \limits_{E} P_\varepsilon(\underline{X}) f_0(\varepsilon)} d\varepsilon$$
$$= \frac{(\frac{1}{6} + \varepsilon)(\frac{5}{6} - \varepsilon) \frac{1}{6}  \chi_{[0, \frac{1}{6}]}(\varepsilon)}{\int \limits_0^{\frac{1}{6}} (\frac{1}{6} + \varepsilon)(\frac{5}{6} - \varepsilon) \frac{1}{6}  d\varepsilon}$$
$$ = \frac{162}{5}(\frac{1}{6} + \varepsilon)(\frac{5}{6} - \varepsilon) \chi_{[0, \frac{1}{6}]}(\varepsilon)$$
Is my reasoning valid? Or should there be no characteristic function in the final formula, since we're considering a specific $\varepsilon$ at this point? I'm still confused with continuous variables in the Bayesian approach.

A: I thought this was correct up to a constant factor, but after doing the work got the same answer.
I was thinking you have to take into account the number of arrangements of the event $\{\textrm{One Success}\land\textrm{One Failure}\}$, but if you reformulate the problem assuming the events are exchangeable "successes", and view the number of them as counts in the Binomial distribution, you get the same answer.
I'll just put the calculations up in case it helps anyone.
Letting $\gamma_i = I(X_i = 6)$ and $1-\gamma_i = I(X_i = \{6\}^c)$. Then, specifying $p = P[\gamma_i = 1] = \epsilon + \frac{1}{6}$. Under this specification $p$ has an induced prior of the form: $p\sim\textrm{Unif}(\frac{1}{6},\frac{2}{6})$. It also follows that:
\begin{equation}
\begin{split}
P[\sum_{i=\{1,2\}}\gamma_i = n] \sim \textrm{Binom}(n|2,p)
\end{split}
\end{equation}
From the exchangeability of $X_1$ and $X_2$, the binomial distribution is appropriate. We observed $\sum_{i=\{1,2\}}\gamma_i = 1$ which has probability $P[\sum_{i=\{1,2\}}\gamma_i = 1] = \binom{2}{1}p^1(1-p)^1 = 2p(1-p)$.
Doing the integration, we get the following posterior distribution on $p$:
\begin{equation}
\begin{split}
P[p|\underline{X}] & = \frac{2p(1-p)\frac{1}{6}I(p\in[\frac{1}{6},\frac{2}{6}])}{\int_{\frac{1}{6}}^\frac{2}{6}2p(1-p)\frac{1}{6}I(p\in[\frac{1}{6},\frac{2}{6}])}\\
& = \frac{162}{5}p(1-p)I(p\in[\frac{1}{6},\frac{2}{6}])\\
&  = \frac{162}{5}p(1-p)I(p\in[\frac{1}{6},\frac{2}{6}])
\end{split}
\end{equation}
This induces a posterior on $\epsilon$ of the form:
\begin{equation}
\begin{split}
P[\epsilon|\underline{X}] & =  \frac{162}{5}(\epsilon - \frac{1}{6})(\frac{5}{6}-\epsilon)I(\epsilon\in[0,\frac{1}{6}])
\end{split}
\end{equation}


text:
Q: How to send Post request to Rest API with XML data I have created a rest API(apex class) in Salesforce. I have multiple nested tags in xml that comes via API request. I am wondering how do I define my post method in apex that could handle the request. Do I have to list all the fields as parameters in the method or is there a way to use DOMElement as a parameter while defining the method and then I go about extracting the data out of it.
XML Data via API:
<TestContact xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:xsl="http://www.w3.org/2001/XMLSchema-instance">

<VendorData>
  <CompanyAffiliation>Test</CompanyAffiliation >  *MUST HAVE *
  <Vendor>Test Vendor</Vendor>  * MUST HAVE *
  <VendorID>xyz1234567</VendorID> * MUST HAVE *
</VendorData>

<Contact>
  <FirstName>TestFirstName</FirstName> * MUST HAVE *  Lead
  <LastName>TestLastName</LastName> * MUST HAVE * Lead

</contact>

</TestContact>

Rest API in Salesforce:(Approach 1)
@RestResource(urlMapping='/api/*/createContact')
global with sharing class RESTAPI_JSON_XML
{
    @HttpPost
    // Is this the right way to define input parameters??

    global static void doPost(String CompanyAffiliation, String Vendor, String VendorId, String FirstName, String Lastname  ) {

    RestResponse standardResp = RestContext.response;
    REST_API_Helper.ResponseBase  CustomeResponse = new
    REST_API_Helper.ResponseBase();
    ContactDetail reqBodyObj = Detail;

    RestRequest req = RestContext.request;
    String ContentType = RestContext.request.headers.get('Content-Type') ;

    // I don't know how to parse it and put it into appropriate objects

    Vendor__c vendor= new Vendor__c();
    vendor.Company_Affiliation__c=reqBodyObj.CompanyAffiliation;
    vendor.Vendor__c=reqBodyObj.Vendor;
    vendor.VendorID__c=reqBodyObj.VendorID__c;
    insert vendor;

    Contact con = new Contact();
    con.FirstName = reqBodyObj.FirstName.trim();
    con.LastName  = reqBodyObj.LastName.trim();
    insert cont;

    CustomeResponse.Success = true;
    CustomeResponse.Message = 'Contact Created id ='+cont.id;
    standardResp.statusCode = 200;
    standardResp.responseBody =
    REST_API_Helper.formatResponse(CustomeResponse,ContentType);

   }

}

Rest API in Salesforce:(Approach 2)
@RestResource(urlMapping='/api/*/createContact')
global with sharing class RESTAPI_JSON_XML
{
    @HttpPost
    // Is there a way to define one input parameter that captures all the incoming information and then extract it in the body??

    global static void doPost(XMLDOMElement Detail  ) {

     ........=   Detail.CompanyAffiliation;
     ........=   Detail.FirstName;

    }

}

What is the best approach to define the post method from the above two approaches and how can I parse the information using the suggested approach(any parsing/data extracting methods)? Any sample code?

A: parsing/deserializing
Dealing with XML in Apex is a pain. The best approach that I've found so far is to use the classes in the Dom namespace, Dom.Document and DOM.XmlNode, in combination with a class structure that mimics the schema of your XML.
Think of it like creating the class structure that you'd need to deserialize the data if it were JSON. The difference with XML is that you'd need to add some logic to take a Dom.XmlNode and extract the data into class variables yourself.
Your flow here is then: receive request -> use Dom.Document.load() to do the parsing -> send Dom.XmlNodes into the "deserialization" classes to make it easy to use the data in Apex.
A search on XML answers that I've given should help out, but in interest of not just saying "here's the link, go there", here's a reproduction of one of the example "deserialization" class(es) that I've given.

public class Permissions{
    // 'Permission' is an inner class, which is defined below.
    // I find it helpful to have class names and variable names mirror the names used
    //   in the XML document as closely as possible.
    public List<Permission> userPermissions;

    public Permissions(String xmlInput){
        Dom.Document inputDoc = new Dom.Document();
        inputDoc.load(xmlInput);

        process(inputDoc.getRootElement());
    }

    // If you're going to use this in a visualforce page, you'll need to manually
    //   implement getter methods.
    public List<Permission> getUserPermissions(){
        return userPermissions;
    }

    // Each inner class will need a 'process' method like this one.
    private void process(Dom.XmlNode inNode){
        String currentNodeName;
        userPermissions = new List<Permission>();

        for(Dom.XmlNode childNode :inNode.getChildElements()){
            currentNodeName = childNode.getName();

            // When we come across a node that we want to handle, we simply create
            //   a new instance of the appropriate inner class, and pass the node
            //   to its process() method.
            // Each inner class should specialize in handling a specific type of XmlNode.
            // This helps to prevent the parsing logic from getting too unwieldy in
            //   any one class.
            if(currentNodeName == 'userPermissions'){
                Permissions perm = new Permission();
                perm.process(inNode);

                // After we're done processing the current node, we can add it
                //   to the list.
                userPermissions.add(perm);
            }
        }
    }

    // When we get down to a level where a child element contains just a string,
    //   then there's little use in creating one more level of inner classes.
    // Such child elements can just be made variables of this class.
    public class Permission{
        // Again, variable names mirror those found in the XML document.
        public String name;
        public Boolean enabled;

        public Permission(){
        }

        // Again, getters are required for visualforce
        public Boolean getEnabled(){
            return enabled;
        }

        public String getName(){
            return name;
        }

        // This method should look like it has something in common with the 'process()'
        //   method of the outer class.
        // Having the same general structure makes this pattern easy to expand to
        //   be able to parse more complicated XML structures.
        public void process(Dom.XmlNode inNode){
            String currentNodeName;

            for(Dom.XmlNode childNode :inNode.getChildElements()){
                currentNodeName = childNode.getName();

                // Note: The order that you check currentNodeName values in doesn't matter at all
                if(currentNodeName == 'enabled'){
                    // For everything that isn't a string, we'll need to use the
                    //   appropriate 'valueOf()' method to convert to the correct type
                    enabled = Boolean.valueOf(childNode.getText());
                } else if (currentNodeName == 'name'){
                    // For strings, we don't need any special treatment
                    name = childNode.getText();
                }
            }
        }
    }
}

The xml that this example covers is some Salesforce metadata
<Profile xmlns="http://soap.sforce.com/2006/04/metadata">
    <custom>true</custom>
    <userLicense>Salesforce</userLicense>
    <userPermissions>
        <enabled></enabled>
        <name></name>
    </userPermissions>
    <userPermissions>
    </userPermissions>
    <!-- etc... -->

The idea is that by having each deserialization class contain a process() method, and calling that in the constructor, we can spread the load of extracting data from the XML to make each level of processing more manageable.
returning xml
A Visualforce page is actually a really easy way to accomplish this. Instead of html tags and things like <apex:pageBlockTable>, you simply make your VF page spit out the xml tags you want. <apex:repeat> is still very helpful here. The VF page is your template, and generates your xml using the data you get from your controller and/or extension.
// If there's any page parameters that need setting, now's the time to set them
Map<String, String> pageParams = ApexPages.currentPage().getParameters();

pageParams.put('id', '<some sobject record id here>');

ApexPages.PageReference myXmlTemplate = Page.XmlTemplate;

// Be careful, because this counts as a callout (no DML, scheduling a batch, enqueuing a queueable,
//   future method call, etc... before calling this)
// This won't work when called as part of a test method
// I don't think the resulting Blob is base64 encoded, and should be able to be used in
// HttpResponse.setBodyAsBlob()
Blob xmlContent = myXmlTemplate.getContent();

One last warning
While this helps make XML data more usable in Apex, it's not an insignificant amount of work.
There's also no tool I know of to do the work for you (unlike the JSON2Apex heroku app thingy that works for JSON). Every different XML payload you work with will probably need its own set of deserialization classes/logic/tests (it's very domain-specific).
Testing these things is a pain unto itself.

A:
Do I have to list all the fields as parameters in the method or is there a way to use DOMElement as a parameter while defining the method and then I go about extracting the data out of it.

One Approach is like declare your http post method with no parameters and when you pass the XML request body it will be copied in the RestRequest.requestBody as Blob.Then you can convert to string and pass it Dom.Document.load() something like below and parse it.
  @RestResource(urlMapping='/api/*/createContact')
    global with sharing class RESTAPI_JSON_XML{
      @httppost
        global static void doPost(){
            RestRequest req = RestContext.request;
            system.debug('XML String---'+req.requestBody.toString());
            DOM.Document doc=new DOM.Document();
            doc.load(req.requestBody.toString());
            DOM.XmlNode rootNode=doc.getRootElement();
            //XML Parsing
        }
     }

A: You can use my XML Serializer. Here is the link to it: https://github.com/skolakan/Apex-XML-Serializer
Here is how you can approach it
1. Create Apex class that matches the XML
    Since yours is a simple XML, you can just convert it to JSON (there are many online converters for ex:https://codebeautify.org/xmltojson and use https://json2apex.herokuapp.com/ to convert json to Apex). Change the class names to be different from variable names to avoid confusion.
I got the following class
public class clsContactData {

    public clsTestContact TestContact;

    public class clsTestContact {
        public clsVendorData vendorData;
        public clsContact Contact;
    }

    public class clsVendorData {
        public String CompanyAffiliation;
        public String Vendor;
        public String VendorID;
    }

    public class clsContact {
        public String FirstName;
        public String LastName;
    }
}

*Use XML Serializer to deserialize your XML to Apex object

    XMLSerializer serializer = new XMLSerializer();

    clsContactData contactData = (clsContactData) serializer.deserialize(xmlString, clsContactData.Class, new Set<String>());

    system.debug('Contact First Name: ' + contactData.TestContact.Contact.FirstName);

Debug statement resulted in
|DEBUG|Contact First Name: TestFirstName


text:
Q: mypy allow redefinition at a specific line I'm trying to lint my python code with mypy. A utility that I depend on uses a callback to which arguments can take multiple types. Type is typically defined by an accompanying topic string.
I'm having an issue in a situation where a callback takes multiple topics, each with a unique type. In this case, I'm unsure how to communicate to mypy that type is more restricted than the union of the two.
def callback(self, topic: str, msg: Union[A, B]):
    if topic == "a":
        msg: A
        # Do something specific to topic "a"
    if topic == "b":
        msg: B
        # Do something specific to topic "b"

I've tried writing msg: A  # type: ignore instead, but then mypy just ignores this line. I also cannot use isinstance due to the that utility's structure.
Potential solutions
There are two things that I believe should work, but I'm uncertain if mypy has such capabilities:

*

*Allow redefinition on specific line. When running with --allow-redefinition the error is suppressed. Unfortuantely, running it for the whole package is too loose in my view, so I would prefer to avoid it.

*Bind type of variable to value of another variable. I'm unsure if it exists, but it can be similar to TypedDict where keys can bind to different types of values, instead on two separate variables.

A: Overload signatures will make your function externally correct, even if you have to cast on the inside.
class Example:

    @overload
    def callback(self, topic: Literal["a"], msg: A) -> None: ...
    @overload
    def callback(self, topic: Literal["b"], msg: B) -> None: ...
    def callback(self, topic: str, msg: Union[A, B]):
        if topic == "a":
            a_msg = cast(A, msg)
            reveal_locals()
        if topic == "b":
            b_msg = cast(B, msg)
            reveal_locals()

(Note: Literal was added to typing in Python 3.8. If you're using an earlier version, you can get it from typing_extensions)
Inside the function, we still have to cast explicitly, but externally, the caller will always be required to call the function with either (1) the literal "a" and an A, or (2) the literal "b" and a B.

A: It takes some annoying boilerplate and a bit of a hack, but you can do this with a PEP 647 TypeGuard.
TypeGuards exist to tell MyPy that some custom function is able to do type narrowing in a similar way to things like isinstance. For example, you might have a function which takes a list and returns True if everything in that list is an integer:
def are_all_ints(probe: List[Any]) -> TypeGuard[List[int]]:
    return all(isinstance(int, p) for p in probe)

xs: List[Any] = ...

if are_all_ints(xs):
    # MyPy trusts the check was done correctly and therefore
    reveal_type(xs) # this gives List[int] within this section

As you can see, TypeGuards operate on the variable that is passed to them. You could get narrowing of your topic string if you pass it to a suitable typeguard function, but not of msg. The workaround for that is to package them together into a temporary variable.
def callback(self, topic: str, msg: Union[A, B]):

    def is_callback_from_a(p: Tuple[str, Union[A, B]]) -> TypeGuard[Tuple[Literal["a"], A]]:
        return p[0] == "a"

    def is_callback_from_b(p: Tuple[str, Union[A, B]]) -> TypeGuard[Tuple[Literal["b"], B]]:
        return p[0] == "b"

    # Package the two parameters into one variable so that
    # the guard clears them simulataneously
    topic_msg_pair = (topic, msg)

    if is_callback_from_a(topic_msg_pair):
        ...
        # topic_msg_pair[1] is known to be an A here
    elif is_callback_from_b(topic_msg_pair):
        ...
        # topic_msg_pair[1] is known to be a B here


text:
Q: Peewee 3 - Order by and Recursive common table expression (cte) Tools: Peewee 3, SQLite, Python 3
Official documentation for Peewee 3 recursive common table expression (cte):
http://docs.peewee-orm.com/en/latest/peewee/querying.html#common-table-expressions
I am storing a family tree in a simple self-referencing table called Person.
Structure (see below): id, name, parent, custom_order
Notes:
- parent field equals null if this person is an ancestor / root item, otherwise equals to id of parent record if this person is a child
- custom_order is a float number (score to determine who is the user's favourite person)
Objective:
I would like to retrieve the whole family tree and ORDER the results FIRST by parent and SECOND by custom_order.
Issue:
I managed to get the results list but the ORDER is wrong.
DB model
class Person(Model):
    name = CharField()
    parent = ForeignKeyField('self', backref='children', null = True)
    custom_order = FloatField()

Note: if parent field is null then it's a root item
Query code
# Define the base case of our recursive CTE. This will be people that have a null parent foreign-key.
Base = Person.alias()
base_case = (Base
    .select(Base)
    .where(Base.parent.is_null())
    .cte('base', recursive=True))

# Define the recursive terms.
RTerm = Person.alias()
recursive = (RTerm
    .select(RTerm)
    .join(base_case, on=(RTerm.parent == base_case.c.id)))

# The recursive CTE is created by taking the base case and UNION ALL with the recursive term.
cte = base_case.union_all(recursive)

# We will now query from the CTE to get the people
query = cte.select_from(cte.c.id, cte.c.name, cte.c.parent_id, cte.c.custom_order).order_by(cte.c.parent_id, cte.c.custom_order)

print(query.sql())

Printed query syntax
('WITH RECURSIVE "base" AS
(
SELECT "t1"."id", "t1"."name", "t1"."parent_id", "t1"."custom_order" FROM "person" AS "t1" WHERE ("t1"."parent_id" IS ?)
UNION ALL
SELECT "t2"."id", "t2"."name", "t2"."parent_id", "t2"."custom_order" FROM "person" AS "t2" INNER JOIN "base" ON ("t2"."parent_id" = "base"."id")
)
SELECT "base"."id", "base"."name", "base"."parent_id" FROM "base"
ORDER BY "base"."parent_id", "base"."custom_order"',
[None])

A: Root of the problem
The code posted in the question works correctly. I verified it by printing the query results to the console:
query = cte.select_from(cte.c.id, cte.c.name, cte.c.parent_id, cte.c.custom_order).order_by(cte.c.parent_id, cte.c.custom_order).dicts()
print(json.dumps(list(query), indent=4))

The problem originated from the fact that I was passing the query results  to a nested python Dictionary before printing them to the console, BUT the Python Dictionary is unordered. So, no wonder the printed results were in a different order than the database results.
Solution
Use a Python Ordered Dictionary if you want to store the query results in a fixed order:
import collections
treeDictionary = collections.OrderedDict()


text:
Q: Viisual Studio 2015 not finding variables in scope after update 2 I have a .NET core project and an Xunit project in a solution, where I've all of a sudden gotten huge problems with debugging. This seems to have coincided with installing update 2 yesterday.
When debugging and hitting a breakpoint, only a select few parameters show up in locals, autos, watch or are reachable from immediate window. I think, but haven't verified 100%, that the variables I can access are globals and ones passed as parameters to the function.
For instance, look at part of this test:
 public void UniTest4()
        {
            var s = @"{
                ""id"": ""0001"",

                ""type"": ""donut"",
                ""name"": ""Cake"",
                ""ppu"": 0.55,
                ""batters"":
                    {
                            ""batter"":
                            [
                                { ""id"": ""1001"", ""type"": ""Regular"" },
                                { ""id"": ""1002"", ""type"": ""Chocolate"" },
                                { ""id"": ""1003"", ""type"": ""Blueberry"" },
                                { ""id"": ""1004"", ""type"": ""Devil's Food"" }
                            ]
                    },
                ""topping"":
                    [
                        { ""id"": ""5001"", ""type"": ""None"" },
                        { ""id"": ""5002"", ""type"": ""Glazed"" },
                        { ""id"": ""5005"", ""type"": ""Sugar"" },
                        { ""id"": ""5007"", ""type"": ""Powdered Sugar"" },
                        { ""id"": ""5006"", ""type"": ""Chocolate with Sprinkles"" },
                        { ""id"": ""5003"", ""type"": ""Chocolate"" },
                        { ""id"": ""5004"", ""type"": ""Maple"" }
                    ]
            }";

            var token = yayson.MakeToken(s);

When I break on the last line, I can't to reach the variable "s". I have looked for others with similar problems, and have then seen suggestions that this may be due to building with certain compiler optimizations. But is that really the case for me? Shown below are the build settings for my Xunit project. My business project looks the same, excep for the top checkbox being checked (which it also was, working just fine, prior to the VS update).

What can I do to find local variables again?

A: I finally found a solution from Andrew Arnott via this SO question: Visual Studio 2015 Debugging: Can't expand local variables?
Just ticking the "Use Managed Compatibility Mode" box solved my problem. Although I'd love to know why that helped.


text:
Q: Creating Model instance with a randomly generated, human sized, unique id I need a Model that has a field with a Random, Human-Sized, Unique key. We intend to use this for a human to brain-net the id to another computer and recall the data.
What I have:
def make_code():
    numbers = "".join(random.choice(string.digits) for x in range(4))
    letters = "".join(random.choice(string.ascii_lowercase) for x in range(2))
    return numbers + letters

class PinRecord(models.Model):
    pin = models.CharField(max_length=16, primary_key=True)
    data = models.TextField(blank=False, null=False)
    created = models.DateTimeField(auto_now_add=True)

    @classmethod
    def create_uniq(cls, action, data):
        created = False
        while not created:
            pin, created = cls.objects.get_or_create(pin=make_code(), defaults={'data':data})
        return pin.pin

Is there a better way to do create_uniq?
Right now, there is a small chance that it loops for a long time, especially if the PinRecords don't get cleaned up properly or traffic is higher then expected. An alternate version that limits attempts to a finite number leaves us with nothing to give the user except a middle finger error.
The recommended solution to the Random, Unique key problem seems to be uuid, but the users will object to writing down and retyping a uuid.


text:
Q: Gap on bottom of the page on mobile browsers when using height 100vh/100% I have a page with a few divs (class="full") that I want to be as high as the viewport of the user is. It works on Desktop (Ubuntu, Firefox) but not on mobile (Android, Chrome). My smartphone shows a small white gap at the bottom.
div.full {
    min-height: 100vh !important;
}

html,body {
    min-height: 100vh !important;
    height:100vh;
    margin:0px;
    padding:0px;
}

body {
    position: relative;
    background: url(../img/background.jpg) no-repeat center center fixed;
    -webkit-background-size: cover;
    -moz-background-size: cover;
    -o-background-size: cover;
    background-size: cover;
}

When I scroll on the page, this gap increases. It seems like it is the height of my android status bar + the address bar of chrome when I scrolled down and just the height of the status bar when I did not scroll.
I also tried 100% instead of 100vh, it didn't help.
If I remove
height:100vh;

from the html, body block the gap disappears, but then I have a new problem: The background image is scaled up a lot and gets blurred...
How can I make a div exactly 100% high on all devices (even when scrolling)?

A: I think I got it working now. The code in the question was correct, but I also had this code in my CSS:
.ref-logo {
    width: 400px;
}

This seems to have caused my page to be rescaled. I noticed this because the navbar-button was only shown when I scrolled to the right...
This works now:
.ref-logo {
    max-width: 400px;
    width: 90%;
}

I know why I am no web developer :P


text:
Q: Preventing fb.ui() from scrolling the browser I'm working on a Facebook canvas page application using an iframe.  I'm using fb.ui() to create a dialog box for sharing however when the dialog opens, it's centered at first, then once the async call loads the dialog, it moves the dialog box to the top of the iframe and scrolls the browser to the top.
I considered using jQuery to reposition the box however I'd also have to scroll the browser position which screams hack to me.  Any suggestions would be greatly appreciated.

A: Had the same problem, positioning in iFrames sucks.  The easiest way to keep the dialog positioned correctly is to use the popup display option which pops a new browser window above the center of the current page.  It's not as pretty, but it works nicely.
//generic sharing function
var fbshare = function(url, display) {
    var share = {
        method: 'stream.share',
        u: url,
        display: display
    };
    FB.ui(share);
};

//share using popup
Share

A: I'm using jquery to get the scroll position, and then setting it in the response function.
scroll = $(window).scrollTop();
FB.ui(
{
//setup
},
function(response)
{
//handle response
$(window).scrollTop(scroll);
});

A: For anyone else who is coming across this issue, just to reiterate Jonathan Tran's comment above about this reported bug, it has been fixed by Facebook, but only for the SHARE dialog. If you are still hitting this issue, you are probably calling the FEED dialog from your Javascript instead, which Facebook hasn't bothered to fix yet. Use this:
FB.ui({
        method: 'share',
        ...

NOT this:
FB.ui({
        method: 'feed',
        ...

A: Improving the Nate idea...
    window['__sy'] = $(window).scrollTop();
    FB.ui(
    {
    //setup
    },
    function(response)
    {
    //handle response
    });
    $(window).one('scroll',function (){$(window).scrollTop(window['__sy'])});


text:
Q: How to find out whether the application is running or not using blue prism tool? Is it possible to find out whether the application is running/hanged/not yet started using blue prism tool.

A: Use the "Process Exists" Action in the "Utility - General" Object to find if it's running. You'll have to catch the exception and probably kill it if it's hanged.

A: In utility general there is an option to check process(Process exist) and the existing process can be killed using utility environment(Kill Process).


text:
Q: Struggling to make my buttons work I am busy learning Python and I want to make a simple program that connects to a database to locate the information of Doctors. Now the as far as I can see everything works fine, database connects, info gets displayed, but the buttons don't want to work. Please see code and error below.
Any help will be greatly appreciated.
Error:
Traceback (most recent call last):
  File "C:\Users\Bl@h\Desktop\New INF\CallDoctorLocator.py", line 57, in <module>
    myapp = MyForm()
  File "C:\Users\Bl@h\Desktop\New INF\CallDoctorLocator.py", line 29, in __init__
    QtCore.QObject.connect(self.ui.ButtonUpdate, QtCore.SIGNAL('clicked()' ), self.UpdateRecords)
AttributeError: 'MyForm' object has no attribute 'UpdateRecords'
>>>

Code:
#CallDoctorLocator import sys from DoctorLocator import * from PyQt4 import QtSql, QtGui

#Create Connection to the Database def createConnection():
    db = QtSql.QSqlDatabase.addDatabase('QMYSQL')
    db.setHostName('localhost')
    db.setDatabaseName('healthcare')
    db.setUserName('root')
    db.setPassword('3364834')
    db.open()
    print (db.lastError().text())
    return True

class MyForm(QtGui.QDialog):
    def __init__(self, parent=None):
        QtGui.QWidget.__init__(self, parent)
        QtGui.QWidget.__init__(self, parent)
        self.ui = Ui_Dialog()
        self.ui.setupUi(self)
        self.model = QtSql.QSqlTableModel(self)
        self.model.setTable("doctors")
        self.model.setEditStrategy(QtSql.QSqlTableModel.OnManualSubmit)
        self.model.select()
        self.ui.tableView.setModel(self.model)
        QtCore.QObject.connect(self.ui.ButtonUpdate, QtCore.SIGNAL('clicked()'
        ), self.UpdateRecords)
        QtCore.QObject.connect(self.ui.buttonCancel, QtCore.SIGNAL('clicked()'
        ), self.CancelChanges)
        QtCore.QObject.connect(self.ui.buttonAdd, QtCore.SIGNAL('clicked()' ),
        self.AddRecord)
        QtCore.QObject.connect(self.ui.buttonDelete, QtCore.SIGNAL('clicked()'
        ), self.DeleteRecord)
        QtCore.QObject.connect(self.ui.buttonSearch, QtCore.SIGNAL('clicked()'
        ), self.SearchRecords)

def UpdateRecords(self):
    self.model.AddRecord()

def CancelChanges(self):
    self.model.revertAll()

def UpdateRecords (self):
    self.model.insertRow(self.ui.tableView.currentIndex().row())

def DeleteRecords(self):
    self.model.removeRow(self.ui.tableView.currentIndex().row())
    self.model.AddRecord()

def SearchRecords(self):
    self.model.setFilter("Name like '" + self.ui.Name.text()+"%'")

if __name__ == "__main__":
    app = QtGui.QApplication(sys.argv)
    if not createConnection():
        sys.exit(1)
    myapp = MyForm()
    myapp.show()
    sys.exit(app.exec_())


text:
Q: PDO query does not return data when inserting date as variable Im trying to get a hold of OOP and PDO. Did some tutorials. In the tutorial i got the query method (so thats not mine...)
but im having troubles with a pdo query
I want to select orders from the database matching a date..... de date comes from a datepicker and returns 2012-12-16 for example therefor
$dateInputQuery = date("Y-m-d", strtotime(Input::get('datepick')));
$data = $order->getAllOrders('order', 'WHERE DATE(orderdate) = DATE({$dateInputQuery})', false, false);

the strange thing is that when i replace the WHERE clause to WHERE DATE(orderdate) = \'2013-12-16\' it returns all the data but when inserting my date like above it does not....
in the db class the method looks like this
public function getAll($table, $where = NULL, $orderSort = NULL, $limit = NULL) {
    $this->query("SELECT * FROM {$table} {$where} {$orderSort} {$limit}")->error();
    return $this;
}

and query method in db class
public function query($sql, $params = array()) {
    //reset error
    $this->_error = false;
    if ($this->_query = $this->_pdo->prepare($sql)) {

        $x = 1;
        if (count($params)) {
            foreach ($params as $param) {
                $this->_query->bindValue($x,$param);
                $x++;
            }
        }

        if ($this->_query->execute()) {
            $this->_results = $this->_query->fetchAll(PDO::FETCH_OBJ);
            $this->_count = $this->_query->rowCount();
        } else {
            $this->_error = true;
        }
    }

    return $this;
}

why is this ?

A: *

*Your immediate problem is caused the fact that $dateInputQuery is unquoted. Date is a string literal and should be quoted. And even though you can easily add quotes around it you really shouldn't do this. See next point.

*order is a reserved word in MySQL, therefore the table name should be put in backticks
$data = $order->getAllOrders('`order`', "WHERE DATE(orderdate) = DATE('$dateInputQuery')", false, false);
                              ^     ^                                 ^               ^

*You're not leveraging parameter binding in query() function. Instead on top of it you're using query string interpolation leaving your code vulnerable to sql injections and diminishing the usage of prepared statements. When you use parameter binding you no longer need to quote parameter values.

*Your sql query is not index-friendly. You shouldn't apply any functions (in your case DATE()) to the column you're searching on (orderdate). Instead you can rewrite your condition to apply necessary transformations/calculations to the arguments which are constants.

*You should avoid using SELECT *. Read Which is faster/best? SELECT * or SELECT column1, colum2, column3, etc and Why is using '*' to build a view bad?
That being said your query should look something like
$sql = "SELECT order_id, orderdate, ...
          FROM `order`
         WHERE orderdate >= ?
           AND orderdate <  ? + INTERVAL 1 DAY";

And you should execute it
$this->query($sql, array($dateInputQuery, $dateInputQuery));

Instead of passing whole clauses (e.g. WHERE) you should pass values


text:
Q: IDL: Using a 64bit .save file with a 32 bit virtual machine If I compile a .save file in a 64 bit IDL version, will it work with the 32 bit IDL virtual machine?

A: Yes, 32-bit or 64-bit should not matter. The only problem is the IDL version. From the help:

Note: Files containing IDL routines and system variables can only be restored by versions of IDL that share the same internal code representation. Since the internal code representation changes regularly, you should always archive the IDL language source files (.pro files) for routines you are placing in IDL SAVE files so you can recompile the code when a new version of IDL is released.


text:
Q: Java RMI NoSuchObjectException I have a server and client using Java RMI. If I use one client all is fine with the code below. But if I connect with a client and then a second one, it throws port already in use exception. That's fine, so I disconnect the connected client and then try to connect with the second client again. It gives me this:
java.rmi.NoSuchObjectException: no such object in table
Why is this?
//CONNECT

Registry registry = LocateRegistry.getRegistry(
    Options.getRegistryIp(), Options.getRegistryPort());
server = (IServer) registry.lookup(Constants.MB_SERVER_NAME);

UnicastRemoteObject.exportObject(client, Options.getMyPort());
server.registerClient(client);

//DISCONNECT

server.removeClient(client, client.getUser());
UnicastRemoteObject.unexportObject(client, false);

A: NoSuchObjectException means that the stub refers to a remote object which has been unexported, either explicitly or via GC. Are you getting this on the lookup(), or the registerClient(), or the removeClient()?


text:
Q: SQLAlchemy: How to properly escape text for .update() In using JSONB columns in a postgres + SQLAlchemy setup we often use the .update() method.
An example is:
path = '{user,lastText}'
text = 'Hello. Please activate folder \nD:\\foo\bar\some\more \t Thanks, yours "Ted"'

db.session.query(
  Customer
).filter(
  Customer.custid == '10'
).update(
  {Customer.context: func.jsonb_set(Customer.context, path, text)},
  synchronize_session='fetch'
)

You see that the text has plenty of problematic chars and needs to be escaped.
What's the recommended way to do that?
SQLAlchemy should have such a module?

A: Ilja's answer is spot on:
json.dumps()

Its a very good way to go.


text:
Q: Login for PHP site sometimes works I'm having a problem with my login system. Sometimes it works, sometimes it doesn't. It seems that it fails on the first try more often than not and works on the second go around. There is NO ERROR; the page redirects to the home page as it is supposed to but the session variables are coming up empty.
The first code block is the relevant login script after a username/pass was accepted. The second block is what i use to see if the user has any cookies if the the session vars arn't set the home page. The third clock is my logout script.
Thanks in advance.
// The log-in is OK so set the user ID and username session vars (and cookies), and redirect to the home page
$row = mysqli_fetch_array($data);
$_SESSION['user_id'] = $row['user_id'];
$_SESSION['username'] = $row['username'];
$_SESSION['first_name'] = $row['first_name'];

if($rememberme == 1)
{
    setcookie('user_id', $row['user_id'], time() + (60 * 60 * 24 * 30));    // expires in 30 days
    setcookie('username', $row['username'], time() + (60 * 60 * 24 * 30));  // expires in 30 days
    setcookie('first_name', $row['first_name'], time() + (60 * 60 * 24 * 30));  // expires in 30 days
}

if($ref==0)
{
    header("location: http://domain.com/test.php");

}
else
{
    header("location: http://domain.com/".$ref);

}

second block:
session_start();

if (!isset($_SESSION['user_id'])) {

    if (isset($_COOKIE['user_id']) && isset($_COOKIE['username']) && isset($_COOKIE['first_name'])) {
        $_SESSION['user_id'] = $_COOKIE['user_id'];
        $_SESSION['username'] = $_COOKIE['username'];
        $_SESSION['first_name'] = $_COOKIE['first_name'];
    }
}

third block:
// If the user is logged in, delete the session vars to log them out
session_start();
if (isset($_SESSION['user_id']))
{
    // Delete the session vars by clearing the $_SESSION array
    $_SESSION = array();

    // Delete the session cookie by setting its expiration to an hour ago (3600)
    if (isset($_COOKIE[session_name()]))
    {
      setcookie(session_name(), '', time() - 3600);
    }

    // Destroy the session
    session_destroy();
}

// Delete the user ID and username cookies by setting their expirations to an hour ago (3600)
setcookie('user_id', '', time() - 3600);
setcookie('username', '', time() - 3600);

// Redirect to the home page
header('Location: http://domain.com/test.php');

A: Try destroying your session variables in your log out script, also at the beginning of your log in script.


text:
Q: Correct Description of "class" public class Program
{
  static void Main(string[] args)
  {
    Test test = new Test();
    Console.WriteLine(test.GetType()); // -> it´s Test, of course
    int a = 5;
    Console.ReadLine();
  }
}

public class Test
{
  public string Name;
}

In the above case
the Type of "test" is Test, right?
And in this case the Type of "a" is int, named primitive data type,
public is an access modifier
So my Question now is, what is class then? A keyword? A primitive Datatype? Neither, Nor?
Please, don't explain my, what a class is doing or what's the difference between class or object, I know a class is like a construction plan.

A: Class is a keyword that signifies to the C# compiler that a class is being declared. See https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/


text:
Q: Selenium opening multiple tabs not working I've tried this code snippet to automate opening the same url 'google.com' in multiple tabs in Firefox. But it still gets opened in new Windows only. Since I just want to open that url only, I don't want to get the handle to switch back and forth.
Can you please help me find what's wrong with my code:
public class MultipleTabsWebinar {
public static void main(String[] args) throws InterruptedException{
    List drivers = new ArrayList();
    for(int i = 0; i < 5; i++){
        WebDriver driver;
        System.setProperty("webdriver.gecko.driver", "C:\\geckodriver-v0.11.1-win64\\geckodriver.exe");
        System.out.println("Hello World Test on AMS148");
        driver = new FirefoxDriver();
        driver.get("http://10.3.3.148");
        Thread.sleep(100);
        driver.findElement(By.cssSelector("body")).sendKeys(Keys.CONTROL +"t");
        drivers.add(driver);
    }
    for(int i = 0; i < drivers.size(); i++){
        ((WebDriver) drivers.get(i)).close();
    }
}

}

A: You can try below code:
JavascriptExecutor jse = (JavascriptExecutor)driver;
for(int i = 0; i < 15; i++)
    {
    jse.executeScript("window.open('https://google.com');");
    }

This should allow you to open Google search page in multiple new tabs
Note that (as was mentioned in comments) you don't need to initialize WebDriver instance inside a loop


text:
Q: Decode SEGD file and plot any trace from it There is a SEGD file with some seismic data. How to decode any trace ?
The python script can read and decode headers according SEGD Rev 2.1 documentation. How to decode and plot any trace. Have tried to use 1 byte quatery exponebt data recording method. But having wrong result.
The Data Body:
'10111110',
 '00101001',
 '11001111',
 '00010010',
 '10111101',
 '10100110',
 '00110010',
 '00100100',
 '10111100',
 '10010000',
 '10000100',
 '10010101',
 '00111101',
 '10101001',
 '00010110',
 '00100010',
 '00111110',
 '00001000',
 '10010001',
 '11011010',
 '00111101',
 '10101001',
 '00010110',
 '00100010',
 '00111100',
 '10011100',
 '00010100',
 '10001011',
expecting to get something like
    1.000e+00,  1.000e+00,  1.000e+00,  1.000e+00,  3.125e-02,
    1.000e+00,  1.000e+00,  1.000e+00,  1.000e+00,  1.000e+00,
    1.000e+00,  1.000e+00,  1.000e+00,  3.125e-02,  3.125e-02,
    3.125e-02,  3.125e-02,  3.125e-02,  3.125e-02,  3.125e-02,
    3.125e-02,  3.125e-02,  3.125e-02,  3.125e-02,  3.125e-02,
    3.125e-02,  3.125e-02,  3.125e-02,  3.125e-02,  3.125e-02,
    3.125e-02,  3.125e-02, -1.000e+00, -1.000e+00, -1.000e+00,
   -1.000e+00, -1.000e+00, -1.000e+00, -1.000e+00, -1.000e+00,
    3.125e-02,  3.125e-02,  3.125e-02,  3.125e-02,  7.000e+00,
    2.600e+01,  4.100e+01,  6.100e+01,  7.500e+01,  7.400e+01,
    5.900e+01,  3.600e+01,  1.500e+01,  1.000e+00, -7.000e+00,
   -1.200e+01, -1.300e+01, -1.400e+01, -1.200e+01, -1.000e+01,

A: Use a struct. Create a format, and use it to read the file at the start of the trace, viz.
    tracedataformat = '!' + str('f' * ns)
    f.seek(pos)
    tr = np.zeros(ns, np.float)
    tr = np.array(struct.unpack(format, f.read(4 * ns)))

*

*Read 32-bit floats in IEEE format

*ns - the number of samples to read (get it from the channels descriptor)

*pos - the position in bytes relative to the start of the file of the start of the trace.


text:
Q: What is a recommended scalable DB platform to use in AWS for large amounts of volatile data sets - elasticsearch, Redis or DynamoDB? Users of our platform will have large amounts of stored data on our system.  Through an application, once connected, that data will be transferred to them and no longer need to remain on our servers.  There could potentially be hundreds or thousands of users connected at any given time, performing their downloads.
Here's the proposed architecture:
User management, configuration, and data download statistics will be maintained in a SQL Server database, while using either Redis or DynamoDB for the large data sets.
The reason for choosing either Redis or DynamoDB is based on cost - cheaper than running another SQL Server instance, and performance.  The data format will be similar to a datamart - flat table with no joins.
Initially the queries would be simple - get all data for user X between a date range, and optionally delete.
Since we may want to add free text searching for certain fields of that data using elasticsearch may be a better option to use from the get-go.
I want this to be auto-scaling but not sure which database would be best to use for this scenario.

A: Here's some great discussion on Database + Search tier from AWS ReInvent:
https://youtu.be/K7o5OlRLtvU?t=1574

A: I would not take Elastic-search alone because it does not provide auto-scaling for writing capacity. In fact, it's not trivial to augment the number of shard of an index. Secondly it can only handle the JSON format, which could be an issue for you.
Redis could be a good idea because it is really fast, everything is done in RAM, and it provides keys with a limited time-to-live which could be interesting for you. Unfortunately, if your data size exceeds the capacity in RAM of your amazon instance you will have to shard your Redis database. And Redis does not support it, you will have to deal it on your application code. Moreover, as far as I know Redis does not handle complex queries. You will also need to save your data in a Redis data structure which could be an issue for you
DynamoDB handles auto-scaling really well but on the other hand it is a key/value database so it does not allow you to make queries like "get all data for user X between a date range". DynamoDB also allows you to save your data in any format.
The solution will be to use either DynamoDB or either Redis depending of the size of your datas, and to use ElasticSearch in order to index your key with only the meta-data (user and dates). Like that your index will be small, and if you lost the ability to index because of ElasticSearch get too buzy, you keep the ability to save user's datas.


text:
Q: Telerik Grid MVC: Get the object passed to ClientEvent functions in javascript side I have a little tricky question. I have a Telerik Grid with some ClientSide Events:
.ClientEvents(events => events
    .OnDataBinding("SetAjaxParameter")
)

In the function SetAjaxParameter I set the paramters for the ajaxBinding:
function SetAjaxParameter(event) {
    event.data = {
        name: $('#paramterID').val(),
        value: $('#valueID').val()
    };
};

So in my controller I have access to the passed parameters 'name' and 'value'.
But I want to define the call to SetAjaxParameter() in javascript and not in the Setup of the TelerikGrid. Is that somehow possible? So i have to get this event-Objekt which is passed by the Grid to my function. But i can't figure out what type of objekt it is neather how to get it.
You may ask why: i want to seperate cshtml and javascript files and my javascript gets loaded after the html has been loaded, so the function for the databinding-Event is not available yet

A: In the end, it's pretty simple to to that. I just had to write following code snippet:
    $('#GridName).bind('dataBinding', function (event) {
        SetAjaxParameter(event);
    });

And on the next AjaxCall by the grid, the desired parameter get passed to my controller.


text:
Q: Member field gets ignored when parsing using gson I am parsing a POJO into json using Google's gson library. These are the objects involved:
// Order.java
public class Order {
    // ...
    private int id;
    private String name;
    private Location location;
    // ...
}
// Location.java
public class Location {
    // ...
    private String address;
    private float latitude;
    private float longitude;
    private String postcode
    // ...
}

When I run it though gson (making sure the Location member variable is not null) using new Gson().toJson(order) I get this results:
{
    "id" : 1,
    "name" : "nameValue"
}

but I was expecting to get something like this:
{
    "id" : 1,
    "name" : "nameValue",
    "location" : {
            "address" : "some address",
            "latitude" : 53.346346,
            "longitude" : -3.346363,
            "postcode" : "23563"
        }
}

Can't figure out why is this happening. Has anybody come across this? What can it be that I may be doing wrong?
I have tried setting a custom Type adapter with no luck.
Thanks for your help.

A: Ok, I figured out what the issue was. I had a mock object factory that created the mock objects using anonymous constructor in the Location type, like this:
Location location = new Location() {
    {
         setAddress("some address");
         setLatitude(53.346346);
         setLongitude(-3.356363);
         setPostCode("23563");
    }
};

So Gson interpreted it as an anonymous class and as it is said in the documentation:

Fields corresponding to the outer classes in  inner classes, anonymous classes, and local classes are ignored and not included in serialization or deserialization

I changed it into the normal way of setting up the GsonBuilder and iworks as expected. However I wonder if it would be possible to use this kind of initiation, since it does work for Collections (ArrayList). It makes my mock factories easier to read. :)


text:
Q: How to upgrading to new release automatically or download the release iso once it's released? All of you know that within few hours, Ubuntu 14.04 is going to be released.
What can I do to upgrade my system automatically when Ubuntu 14.04 is arrived?
And also What can I do to download a single Ubuntu 14.04 desktop-64-bit iso file or all the trusty images automatically when it was arrived(available for download)?

A: I extremely recommend against. Upgrading from a version to the next can take several hours, block your system, wait for your intervention, be interrupted by power loss, leave your system unbootable, etc.
When upgrading you should make sure that you have the time and a backup plan in case something go wrong. The upgrades to the next version are not automatic for this reason, there is several things that can go wrong.

A: Better version, with python3. Slightly more efficient and checks every 2 minutes. Just have it run in a screen process
dload.py
import subprocess
import time
import http.client
def exists(site, path):
    conn = http.client.HTTPConnection(site)
    conn.request('HEAD', path)
    response = conn.getresponse()
    conn.close()
    return response.status == 200

while 5>0:
    if(exists("releases.ubuntu.com:80","/14.04/ubuntu-14.04-desktop-i386.iso")):
         print("Downloading")
         subprocess.call(['wget', 'http://releases.ubuntu.com/14.04/ubuntu-14.04-desktop-amd64.iso'])
         break
    time.sleep(2*60)

Running it:

*

*Copy the above into a file called dload.py

*Open a terminal and type screen

*type in python3 ./dload.py

A: Hm, hard one. I guess you could make a script that tries to do a wget to the location where the ISO will probably arrive once it's released:
wget http://releases.ubuntu.com/releases/14.04/ubuntu-14.04-desktop-amd64.iso
You might need to change the ISO name to the architecture of your system (amd64 or i386)
Just script it and put it on a cron job every 15 minutes or so. :P


text:
Q: Keeping count in recursive function C++ I have a function that's traversing an AVL tree in level-order. The output format is:
level 0: jim(2)
level 1: bob(1) joe(1)

But when I get to level 4 and up, I want to break it down so it will only show 8 items per line. So the out put would start to look like this:
level 4: item1(1) item2(1) item3(2) item4(2) item5(1) item6(2) item7(1) item8(2)
level 4: item9(2) item10(2)

Right now my code will display all the items, but only on one line. I'm having trouble figuring out how to improve this code so that it is formatted the way I want. How can I implement this?
Here are the current functions:
//PRINT BY LEVEL ORDER TRAVERSAL
void Avltree::level_order(Avlnode* root, ofstream &out){
int h = height(root);
for(int i = 0; i < h; i++){
    out << "Level " << i << ": ";
    print_level(root, i, out);
    out << endl;
}
}

//PRINT A GIVEN LEVEL ON A TREE
void Avltree::print_level(Avlnode* root, int level, ofstream &out){

    if(root == NULL)
        return;
    if(level == 0){
        out << root->data << "(" << height(root) << ") ";
    }
    else if (level > 0)
    {
        print_level(root->left, level-1, out);
        print_level(root->right, level-1, out);
    }
}

A: You should pass a count as a parameter to the recursive function and when count % 8 (or whatever you want the number per line to be) is 0, then start a new line.

A: Add a call by reference parameter for total number of nodes printed
void Avltree::print_level(Avlnode* root, int level, ofstream &out, int &count)
{
    ...
    if(level == 0){
        out << root->data << "(" << height(root) << ") ";
        count++;
    }
    if(count==8){
        out << endl;
        count=0;
    }
    ...
}

While the calling would be
int count=0;
for(int i = 0; i < h; i++){
    count=0;
    out << "Level " << i << ": ";
    print_level(root, i, out, count);
    out << endl;
}


text:
Q: Como enviar múltiplos dados diferentes por email? Boa noite,
E o seguinte eu tenho um sistema com 3 input e tenho um jquery que me adiciona mais 3 iguais caso queria enviar mais dados eu estou a conseguir enviar por email os dados das primeiras três mas quando adiciono mais 3 já não me envia o valor das 3 que ele adicionou.
Formulário

<input placeholder="País" type="text"  name="input_anuncia[]">

<input placeholder="Nome do Estabelecimento" type="text" name="input_anuncia[]">

<input placeholder="Localização" type="text" name="input_anuncia[]">

Código onde trato o valor do post
foreach ($_REQUEST['input_anuncia'] as $dados_local ) {

  $mostra_dados_local = '

Dados do Estabelecimento

País:

'.$_REQUEST['input_anuncia'][0].'

Nome do Estabelecimento:

'.$_REQUEST['input_anuncia'][1].'

Localização

'.$_REQUEST['input_anuncia'][2].'

  ';
}

A: Primeiro, convém mudar um pouco o formulário para facilitar as coisas:

<input placeholder="País" type="text"  name="input_pais[]">

<input placeholder="Nome do Estabelecimento" type="text" name="input_nome[]">

<input placeholder="Localização" type="text" name="input_local[]">

Notar que mudei o nome dos inputs, para saber o que é o que (dava para manter igual, mas teria que multiplicar tudo por 3 para usar os campos certos)
Aí, na parte que processa os dados você ajusta o loop nesta parte:
$qtd = count( $_REQUEST['input_pais'] );
for ( $i = 0; $i < $qtd ; $i++ ) {

e aqui muda as variáveis e põe os índices:

'.$_REQUEST['input_pais'][$i].'

Nome do Estabelecimento:

'.$_REQUEST['input_nome'][$i].'

Localização

'.$_REQUEST['input_local'][$i].'

Assim, o código será repetido para a quantidade certa de dados do form.
IMPORTANTE: Não quis deixar muito confusa a resposta, mas você pode simplificar muito esse seu HTML, e repetir apenas a parte dos TR, em vez da div inteira. Procure entender e fazer funcionar até esta parte, mas depois tente otimizar o código.


text:
Q: SQL Server lots of overhead from network communication? We have a 'server' that is configured with SQL Server 2008 R2 on machine A. In the same LAN we have machine B which is a machine with identical hardware without the SQL Server installation.
We have a set of unit tests that request some records from the database and maps them to the proper CLR objects. When this unit test is run from Machine A, with SQL Server, the tests run in 5ms.
If I copy the code of the test to machine b and run it the tests take a total of ~50ms which is a significant increase if this is only caused by network overhead.
The queries executed do not send a lot of data (there are no blobs/xml data in the columns), the total data is around a few KB. The data is read using an IDataReader. We use a single connection which is opened once and is used to fire about 24 queries to the database.
Are there any tips/tricks that I can try in order to test if it's really the network overhead slowing the execution? I have a feeling something is just not configured properly in SQL Server.

A: This sounds like normal behaviour, its just network latency... To confirm if these figures sound reasonable, ping one server from the other, I would not be surprised if this reported a roundtrip well into double digit milliseconds whereas a ping of your local machine should come in a 1ms...  I agree with Pondlife, sounds like par for the course for a healthy LAN.


text:
Q: awk processing with a variable input file is:
line1 [time-1] abcdef
line2 [time-1] absde1
line3 [time-1] abcdef
line4 [time-1] zzzzzz

this command is working fine:
$ str="abcdef|zzzzzz"
$ awk '!($0~/('"$str"')$/)' test_input
line2 [time-1] absde1

following command fails:
$ str="[time-1] abcdef|[time-1] zzzzzz"
$ echo "${str}"
[time-1] abcdef|[time-1] zzzzzz
$ awk '!($0~/('"$str"')$/)' test_input
awk: fatal: Invalid range end: /([time-1] abcdef|[time-1] zzzzzz)$/
$

Is it possible to pass variable with such string to awk too?

A: One more awk:
awk -v str="$str" 'BEGIN {
   n = split(str, a, "|")
}
{
   for (i=1; i<=n; i++)
      if (index($0, a[i]))
         next
   print
}' file

line2 [time-1] absde1

Reason why you cannot just use $str as regex is that you have regex meta characters such as [, ] etc.

A: You just have to escape the square brackets
$ str="\[time-1\] abcdef|\[time-1\] zzzzzz"
$ awk '!($0~/('"$str"')$/)' test_input
line2 [time-1] absde1

--- Edit --------------------------
To create the str variable with escaped characters
str="[time-1] abcdef|[time-1] zzzzzz" | sed -e 's/[]\/$*.^[]/\\&/g'

This way, the pipe-separated list can be an automatically generated list.