text:
Q: Help with Code coverage, Loop and if conditions I'm unable to have code coverage. Wrote a test class that has 24% coverage. How should I test loops and conditional statements?

Following is my Apex Class...

public class OrderTrackingList{
public OrderTrackingList(ApexPages.StandardController controller) {}
public list<wrapgroupwise> singlegroup;
public List<wrapgroupwise> getStartHere(){
singlegroup= new List<wrapgroupwise>();
List<orders__c> tempacc=[SELECT Id,Name FROM orders__c where id=:ApexPages.currentPage().getParameters().get('id')];

 for(Integer i=0; i<tempacc.size() ; i++){
    List <order_lines__c> tempOrderLines=[SELECT Id,name From order_lines__c Where order_number__c=:tempacc[i].id];
    List <shipment_lines__c> tempShipmentLines=[SELECT Id,Name From shipment_lines__c Where Order_Number__c=:tempacc[i].id];

  if(tempOrderLines.size()==0 && tempShipmentLines.size()==0){
          singlegroup.add(new wrapgroupwise(tempacc[i],null,null));
    }
    else{

     if(tempShipmentLines.size()==0)
     {
          if(tempOrderLines[i].status__c=='Open')
           {
               tempOrderLines[i].calculated_estimated_delivery_date__c=tempOrderLines[i].planned_ship_date__c;
           }

        singlegroup.add(new wrapgroupwise(tempacc[i],tempOrderLines,null));

      }
     else
     {

       if(tempOrderLines[i].status__c=='Open')
       {
           tempOrderLines[i].calculated_estimated_delivery_date__c=tempOrderLines[i].planned_ship_date__c;
       }
       if(tempOrderLines[i].status__c=='Invoiced')
       {
           tempOrderLines[i].calculated_estimated_delivery_date__c=tempShipmentLines[i].estimated_delivery_date__c;
       }
       if(tempOrderLines[i].status__c=='Shipped but not billed')
       {
           tempOrderLines[i].calculated_estimated_delivery_date__c=tempShipmentLines[i].estimated_delivery_date__c;
       }

      singlegroup.add( new wrapgroupwise(tempacc[i],tempOrderLines,tempShipmentLines));
     }

    }
   }
  return singlegroup;
  }
 public class wrapgroupwise
 {
    public List<order_lines__c> con {get;set;}
    public orders__c acc {get;set;}
    public List<shipment_lines__c> opp {get;set;}

     public wrapgroupwise( orders__c a , list<order_lines__c> c,list<shipment_lines__c> o)
     {
        acc=a;
        con=c;
        opp=o;
      }
  }
 }

========================TEST CLASS===========================

 @isTest
 public class OrderTrackingList_Test{
static testMethod void coverCode(){

          //OrderTrackingList.wrapgroupwise wgw = new            OrderTrackingList.wrapgroupwise();
          Profile pf= [SELECT Id FROM Profile WHERE name= 'System Administrator' LIMIT 1];

          Account acc = new Account(Name='ABC Corp.');
          insert acc;
          System.assertEquals('ABC Corp.', acc.name);

          orders__c tempOrder = new orders__c();
          tempOrder.name = '0001234567';
          tempOrder.account__c = acc.id;
          insert tempOrder;
          System.assertEquals('0001234567', tempOrder.name);

          order_lines__c tempOL = new order_lines__c();
          tempOL.Name = '10';
          tempOL.number_of_order_lines__c = tempOrder.id;
          insert tempOL;
          System.assertEquals('10', tempOL.name);

          shipment_lines__c tempSL = new shipment_lines__c();
          tempSL.Name = '10';
          tempSL.CurrencyIsoCode = 'USD';
          insert tempSL;

          System.assertEquals('USD', tempSL.CurrencyIsoCode);

         OrderTrackingList gepwO = new OrderTrackingList(new ApexPages.StandardController(tempOrder));
         OrderTrackingList gepwOL = new OrderTrackingList(new ApexPages.StandardController(tempOL));
         OrderTrackingList gepwSL = new OrderTrackingList(new ApexPages.StandardController(tempSL));
         gepwO.getStartHere();
         //gepwOL.singlegroup.add(gepwOL);
        // gepwSL.singlegroup.add(gepwSL);
        // gepwO.singlegroup.add(gepwO);
        }
   }

What am I missing? Please guide.
Thanks.

A:
How should I test loops and conditional statements?

Your test methods need to create the data which meets your conditions.

What am I missing?

This line of code will require your unit test to set the current page reference and provide an ID value in the parameters collection. Without it, there is no "current page", no id available and thus no parameter for the query.
List<orders__c> tempacc=[SELECT Id,Name
 FROM orders__c where id=:ApexPages.currentPage().getParameters().get('id')];

Similar to this: (SFDC Docs on testing controllers and extensions)
PageReference pageRef = Page.YourPageName;
pageRef.getParameters().put('id', theIdOfYourOrder);
Test.setCurrentPage(pageRef);

Your unit test might contain this near the end after you've inserted all of your data:
Test.startTest();

PageReference pageRef = Page.YourPageName;
pageRef.getParameters().put('id', tempOrder.Id);
Test.setCurrentPage(pageRef);

OrderTrackingList gepwO = new OrderTrackingList(new ApexPages.StandardController(tempOrder));
gepwO.getStartHere();

/* your asserts for business requirements */

Test.stopTest();

These two lines are invalid given the code you've provided:
// OrderTrackingList gepwOL = new OrderTrackingList(new ApexPages.StandardController(tempOL));
// OrderTrackingList gepwSL = new OrderTrackingList(new ApexPages.StandardController(tempSL));

As an aside, the assert statements in the test class which you've posted are of very little value. (Unless you're concerned with ensuring that the Name field didn't get manipulated by another process outside of the test, which is probably not the case.)
It's great that there are assert statements in the code, but they should assert the business requirements that the custom code was written to address. This ensures that the custom code is doing what it is supposed to be doing.
gew_orders__c tempOrder = new gew_orders__c();
tempOrder.name = '0001234567';
tempOrder.gew_account__c = acc.id;
insert tempOrder;
System.assertEquals('0001234567', tempOrder.name);

A: There are multiple things I need to mention here. The first is your use of queries inside a loop. This will potentially cause governor limit overruns. Try this change:
List<orders__c> tempacc=[SELECT Id,Name,
    (SELECT Id,name From order_lines__r),
    (SELECT Id,Name From shipment_lines__r)
    FROM orders__c
    where id=:ApexPages.currentPage().getParameters().get('id')];

for(Integer i=0; i<tempacc.size() ; i++){
    List <order_lines__c> tempOrderLines = tempacc[i].order_lines__r;
    List <shipment_lines__c> tempShipmentLines = tempacc[i].shipment_lines__r;
}

Regarding testing:

*

*Developer Console can show you which lines you are missing in your logic. Look at each missed line and determine what data would have to exist in order to hit that line, and then include a record like that in your test data. If you have specific lines you can't figure out, post that information here.

*You are not asserting anything about the results of your method. You should capture that returned list and check it through system.assert()s to make sure the method ran properly.
list testlist = gepwO.getStartHere();
system.assertEquals(expectedListSize, testlist.size());


text:
Q: Variable is not being echoed When I run the following script in Bash 3.2.48:
#!/bin/bash

export var1='var1'
echo "UID=$UID"

if [ x"$UID" != x"0" ]
then
    export var2='var2'
    while ! { sudo -v; }; do { sudo -v; }; done;
    sudo $0
    exit
fi

echo $var1
echo $var2

exit 0

What I get as output is:
UID=1000
UID=0
var1

Why is var2 not exported and echoed? I'm pretty sure that the same script worked with older Bash versions.

A: *

*you enter first time with UID == 1000, you enter the if clause

*you sudo to execute the script with UID == 0;
sudo doesn't preserve the environment if env_reset is set in /etc/sudoers (default in most distros). You need sudo -E to preserve env.

*you exit (before echoing)

from the sudo call you enter with clean env.

*

*you enter with UID == 0

*you don't enter the if clause, var2 is not set

*you echo the variables.

A: The answer is much more simpler than is seems: you never echo those vars (when not running as root, obviously), because you already exit :))
Try avoiding/minimizing confusion by adding more appropriate/concise debug statements. For instance, use a single echo that contains everything that's relevant to your problem (i.e. process ID, user ID, var1, var2):
#!/bin/bash
export var1='var1'
if [ "$UID" != "0" ] ; then
    export var2='var2'
    while ! { sudo -v; }; do { sudo -v; }; done;
    sudo $0
    # this is "the key exit" ;-)
    #exit
fi
echo "pid=[$$] uid=[$UID] var1=[$var1] var2=[$var2]"

With the exit commented out you get what you expect (obviously, in the "parent" process, as the "child" one - the one running as "root" - never reaches that part of the code that exports var2):
pid=[12346] uid=[0] var1=[var1] var2=[]
pid=[12345] uid=[1] var1=[var1] var2=[var2]

++ sometimes running scripts in debug mode (bash -x) helps too ;-)

redpajama_set_name: RedPajamaStackExchange


text:
Q: query times within time range with exclusion/specific case Assume I have Item model which have a start and end timefield.
class Item(models.Model):
    start = models.TimeField()
    end = models.TimeField()

I need to get all Items which are in a specific range (between some start and end),
BUT,
assume I have two Items in my database:
Item 1 that start 5pm and end 8pm
and
Item 2 that start 8pm and end 11pm
I want to query to get all Items that are between and on (inclusive) 5pm to 8pm,
so it should only return the Item 1, and even though Item 2 starts at 8pm, I do not want Item 2, because the end on Item 2 is different than the start of Item 1.

A: In your query check explicitly for gte and lte.
qs = Item.objects.filter(start__gte=<given_start>, end__lte=<given_end>)


text:
Q: How come in Chrome or Firefox's debugger, no :focus or :hover style is shown and not even in the computed value of CSS? Let's say if we go to Bootstrap's pagination section and moved that sample into our sample page, with no JavaScript whatsoever.
I think the "hover" and get grey background effect, as well as the "click" and grey background effect, is done by something like this, which I add to my page as well:
    .pagination li a:focus { background: #fa6 !important }
    .pagination li a:hover { background: #fa6 !important }

However, I don't know why when I inspect that <a> element on Google Chrome or Firefox's debugger, I do not see the CSS rule come into view, and also, I do not see the "computed value" of CSS showing a different value -- all it shows is #ffffff for white.
I thought I did see the :hover or :focus being listed in the CSS rules before (and the computed value will change as well in the past).  What is happening and can we see that as before?

A: Bootstrap specifically target a to design it. You have to override the bootstrap by this way-
.pagination>li>a:focus,
.pagination>li>a:hover,
.pagination>li>span:focus,
.pagination>li>span:hover
{
    background: #fa6
}


text:
Q: Error while extracting public key from PKCS11 and Asn1crypto signed certificate In addition to this thread: Where is the trust chain? [python] asn1crypto and pkcs11 Aladdin USB eToken
I tried:
openssl x509 -pubkey -noout -in cert.pem
Error getting public key
140003854860736:error:0D0680A8:asn1 encoding routines:asn1_check_tlen:wrong tag:../crypto/asn1/tasn_dec.c:1129:
140003854860736:error:0D06C03A:asn1 encoding routines:asn1_d2i_ex_primitive:nested asn1 error:../crypto/asn1/tasn_dec.c:693:
140003854860736:error:0D08303A:asn1 encoding routines:asn1_template_noexp_d2i:nested asn1 error:../crypto/asn1/tasn_dec.c:626:Field=n, Type=RSA
140003854860736:error:0408B004:rsa routines:rsa_pub_decode:RSA lib:../crypto/rsa/rsa_ameth.c:51:
140003854860736:error:0B09407D:x509 certificate routines:x509_pubkey_decode:public key decode error:../crypto/x509/x_pubkey.c:124:

The contents of this file is:
-----BEGIN CERTIFICATE-----
MIIFXjCCBEigAwIBAQIEBHHhkjALBgkqhkiG9w0BAQswKjEoMCYGA1UEAwwfTW92
aW1lbnRvIEVzdHVkYW50aWwgQnJhc2lsZWlybzAiGA8yMDE5MDEwMTAwMDAwMVoY
DzIwMjAwMzMxMjM1OTU5WjAWMRQwEgYDVQQDDAtDTkUgVEVTVEUgMzCCAjgwCwYJ
KoZIhvcNAQEBA4ICJwAwggIiMA0GCSqGSIb3DQEBAQUAA4ICDwAwggIKAoICAQCd
YHeqD8rwL2AtAeX1CLVxVP3LF9sjRDlSY6/0nrkr+WxNICHP5FI6GFTTLlHvgkwW
P4JKCIsEe6q+w7KfY5/BUy5wC65+o9bG25KA+MrUyN1h1Lonn8/6AKb/h+cz7MI9
yalMl2iu28zeQJHNzzRVM0W9/lG7WANn14pwQHsMa6WYnRl9APoqAvvqj6tOgD04
qPUlkgQRhGYJizgB6ZHR4TVAGj/TCV0XEPZOJIpTrd7nsET+xCjMjBg8jT3qg7Vg
lghIn+72Yi0nKykmN5duZwlvcFTfKkNBvJicDExYZ7WXxu9PfJETdHyFQLLck+Cr
MlSDloI/K9qWfdd8iX6GzETspfPV+ZXkdvfIM8A4TdlCiVx5n+1xc6jk4NB5eHSu
S80oNO0ctg6qKBcHb8YwV5VnQFZE3WaOZTORUBq+bjQxci9g0MA7ZqTK0O0K1QOL
Gl38AbDFjHpdtLIl/LdmzhSFx3NR4lA8RE4AkMOOeNqcDrRT4/PlBWoPsqWYcpPL
6AGl0I8N6hrm1iOvIxTWU6zV40E4SJSViPNzlo3L5iK+Ej4G3/YSCB8850nc6j11
3QGUTUvX8a8ZoKE3BuCO3LtYWYAb/RxyGlCq9jMFwHTYqqHu9cA5CwilMfP31SZ4
bMKhwR2AI/iowcMqCVtSZYi/dUDk9wY89nqY+5I+7QIDAQABo4IBiDCCAYQwRgYF
YEwBCgEEPTE5OTgtMDMtMTY2NzE0ODUyNDYwMTAwNzQ0NjQyMjU2NTIzNTAwMDAw
MDAwMDAwMDAwMDAwMDAwMDAwMDAwQwYFYEwBCgIEOlVuaXZlcnNpZGFkZSBDYW5k
aWRvIE1lbmRlc1N1cGVyaW9yRGlyZWl0b1JpbyBkbyBKYW5laXJvUkowIgYFYEwB
BAMEGUx1aXMgSW5hY2lvIEx1bGEgZGEgU2lsdmEwYgYIKwYBBQUHAQEEVjBUMFIG
CCsGAQUFBzAFhkZodHRwczovL3ZhbGlkYS5zb3BhZ29tZWlhLmNvbS5ici9nZXRf
YXV0aG9yaXR5X2luZm9ybWF0aW9uX2FjY2Vzcy83NDU3MDgGA1UdHwQxMC8wLaAr
oCmGJ2h0dHBzOi8vZG9taW5pby5jb20vZ2V0X2NybC9jb2RpZ29fZWVhLzAzBgNV
HSMELDAqgCg4OGQwZGU4MmMxYzE4NjJlZjUzYjExMWIwMzE2ODRlYWE1YjAwM2Ri
MAsGCSqGSIb3DQEBCwOCAQEAAhxXh4ouoo3pv12/nYyIKWDNDuRdAXCVasAQtpn6
ZOfOzde1a2AnqMET04BrR5SSpBeBq+aVacXtIVQCPoBD7F8+NppEM+q/Gw8aGugP
dXGKTgMQZMGI1vHMsydNB3tg0MoepUyr3V6HmBSGQkRq8uLiQ2Ke3Fm6/I+BOdNl
oe6/VBcD3zOMM+qnqM/ucR2Lcje0deifGTVnP16bISBk8077PxzGq1Ds2jLrDj1+
KsVA4JKBCZgDT3BBCQrKbXnENDeCSZ9TVlzgcNBFnFQzWDga3UjLvhEj8SjSg9Rl
e1jK7e83C6A96ixfUDlD6pVPl57QHAaalnQ6aHONq2wamg==
-----END CERTIFICATE-----

What's wrong with this file or with the code from that thread? I can't extract the public key.


text:
Q: jQuery update table row depending on how user inputs data I have a table with rows of 2 input text boxes in each row:

<input id="1_1" type="text">	<input id="1_2" type="text">

<input id="2_1" type="text">	<input id="2_2" type="text">

<input id="3_1" type="text">	<input id="3_2" type="text">

If the user has just one of the input texts filled in, I would like to append a certain icon in front of the row.  If the user has both inputs filled in, I would like to append a different type of icon.  All of this occurs on a per row basis.  How would I go about accomplishing this?
Any suggestions would be greatly appreciated.

A: Have you tried anything? Seems like some pretty straightforward jQuery to me.
Here's a working example where I've added an additional  prior to the input fields and inserted a

 inside of it as a placeholder for the icon you want.
The jQuery for changing it is the following:
$(function(){
    $('input').keyup(function(){
        var row = $(this).parent().parent();
        var inputsChanged = 0;
        row.find('input').each(function(){
            if($(this).val() !== '') inputsChanged++;
        });
        if(inputsChanged === 1){
            row.find('.icon').css('background-color','red');
        }else if(inputsChanged === 2){
            row.find('.icon').css('background-color','green');
        }else if(inputsChanged === 0){
            row.find('.icon').css('background','none');
        }
    });
});


text:
Q: Google Analytics Send Event on Ajax Success Not Working I have a Process Transaction Knockout method that returns a transaction status and depending on that status I want analytics.js event to be sent. I've used analytics-debug.js and in the console it says "Send finished" but the event never shows up in Google Analytics.
The send event works if it is before or after the ajax request but not if it is in the success or done callbacks.
$.ajax({
    url: '/ProcessTransaction',
    type: 'post',
    data: 'data',
    contentType: 'application/json',
    success: function (result) {
        if (result.StatusCode == 1 || result.StatusCode == 4) {
            var subtotal = 7.95;
            var enrollmentFee = 25;
            var total = subtotal + enrollmentFee;
            ga('ec:addProduct', {
                'id': 'P12345',
                'name': 'Test Product 1',
                'category': 'Products',
                'brand': 'Brand',
                'price': subtotal,
                'quantity': 1
            });
            ga('ec:setAction', 'purchase', {
                'id': 'T12345',
                'affiliation': 'TestSite',
                'revenue': total,
                'tax': enrollmentFee,
            });
            ga('send', 'event', 'Review', 'transaction', 'approved', total);
            $('#submitpaymentbtn').data('loading-text', 'Approved!').button('loading');
            window.location.href = '@Url.Action("Confirmation", new { ParticipantId = Participant.ParticipantId })';
        }
        else {
            $('#modal-error').modal();
        }
    }
});

A: Send event does not allow decimal for event value. Math.round(total) fixes the issue. Even thought the analytics debug says event sent, it is never accepted or logged because the value must be an integer.
ga('send', 'event', 'Review', 'transaction', 'approved', Math.round(total));


text:
Q: Blank space in the y direction between card element when maping through array, what is the reason? I'm creating a React project with Tailwindcss, I have an array of objects (projects). I'm mapping through them and returning Card components. When the flex wrap takes action there are blank spaces between the cards in the y direction which I can't seem to figure out why.
Main:

          {filteredProjects.map((item) => {
            return (

                <ProjectCard project={item} />

            );
          })}

And the Card component:

{project.name}

            <svg
              xmlns="http://www.w3.org/2000/svg"
              fill="none"
              viewBox="0 0 24 24"
              strokeWidth="1.5"
              stroke="currentColor"
              className="w-6 h-6 text-stone-500 mt-1"
            >
              <path
                strokeLinecap="round"
                strokeLinejoin="round"
                d="M10.343 3.94c.09-.542.56-.94 1.11-.94h1.093c.55 0 1.02.398 1.11.94l.149.894c.07.424.384.764.78.93.398.164.855.142 1.205-.108l.737-.527a1.125 1.125 0 011.45.12l.773.774c.39.389.44 1.002.12 1.45l-.527.737c-.25.35-.272.806-.107 1.204.165.397.505.71.93.78l.893.15c.543.09.94.56.94 1.109v1.094c0 .55-.397 1.02-.94 1.11l-.893.149c-.425.07-.765.383-.93.78-.165.398-.143.854.107 1.204l.527.738c.32.447.269 1.06-.12 1.45l-.774.773a1.125 1.125 0 01-1.449.12l-.738-.527c-.35-.25-.806-.272-1.203-.107-.397.165-.71.505-.781.929l-.149.894c-.09.542-.56.94-1.11.94h-1.094c-.55 0-1.019-.398-1.11-.94l-.148-.894c-.071-.424-.384-.764-.781-.93-.398-.164-.854-.142-1.204.108l-.738.527c-.447.32-1.06.269-1.45-.12l-.773-.774a1.125 1.125 0 01-.12-1.45l.527-.737c.25-.35.273-.806.108-1.204-.165-.397-.505-.71-.93-.78l-.894-.15c-.542-.09-.94-.56-.94-1.109v-1.094c0-.55.398-1.02.94-1.11l.894-.149c.424-.07.765-.383.93-.78.165-.398.143-.854-.107-1.204l-.527-.738a1.125 1.125 0 01.12-1.45l.773-.773a1.125 1.125 0 011.45-.12l.737.527c.35.25.807.272 1.204.107.397-.165.71-.505.78-.929l.15-.894z"
              />
              <path
                strokeLinecap="round"
                strokeLinejoin="round"
                d="M15 12a3 3 0 11-6 0 3 3 0 016 0z"
              />
            </svg>

          <DateShower started={project.started} finished={project.finished} />

            <svg
              xmlns="http://www.w3.org/2000/svg"
              fill="none"
              viewBox="0 0 24 24"
              strokeWidth="1.5"
              stroke="currentColor"
              className="w-6 h-6"
            >
              <path
                strokeLinecap="round"
                strokeLinejoin="round"
                d="M9 12h3.75M9 15h3.75M9 18h3.75m3 .75H18a2.25 2.25 0 002.25-2.25V6.108c0-1.135-.845-2.098-1.976-2.192a48.424 48.424 0 00-1.123-.08m-5.801 0c-.065.21-.1.433-.1.664 0 .414.336.75.75.75h4.5a.75.75 0 00.75-.75 2.25 2.25 0 00-.1-.664m-5.8 0A2.251 2.251 0 0113.5 2.25H15c1.012 0 1.867.668 2.15 1.586m-5.8 0c-.376.023-.75.05-1.124.08C9.095 4.01 8.25 4.973 8.25 6.108V8.25m0 0H4.875c-.621 0-1.125.504-1.125 1.125v11.25c0 .621.504 1.125 1.125 1.125h9.75c.621 0 1.125-.504 1.125-1.125V9.375c0-.621-.504-1.125-1.125-1.125H8.25zM6.75 12h.008v.008H6.75V12zm0 3h.008v.008H6.75V15zm0 3h.008v.008H6.75V18z"
              />
            </svg>
            {project.taskCount}

            <svg
              xmlns="http://www.w3.org/2000/svg"
              fill="none"
              viewBox="0 0 24 24"
              strokeWidth="1.5"
              stroke="currentColor"
              className="w-6 h-6"
            >
              <path
                strokeLinecap="round"
                strokeLinejoin="round"
                d="M15 19.128a9.38 9.38 0 002.625.372 9.337 9.337 0 004.121-.952 4.125 4.125 0 00-7.533-2.493M15 19.128v-.003c0-1.113-.285-2.16-.786-3.07M15 19.128v.106A12.318 12.318 0 018.624 21c-2.331 0-4.512-.645-6.374-1.766l-.001-.109a6.375 6.375 0 0111.964-3.07M12 6.375a3.375 3.375 0 11-6.75 0 3.375 3.375 0 016.75 0zm8.25 2.25a2.625 2.625 0 11-5.25 0 2.625 2.625 0 015.25 0z"
              />
            </svg>
            {project.userCount}

Picture of black space:
blank_space
I already tried setting the Card's div margins to 0 and also tried "gap-y-0" none of those worked. I'm curious why this is happening and how can I solve it.

A: The culprit is most likely the h-full class in the cards container.
It's taking the full height of its parent container (not shown in your code), and the cards inside it are being distributed accordingly, i.e., each row gets half of the height.
To fix this just remove the h-full class. Also flex-row is the default, so you can remove that too.

  {filteredProjects.map((item) => {
    return (

        <ProjectCard project={item} />

    );
  })}

For future posts (or for this one in case my answer isn't exactly right), I'd suggest you post the full code (within reason) and add a reproducible example using something like https://play.tailwindcss.com/, as that helps people who are answering your question, so you're more likely to get an answer.


text:
Q: Converting String Data Values with two commas from csv or txt files into float in python I just received a dataset from a HPLC run and the problem I ran into is that the txt data from the software generates two dotted separated values for instance "31.456.234 min". Since I want to plot the data with matplotlib and numpy I can only see the data where the values are not listed with two commas. This is due to every value which is smaller than 1 is represented with one comma like "0.765298" the rest of the values is, as aforementioned, listed with two commas.
I tried to solve this issue with a .split() and .find() method, however, this is rather inconvenient and I was wondering whether there would be a more elegant way to solve this issue, since I need in the end again x and y values for plotting.
Many thanks for any helping answers in advance.

A: This is not very clear regarding comma and dots.
For the decimal number you say that you have comma but you show a dot : 0.765298
I guess you can not have dots for either thousand separator and decimal...
If you have english notation I guess the numbers are:
"31,456,234 min" and "0.765298"
In this case you can use the replace method :
output = "31,456,234"
number = float(output.replace(',',''))
# result : 31456234.0

EDIT
Not very sure to have understood what you are looking for and the format of the numbers...
However if the second comma in 31.456.234 is unwanted here is a solution :
def conv(n):
    i = n.find('.')
    return float(n[:i]+'.'+n[i:].replace('.',''))

x = '31.456.234'
y = '0.765298'

print(conv(x)) # 31.456234
print(conv(y)) # 0.765298


text:
Q: Cannot find .runtransaction() equivalent for Firebase Cloud Firestore I had previously called the .runtransaction()method when I anticipated users would be simultaneously writing to a location in Firebase
 private void increasePollTotalVoteCounter(int checkedRadioButtonID) {
    mSelectedPollRef.child("vote_count").runTransaction(new Transaction.Handler() {
        @Override
        public Transaction.Result doTransaction(MutableData mutableData) {
            mutableData.setValue((Long) mutableData.getValue() + 1);
            return Transaction.success(mutableData);
        }

        @Override
        public void onComplete(DatabaseError databaseError, boolean b, DataSnapshot dataSnapshot) {
            if (databaseError != null){
                Toast.makeText(getActivity().getApplicationContext(), databaseError.getMessage(), Toast.LENGTH_LONG).show();
            }

        }
    });
}

I am trying to find the equivalent in the new Cloud Firestore API, I was unable to locate in the documentation. Any help is appreciated.

A: Firestore have transactions for simultaneous database writes,
The documentation is in here
Also here is a sample code
private Task<Void> addRating(final DocumentReference restaurantRef,
                             final Rating rating) {
    // Create reference for new rating, for use inside the transaction
    final DocumentReference ratingRef = restaurantRef.collection("ratings")
            .document();

    // In a transaction, add the new rating and update the aggregate totals
    return mFirestore.runTransaction(new Transaction.Function<Void>() {
        @Override
        public Void apply(Transaction transaction)
                throws FirebaseFirestoreException {

            Restaurant restaurant = transaction.get(restaurantRef)
                    .toObject(Restaurant.class);

            // Compute new number of ratings
            int newNumRatings = restaurant.getNumRatings() + 1;

            // Compute new average rating
            double oldRatingTotal = restaurant.getAvgRating() *
                    restaurant.getNumRatings();
            double newAvgRating = (oldRatingTotal + rating.getRating()) /
                    newNumRatings;

            // Set new restaurant info
            restaurant.setNumRatings(newNumRatings);
            restaurant.setAvgRating(newAvgRating);

            // Commit to Firestore
            transaction.set(restaurantRef, restaurant);
            transaction.set(ratingRef, rating);

            return null;
        }
    });
}


text:
Q: image sprites as background on webpage Is there a way to optimize page loading times of a sprite/texture based background on a website?
Basically the look I'm trying to go for, is a 2d representation of Minecraft, with everything above the grassline to be a header, and bedrock as the footer.
Similar to www.projectminecraft.com and www.dokucraft.co.uk
But I'm worried about page load times, yet want to have caves and other details.

A: For a large background of repeated content you'd want to create an image that tiles in it's smallest form, then use background-repeat: repeat in your CSS.
If it's not possible to tile the entire thing, then try and tile as much as possible (the edges and bottom are usually a good place). Don't forget you can use multiple background images in modern browsers (see their adoption in browsers on caniuse.com).
The second example you listed does however uses one large png, and in this case, you should ensure you're only using the minimum colours you require and compress the image as far as you can with something like http://imageoptim.com/.

A: To use a sprite-sheet, create one large png (or jpg if you'd like and there's no transparency) that has all of your images on it. (example)
Next, for each element you want to have an image, set the background to something like:
background:url(my-sprite-sheet.png) 10px 40px no-repeat;
In this example, the coordinates relate to your sprite sheet. It tells the background to have the upper-left corner of the background begin at 10px from the right of your image and 40px from the bottom. (strangely enough, 0 0 would be the upper-left corner of your image)
As far as I know, you can't do this for repeated (tiled) backgrounds. For that, have each "tile" as it's own image and use something like background:url(my-background.png);. By default, the image will repeat on both the x and y axis. You can further define the repeat with repeat-x repeat-y and no-repeat.
Hope this helps!


text:
Q: How to use, like Google oauth2, to login from web app and access the resource server I'm trying to do a POC project. I want to login just like stackoverflow. User just login their google account without having to register first and forget password in the future.
My stack is Angular + Spring boot. Angular or React shouldn't matter here. I have did some research and see how people setup on Google GCP and use it in the webapp.
Ok, now assume I can login in my webapp. I got user's name, picture, etc. How would my Spring boot server auth with the info I got from google?
Any help is appreciated!

A: Usually, you would get a JWT from Google (or other type of token) that you need to send to your Spring Boot server.
The server should then be configured to verify the token. See https://docs.spring.io/spring-security/reference/servlet/oauth2/resource-server/index.html and https://docs.spring.io/spring-security/reference/servlet/oauth2/resource-server/jwt.html (for JWT).
Basically, add spring-security-oauth2-resource-server (and spring-security-oauth2-jose if JWT) and set the issuer-uri in your applications.(yml | properties)
I think it is https://accounts.google.com/ for Google. This also assumes that you have created app/oauth2 in google console. See https://developers.google.com/identity/protocols/oauth2/openid-connect for details.


text:
Q: how to add a call back function in google.maps.places.PlacesService(map).textSearch() I am trying to find distance between location entered(request.location) and location obtained from results of textSearch

////function,google.maps.geometry.spherical.computeDistanceBetween (x,y) is what i am using to do that ,so how to insert the request.location value as x
var x = new google.maps.LatLng(52.395715, 4.888916);
var request = {
  location: x,
  radius: '500',
  query: 'restaurant'
};
var service = new google.maps.places.PlacesService(resultsMap);
service.textSearch(request, callback);

function callback(results, status) {
  if (status == google.maps.places.PlacesServiceStatus.OK) {
    for (var i = 0; i < results.length; i++) {
      var y = results[i].geometry.location;
      console.log(y);
    }
  }
}

A: The way your code is structured, x will be available inside the callback routine.  Just do:
  var y = results[i].geometry.location;
  +" km
";
  console.log(y);
  console.log((google.maps.geometry.spherical.computeDistanceBetween(x,y)/1000).toFixed(2)+" km");

proof of concept fiddle
code snippet:

function initialize() {
  var resultsMap = new google.maps.Map(
    document.getElementById("map_canvas"), {
      center: new google.maps.LatLng(37.4419, -122.1419),
      zoom: 13,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    });
  ////function,google.maps.geometry.spherical.computeDistanceBetween (x,y) is what i am using to do that ,so how to insert the request.location value as x
  var x = new google.maps.LatLng(52.395715, 4.888916);
  var requestLocation = new google.maps.Marker({
    position: x,
    map: resultsMap,
    title: "request position",
    icon: "http://maps.google.com/mapfiles/ms/micons/blue.png"
  });
  var request = {
    location: x,
    radius: '500',
    query: 'restaurant'
  };
  var service = new google.maps.places.PlacesService(resultsMap);
  service.textSearch(request, callback);

  function callback(results, status) {
    if (status == google.maps.places.PlacesServiceStatus.OK) {
      var bounds = new google.maps.LatLngBounds();
      for (var i = 0; i < results.length; i++) {
        var y = results[i].geometry.location;
        document.getElementById("distance").innerHTML += "[" + i + "]  name:" + results[i].name + ", distance=" + (google.maps.geometry.spherical.computeDistanceBetween(x, y) / 1000).toFixed(2) + " km
";
        console.log(y);
        var marker = new google.maps.Marker({
          position: results[i].geometry.location,
          map: resultsMap,
          title: results[i].name
        });
        bounds.extend(marker.getPosition());
      }
      resultsMap.fitBounds(bounds);
    }

  }
}
google.maps.event.addDomListener(window, "load", initialize);
html,
body,
#map_canvas {
  height: 500px;
  width: 500px;
  margin: 0px;
  padding: 0px
}


text:
Q: Custom Managed Object missing file and edit on Salesforce1 I'm currently trying to have my users on Salesforce1 edit records and upload pictures from their phone to the associated record. They currently have the edit button overridden to their custom visualforce page and I can't seem to get it to default back to the regular pages. I'm not sure if the overridden button is whats preventing the edit button from appearing on the layout.
I've also enabled publisher actions and salesforce1 actions on the layout with the file button their. For some reason I can't see the file button on the actions menu. Any idea why I can't edit or file upload. I have administrator access to the entire org.

A: If i have understand your question correctly then your button is not coming in Salsforce one action bar.
You have missed the checkbox on Visualforce to enabe the page for salesforce one and lightning.
Go to Develop > Visualforce page > select your page and check the checkbox. it will solve the problem.

A: Just forgot to enable feed tracking


text:
Q: Django-reversion : incompatible version data during field_dict access I have the following script:
import django
import os
import sys
from django.db import transaction
from xxx.models import File
import reversion
from reversion.models import Version
from datetime import datetime

# Creating a file entry in here:
with reversion.create_revision():
    f = File(name="foo", mtime=datetime.now(), ctime=datetime.now(), size=33)
    f.save()

    reversion.set_comment("Revision 1")

# Modifying it:
with reversion.create_revision():
    f.mtime = datetime.now()
    f.ctime = datetime.now()
    f.size = 23
    f.save()

    reversion.set_comment("Revision 2")

versions = Version.objects.get_for_object(f)
print(len(versions))
for i in range(len(versions)):
    print(versions[i])
    print(versions[i].field_dict) # ERROR!
    print(versions[i].revision.__dict__)

Here's the very long traceback:
Traceback (most recent call last):
  File "/home/rzhang2/pythons/anaconda2/envs/python36/lib/python3.6/site-packages/django/core/serializers/python.py", line 166, in Deserializer
    data[field.name] = field.to_python(field_value)
  File "/home/rzhang2/pythons/anaconda2/envs/python36/lib/python3.6/site-packages/django/db/models/fields/__init__.py", line 1246, in to_python
    params={'value': value},
django.core.exceptions.ValidationError: ["'2018-04-24T21:38:14.319' value has an invalid date format. It must be in YYYY-MM-DD format."]

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/home/rzhang2/pythons/anaconda2/envs/python36/lib/python3.6/site-packages/reversion/models.py", line 241, in _object_version
    return list(serializers.deserialize(self.format, data, ignorenonexistent=True))[0]
  File "/home/rzhang2/pythons/anaconda2/envs/python36/lib/python3.6/site-packages/django/core/serializers/json.py", line 69, in Deserializer
    yield from PythonDeserializer(objects, **options)
  File "/home/rzhang2/pythons/anaconda2/envs/python36/lib/python3.6/site-packages/django/core/serializers/python.py", line 168, in Deserializer
    raise base.DeserializationError.WithData(e, d['model'], d.get('pk'), field_value)
django.core.serializers.base.DeserializationError: ["'2018-04-24T21:38:14.319' value has an invalid date format. It must be in YYYY-MM-DD format."]: (xxx.file:pk=foo) field_value was '2018-04-24T21:38:14.319'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "play_with_reversion.py", line 47, in <module>
    print(versions[i].field_dict)
  File "/home/rzhang2/pythons/anaconda2/envs/python36/lib/python3.6/site-packages/django/utils/functional.py", line 36, in __get__
    res = instance.__dict__[self.name] = self.func(instance)
  File "/home/rzhang2/pythons/anaconda2/envs/python36/lib/python3.6/site-packages/reversion/models.py", line 283, in field_dict
    field_dict = self._local_field_dict
  File "/home/rzhang2/pythons/anaconda2/envs/python36/lib/python3.6/site-packages/django/utils/functional.py", line 36, in __get__
    res = instance.__dict__[self.name] = self.func(instance)
  File "/home/rzhang2/pythons/anaconda2/envs/python36/lib/python3.6/site-packages/reversion/models.py", line 261, in _local_field_dict
    object_version = self._object_version
  File "/home/rzhang2/pythons/anaconda2/envs/python36/lib/python3.6/site-packages/django/utils/functional.py", line 36, in __get__
    res = instance.__dict__[self.name] = self.func(instance)
  File "/home/rzhang2/pythons/anaconda2/envs/python36/lib/python3.6/site-packages/reversion/models.py", line 244, in _object_version
    "object_repr": self.object_repr,
reversion.errors.RevertError: Could not load name: foo mtime: 2018-04-24 21:30:15.468835 ctime: 2018-04-24 21:30:15.468838 size: 23 version - incompatible version data.

So obviously something is wrong with field_dict, during deserialization.
I then tried to restart all revisions and do it again:
python manage.py deleterevisions

I ran it again, and it still gave the same error.
My schema is fairly simple:
@reversion.register
class File(models.Model):
    name = models.CharField(max_length=400, primary_key=True)
    mtime = models.DateField()
    ctime = models.DateField()
    size = models.IntegerField()

    def __str__(self):
        return "name: {} mtime: {} ctime: {} size: {}".format(self.name, self.mtime, self.ctime, self.size)

What exactly is going on?
Note: If I remove that specific line, here's my output(after running python manage.py deleterevisions to refresh):
3
name: foo mtime: 2018-04-24 21:45:26.497498 ctime: 2018-04-24 21:45:26.497501 size: 23
{'_state': <django.db.models.base.ModelState object at 0x7f6e7aa16f28>, 'id': 42, 'date_created': datetime.datetime(2018, 4, 24, 21, 45, 26, 497470, tzinfo=<UTC>), 'user_id': None, 'comment': 'Revision 2'}
name: foo mtime: 2018-04-24 21:45:26.475707 ctime: 2018-04-24 21:45:26.475711 size: 33
{'_state': <django.db.models.base.ModelState object at 0x7f6e7aa24080>, 'id': 41, 'date_created': datetime.datetime(2018, 4, 24, 21, 45, 26, 470003, tzinfo=<UTC>), 'user_id': None, 'comment': 'Revision 1'}
name: foo mtime: 2018-04-24 ctime: 2018-04-24 size: 23
{'_state': <django.db.models.base.ModelState object at 0x7f6e7aa24198>, 'id': 40, 'date_created': datetime.datetime(2018, 4, 24, 21, 45, 13, 671939, tzinfo=<UTC>), 'user_id': None, 'comment': 'Initial version.'}

A: So I figured out the reason. For some reason, passing in a datetime object into the DateField type of my models is not valid. I was not aware there was a DateTimeField which is exactly for this purpose.
Django did not complain when I passed in a datetime object and it appears that it probably does implicit casting. However, the library django-reversion probably took the value before implicit conversion and tried to deserialize the object into the model which did not prove to be successful with a datetime object.
As per documentation for DateTimeField:

A date and time, represented in Python by a datetime.datetime instance.


text:
Q: The difference between "Subset" and "SubsetRandomSampler" Recently, I am trying to solve K-fold Cross Validation problem by using Subset and SubsetRandomSampler method.
When I using the Subset method, the first epoch accuracy for CIFAR10 dataset is 88% , However, when I using the SubsetRandomSampler method, first epoch accuracy for CIFAR10 dataset only got 16%. It really confuse my and I have no idea. Does anybody know about that? Thanks a lot.
The code for Subset method:
 for fold,(trainLoader,valLoader) in enumerate(kf.split(trainSet)):

      trainSetBasic = torch.utils.data.Subset(trainSet, trainLoader)
      valSetBasic = torch.utils.data.Subset(trainSet, valLoader)

      dataloaders = {
  'train': DataLoader(trainSetBasic, batch_size=BATCH_SIZE, shuffle=True, num_workers=2),
  'val': DataLoader(valSetBasic, batch_size=BATCH_SIZE, shuffle=True, num_workers=2)
  }

The code for SubsetRandomSampler method:
for fold,(trainLoader,valLoader) in enumerate(kf.split(trainSet)):

      train_subsampler = torch.utils.data.SubsetRandomSampler(trainLoader)
      val_subsampler = torch.utils.data.SubsetRandomSampler(valLoader)

      dataloaders = {
  'train': DataLoader(trainSet, batch_size=BATCH_SIZE, sampler=train_subsampler, shuffle=False, num_workers=2),
  'val': DataLoader(trainSet, batch_size=BATCH_SIZE, sampler=val_subsampler, shuffle=False, num_workers=2)
  }

And the code for other parts are all the same.

A: It seems to me that the difference between both codes is the manual shuffling of the indices.
How is your Dataset defined - are the classes sorted internally? If it is, using SubsetRandomSampler you would only pass the first classes to train_subsampler and the last classes to the val_subsampler. That would explain the bad accuracy.


text:
Q: trick double integral Edwards and Penney. Calculus Early Transcendentals. 7th edition, page 1018. $R$ is the unit disk in the $xy$-plane. Evaluate
$$
\iint_R\left(5-x^2\sin{}x+y^3\cos{}y\right)\,dA
$$
It's a "trick integral" in the sense that it's easier to think about the volume of the solid with the unit disk at the base instead of actually integrating (using iterated integrals); but I don't see how to do it.

A: Hint: After breaking it into three double integrals:
$$\iint_R 5\, dA - \iint_R x^2\sin x\, dA + \iint_R y^3\cos y\, dA,$$
think which of these three you could realistically compute (or interpret as a volume). For the other(s), is there any symmetry within $R$ that allows you to know the value of the integral?
If you haven't used symmetry arguments before, consider a basic integral $\displaystyle \int_{-1}^1 x^3\, dx$.


text:
Q: Headers appear in browser but are missing in Response object I have a .NET application running on IIS 7.5 with the following response headers returned, as shown on Chrome's network page:
HTTP/1.1 200 OK
Cache-Control: private
Content-Type: text/html; charset=utf-8
Content-Encoding: gzip
Vary: Accept-Encoding
Server: Microsoft-IIS/7.5
X-AspNetMvc-Version: 3.0
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET
Date: Fri, 21 Sep 2012 16:11:55 GMT
Content-Length: 840

In the C# code I try to read those response headers, but the only ones retrieved by HttpContext.Response.Headers are the following two:

*

*Server: Microsoft-IIS/7.5

*X-AspNetMvc-Version: 3.0

Needless to say, both HttpContext.Response.Headers.AllKeys.Length and HttpContext.Response.Headers.Keys.Count return 2.
Since in the production environment the application will have to read an extra response header, a dynamic one, I need to be able to intercept ALL those headers.
A solution would be greatly appreciated.

A: Theses headers are private on IIS 7.5
You can add a Response Header by executing theses steps:

*

*Open your IIS Manager, navigate to the level you want to manage.

*In Features View, Double click "HTTP Respond Headers" feature.

*Click "Add…" on the Actions Panel


text:
Q: Como montar esse efeito com JS? Tenho uma lista, e gostaria de criar um loop passando cada um desses elementos, basicamente o que quero é esse efeito:
$.each($('.elemento'), function(i, el){
   $(el).fadeIn(100);
   $(el).delay(400).addClass("esconder");
   /*esperar 400ms até o loop rodar de novo fazendo o mesmo efeito com o próximo elemento*/
});

Como eu posso acrescentar esse delay ao fim do meu loop antes que ele interaja com o próximo elemento? Ele passa mostra o elemento e em seguida cria um efeito fadeOut já definido no CSS

A: Uma maneira de fazer isso seria usando setTimeout ou setInterval.
Acho que algo mais ou menos assim talvez funcione:
var elms = $('.elemento');
var i = 0;
var interval = setInterval(function(){
    if (i >= elms.length) {
        clearInterval(interval);
    } else {
        var el = elms[i++];
        $(el).fadeIn(100);
        $(el).delay(400).addClass("esconder");
    }
}, 900);


text:
Q: How to deal with imbalanced classes in Keras I am working on a multi-label image classification problem with Keras and so I utilize functions flow_from_dataframe() and fit_generator().
I have about 2000 classes and as you can guess they are highly skewed / imbalanced. After searching a bit I came across with arguments class_weight and classes and I decided to give them a try. My problem is, I am not sure if I use them correctly. Here is an example:
Let's assume that I have flatten all class occurrences so that I get the following list of (duplicated) labels:
labels = ['classD', 'classA', 'classA', 'classC', 'classD', 'classD']

And this is the function that computes classes and class_weight:
from collections import Counter
def get_classes_weights(l, n):
    counter = Counter(l).most_common(n)
    classes = [cls for cls, ocu in counter]
    majority = max([ocu for cls, ocu in counter])
    weights = {idx: float(majority/ocu) for idx, (cls, ocu) in enumerate(counter)}
    return classes, weights

Let's also assume that I what to consider the top-2 classes only:
classes, class_weight = get_classes_weights(labels, 2)

This gives:
classes: ['classD', 'classA']

and:
class_weight: {0: 1.0, 1: 1.5}

And finally, this is how I use them within the functions:
generator_train.flow_from_dataframe(
    classes=classes,
)

model.fit_generator(
    class_weight=class_weight
)

So my question are:

*

*Is the above the right way to apply weights given that I work on a multi-label image classification problem?

*Does my validation set need to be balanced or it is OK if it has been taken from the same distribution as the training set (20% and 80% random selection, respectively)?


text:
Q: Converting mercator meters without UTM zone? I've been attempting to extract track information from Humminbird (Side Imaging Sonar) binary files and have hit a stumbling block with the coordinates it provides. The values are apparently in Mercator meters but no UTM zone is supplied in the output. I would like to know if anyone knows of a mercator meter conversion that doesn't require a UTM zone, and if so how do you do it? I've found one conversion which kind of does the job but not acurately enough (http://www.oziexplorer3.com/eng/eagle.html).
So basically I get the numbers  Lon: 16226043 Lat: -4557743. I know these should convert to 145.75528834210039 and -38.032398555522214 but can't work out how.
I've had a discussion about this issue on a more dedicated forum but came to a dead end (http://forums.sideimagingsoft.com/index.php?topic=5623.msg35417). I could be reading the binary section wrong but all other data in the line comes out fine.

A: Thanks to your good description I guessed that the projection that Hummingbird is using is "WGS 84 / World Mercator" which has EPSG-code EPSG:3395. More information about this projection:
http://spatialreference.org/ref/epsg/3395/
http://epsg.io/3395
http://epsg-registry.org/report.htm?type=selection&entity=urn:ogc:def:crs:EPSG::3395&reportDetail=short&style=urn:uuid:report-style:default-with-code&style_name=OGP%20Default%20With%20Code&title=EPSG:3395
For converting coordinates between different projections you can use for example gdaltransform http://www.gdal.org/gdaltransform.html
Test with your coordinates:
gdaltransform -s_srs epsg:3395 -t_srs epsg:4236
16226043 -4557743
145.751771880036 -38.033447580973 -512.892291001976

Latitude and longitude seems to be accurate. I do not know what -512 as Z-coordinate means but perhaps it has something to do with the WGS84 spheroid.


text:
Q: Create function for indirect reference to JSON path and value I want to use a configuration JSON to tell any function where to get the data from source data JSON.
Example of 3 values I want to add to an array mapped to value:
data = {
    "value1" : "Hello",
    "value2" : "World",
    "object" : {
        "value3" : "Great"
    }
}

For this most basic example, I want to create the following using configuration:
example = {
    "example_array" : [
        {"value" : "Hello"},
        {"value" : "World"},
        {"value" : "Great"}
]}

What I would prefer is to use a config file which has this:
{
    "paths" : [
        {
            "source" : "data",
            "origin_path" : "",
            "origin_value" : "['value1']"
        },
        {
            "source" : "data",
            "origin_path" : "",
            "origin_value" : "['value2']"
        },
        {
            "source" : "data",
            "origin_path" : "['object']",
            "origin_value" : "['value1']"
        }
    ]
}

If I could create a function like set_mapping(destination, source, path, value) then I want to loop through the paths rows with something like this:
for x in origin['paths']:
    origin_data = setmapping(
                value,
                config['paths'][x]['source'],
                config['paths'][x]['origin_path'],
                config['paths'][x]['origin_value']
                )
    example['example_array'].append using origin_data

Original Question
I want to know if I can control data paths from a configuraiton file so I can process a list of transformations in a loop rather than code for each. In Excel, I would call this an INDIRECT reference to a value used to make up a part of a function, in Python, I can't find out how to do it.
Here's a manual example of what I want to do:
print(data['liability_asset']['acceptance']['contractors_and_subcontractors']['contractors_and_subcontractors_engaged'])

What I want to be able to do is this instead is maybe have a data path function. I imagine the function to have a definition which is like data_path(source, path, value) but that's as far as I got.
for x in config['paths]:
    print(data(data_path(['config']['paths'][x]['source'],['config']['paths'][x]['origin_path'], data_path(['config']['paths'][x]['origin_value']

Here's an extract from the horrible verbose, nested origin data I need to transform from:
data = {
          "liability_asset": {
              "acceptance" : {
                  "contractors_and_subcontractors" : {
                      "contractors_and_subcontractors_engaged" : "YES"
                      }
                  }
              }
       }

Here's the config file I intend to use for starters:
config = {
    "paths" : [
            {
                 "source" : "data",
                 "origin_path" : "['liability_asset']['acceptance']['contractors_and_subcontractors']",
                 "origin_value" : "['contractors_and_subcontractors_engaged']"
            }

        ]
    }

In addition, if there's a way for the script to allow the config to support . as separator of a path rather than [''] each time, that would make the management of the config file much easier.
Expected result from both is YES

A: import json

all_data = {}

# mock config file, in reality you'd load it.
config = """{
    "paths" : [
        {
            "source" : "data",
            "origin_path" : [],
            "origin_value" : "value1"
        },
        {
            "source" : "data",
            "origin_path" : [],
            "origin_value" : "value2"
        },
        {
            "source" : "data",
            "origin_path" : ["object"],
            "origin_value" : "value3"
        }
    ]
}
"""
config = json.loads(config)

# Load all of your possible data sources into a dictionary.
# If you already had a 'data' variable, this could just be
# all_data['data'] = data

all_data['data'] = {
    "value1" : "Hello",
    "value2" : "World",
    "object" : {
        "value3" : "Great"
    }
}

def get_data_via_config(config_file:dict, sources:dict) -> dict:
    # For each given path, goes to the origin_path and adds the
    # value of each origin_value to the output dict, by name.
    output = {}
    for path in config_file['paths']:
        source = sources[path['source']]
        for o_path in path['origin_path']:
            source = source[o_path]
        # You can modify this next line and make output a list if desired.
        output[path['origin_value']] = source[path['origin_value']]
    return output

example = get_data_via_config(config, all_data)
print(example)

Output:
{'value1': 'Hello', 'value2': 'World', 'value3': 'Great'}

It works just fine for your more complicated example as well:
all_data['data_adv'] = {
          "liability_asset": {
              "acceptance" : {
                  "contractors_and_subcontractors" : {
                      "contractors_and_subcontractors_engaged" : "YES"
                      }
                  }
              }
       }

config2 = """{
    "paths" : [
            {
                 "source" : "data_adv",
                 "origin_path" : ["liability_asset", "acceptance", "contractors_and_subcontractors"],
                 "origin_value" : "contractors_and_subcontractors_engaged"
            }

        ]
    }
"""
config2 = json.loads(config2)

example2 = get_data_via_config(config2, all_data)
print(example2)

Output:
{'contractors_and_subcontractors_engaged': 'YES'}


text:
Q: how to get latest value and remove old value? I'm making a sql command that will get lastest value everytime user ask question or answer question .But there is an error that when i get answer value , it get all answer & question . I want to get only the latest asnwer. Example :
|    postid | type    | parentid |
|---------  |---------|-----------
| 97        |       A |         92
| 96        |       A |         93
| 95        |       A |         93
| 94        |       Q |        NULL
| 93        |       Q |        NULL
| 92        |       Q |        NULL
| 91        |       Q |        NULL

I tried to use groupby(parentid) . But it don't get any question . Like this:
|    postid | type    | parentid |
|---------  |---------|-----------
| 97        |       A |         92
| 96        |       A |         93

But I want to get :
    the latest answer (don't get answer before of this answer + the question of this answer)
    the question (if don't have answer , keep this question )
|    postid | type    | parentid |
|---------  |---------|-----------
| 97        |       A |         92
| 96        |       A |         93
| 94        |       Q |        NULL
| 91        |       Q |        NULL

here is my code :
 SELECT `p`.*
FROM `qa_posts` `p`
JOIN `user_member` `u` ON u.user_id = p.userid
LEFT JOIN `user_profile` `pr` ON u.user_id = pr.user_id
WHERE p.is_deleted =0
GROUP BY `p`.`parent_id`
ORDER BY `p`.`postid` DESC LIMIT 10

A: How about this?
select max(postid), type, parentid
  from posts
    group by type, parentid

fiddle: http://sqlfiddle.com/#!9/357ce/1
edit
Okay it seems I may have misunderstood, and that you want all unanswered questions, PLUS the latest answer for every other question, but NOT those questions that have an answer? If so, we can do this quite easily with a UNION, this will do it:
select max(postid) p, type, parentid
  from posts
    where type = 'A'
    group by parentid
union
  select p1.postid, p1.type, p1.parentid
    from posts p1
      left join posts p2
        on p1.postid = p2.parentid
      where p2.parentid is null and p1.type = 'Q'
order by p desc;

With an updated fiddle here: http://sqlfiddle.com/#!9/05667/17


text:
Q: Laravel blade template not working I have developed Laravel projects earlier but somehow I'm not able to solve the Blade issue. My @section and @include both are not working for some reason. Here are my files:
composer.json
{
"name": "educo/laraecom",
"description": "The Laravel Framework.",
"keywords": ["framework", "laravel"],
"license": "MIT",
"require": {
    "laravel/framework": "4.1.*",
    "laravelbook/ardent" : "2.*"
},
"autoload": {
    "classmap": [
        "app/commands",
        "app/controllers",
        "app/models",
        "app/database/migrations",
        "app/database/seeds",
        "app/tests/TestCase.php"
    ]
},
"scripts": {
    "post-install-cmd": [
        "php artisan clear-compiled",
        "php artisan optimize"
    ],
    "post-update-cmd": [
        "php artisan clear-compiled",
        "php artisan optimize"
    ],
    "post-create-project-cmd": [
        "php artisan key:generate"
    ]
},
"config": {
    "preferred-install": "dist"
},
"minimum-stability": "stable"
}

views/layouts/index.blade.php
<!DOCTYPE html>

<title>Sports Gears</title>

{{HTML::style(asset("/public/css/common"))}}
{{HTML::style(asset("/public/css/jRating.jquery"))}}
{{HTML::style(asset("/public/css/cart"))}}
{{HTML::style(asset("/public/css/bootstrap.min"))}}
{{HTML::style(asset("/public/css/font-awesome"))}}
{{HTML::style(asset("/public/css/jquery.raty"))}}
{{HTML::style(asset("/public/css/homestyle.css"))}}

{{HTML::script(asset('/public/js/jquery'))}}
{{HTML::script(asset('/public/js/jquery-ui.min'))}}
{{HTML::script(asset('/public/js/jquery.ui.autocomplete.min'))}}
{{HTML::script(asset('/public/js/jquery.raty'))}}
{{HTML::script(asset('/public/js/common'))}}
{{HTML::script(asset('/public/js/cart'))}}

   @include('sub.header')

    @yield('content')

    @include('sub.footer')

views/sub/header.blade.php
some menu based html goes here

views/sub/footer.blade.php
some plain html content goes here

app/routes.php
Route::get('/', "StaticController@index");

app/controllers/StaticController.php
public function index(){

    return View::make('static.index');
}

app/views/static/index.blade.php
@extends('layouts.index')

@section('content')

{{HTML::style(asset("/public/css/jquery-ui.css", "stylesheet"))}}
{{HTML::style(asset("/public/css/jquery.autocomplete.css", "stylesheet"))}}

{{HTML::script(asset('/public/js/bootstrap.min'))}}
{{HTML::script(asset('/public/js/jquery.flexslider-min.js'))}}

            @include('sub.slider')

GET BEST DEAL

@stop

app/views/sub/slider.blade.php

        <?php
        if (!$mainBanners->isEmpty()) {

            foreach ($mainBanners as $banner) {

                $filename = $banner->savedfilename;
                $url = $banner->url;
        ?>

{{HTML::image(asset("/public/banners/" . $filename))}}

        <?php
            }
        }
        ?>

Now when I run the url on server like this:   http://localhost/laraecom I get a blank page. When I check the source html, I get something like this
<link media="all" type="text/css" rel="stylesheet" href="https://localhost/laraecom/public/css/jquery-ui.css">
<link media="all" type="text/css" rel="stylesheet" href="https://localhost/laraecom/public/css/jquery.autocomplete.css">

This means both my @section and @include are not working

A: I am no expert as I write this but i have looked through your code several times
Looking at what is being referenced i can see that it does indeed include all your files and yield the content as requested however the part where from what i can see it causes problem is here
<?php
        if (!$mainBanners->isEmpty()) {

            foreach ($mainBanners as $banner) {

                $filename = $banner->savedfilename;
                $url = $banner->url;
        ?>

{{HTML::image(asset("/public/banners/" . $filename))}}

        <?php
            }
        }
        ?>

Following your code i can see that it is pulling in all the files and their content which is correct but it is just before this PHP code that it cuts of according to the Sample you provided from the browser output.
I dont know where it is getting this information but try removing this putting in some plain text just to see if it writes out and then you can see if the templates work and from there you can tell if its the PHP Statement that is causing the issue.
I cant tell what the if statement is for or where its information is coming from so I cannot define what its output should be...
You can also try to PHP dump the $mainBanners to see if there is anything in that variable.?
Or for further assistance you can paste and example of where you are passing this information from as well has share a more complete output from your browser?

A: In app/views/static/index.blade.php you have two @stop at the end of the file, remove one and it will work.


text:
Q: Extract external image url from Facebook rss feed I have a Facebook page Feed that looks like this,
http://external.ak.fbcdn.net/safe_image.php?d=AQA-U_vFlmf0YW5c&w=130&h=130&url=http%3A%2F%2Fi1.ytimg.com%2Fvi%2FX9Hx6nUTSwE%2Fmaxresdefault.jpg%3Ffeature%3Dog

How to extract what comes between the &url.........featuredog (Extracting only image url) ?
Appreciate any code example.

A: my regex is ugly but does the trick:
<?php
$str = 'http://external.ak.fbcdn.net/safe_image.php?d=AQA-U_vFlmf0YW5c&w=130&h=130&url=http%3A%2F%2Fi1.ytimg.com%2Fvi%2FX9Hx6nUTSwE%2Fmaxresdefault.jpg%3Ffeature%3Dog';

$str = urldecode($str);
preg_match_all('~&url=(.*?)[\?\!]?feature~i', $str, $matches, PREG_PATTERN_ORDER);

echo $matches[1][0];
?>

A: $parts = parse_url('http://external.ak.fbcdn.net/safe_image.php?d=AQA-U_vFlmf0YW5c&w=130&h=130&url=http%3A%2F%2Fi1.ytimg.com%2Fvi%2FX9Hx6nUTSwE%2Fmaxresdefault.jpg%3Ffeature%3Dog');
parse_str($parts['query'], $params);
var_dump($params['url']);


text:
Q: Minecraft command to remove duplicate entities I am making a wireworld cellular automata, and everything is going well except for one thing: placing "wire" cells on both sides of an "empty" cell and filling the gap afterwards causes TWO "WireCell" entities instead of one because of the flood-fill method that I am using. How can I remove all but one entity from each block?

A: you said you found out how to do it, but I'll just give this answer to show other people how to do it,
I did it in three command blocks (five if you include the two command blocks I used to make it loop, could make it loop with only one extra though)
first you'll need a scoreboard objective
/scoreboard objectives add near dummy

first set all of the sheep's scores to zero
/scoreboard players set @e[type=Sheep] near 0

this command makes each sheep in a stack add one to one other sheep in the stack, basically it counts how many is in each stack
/execute @e[type=Sheep,r=50] ~ ~ ~ /execute @e[r=0,type=Sheep,c=1] ~ ~ ~ /scoreboard players add @e[r=1,type=Sheep] near 1

then you kill one sheep that has a score that is more then two
/execute @e[type=Sheep,c=1,score_near_min=2] ~ ~ ~ /kill @e[r=0,c=1,type=Sheep]

loop the above three commands, until all sheep have a score of 1
note: I used the scoreboard objective "near" but you can use what ever you want, as long as you change the name in each command
same with the entity type, just make sure you get every time it says type=Sheep, I counted six occurrences


text:
Q: addthis sending forever pending requests Live page in question:http://nyaii.com/s/index.php?option=com_preachit&view=study&id=200:&Itemid=179

When open in chrome, this page forever shows "sending request" in status bar and loading  icon in page title. It is not happening every time but it is more than often. In network panel I see two pending requests which seem related to Addthis. Anyone encountered this too? What is the cause and solution?

A: I went to your site, but I'm seeing our buttons without any issues.  Are you still experiencing this issue? If so, please let me know what browsers you are seeing this in.
Certain browser extensions, such as an ad blockers, may also cause our tools to not appear on the page. I'd suggest opening your site in a Private Browsing or Incognito window to see if the issue persists.
Thanks,
Elsa.


text:
Q: how to Cater increasing number of request to web api our api client is making enormous number of call to api site, because of which we are frequently getting timeout error for db connection from api. Below are details. we haven't set any pool size in db connection string. any idea why we are getting these error and how to solve it.
Timeout expired. The timeout period elapsed prior to obtaining a connection from the pool.  This may have occurred because all pooled connections were in use and max pool size was reached.
Note -

*

*sql connection thate getting created for sp calls are properly closed.
we are using executedataset which inherently closing db connection after sp call and for executedatareader we are calling datareader.close method.

*framework - do.net 4.8


text:
Q: Why UIWebView loads HTML with embed frames so long? I load my HTML via UIWebView with:
let baseURL = "..."
self.webView.loadHTMLString("\(baseURL)
\(self.post.first!.title)
\(dateHTML)\((self.post.first?.content)!)\(closures)", baseURL: nil)

these 2 lines. In general everything is okay, but when I have on my HTML pages YouTube video frames it does not open the page. It loads, loads and loads the page continuously.
How can I prevent that?
If exactly, I have a loader, and I remove it in:
func webViewDidFinishLoad(webVieww: UIWebView) {
    self.loaderView?.removeFromSuperview()
}

so my loader does not disappear if I have YouTube videos embedded in my HTML. How can I fix and prevent that?


text:
Q: Why does Keras model.predict() result in different probabilities based on the size of testing data? I'm relatively new to Keras and image classification in general and I'm running into an issue that I can't seem to find much information on.
So the gist of it is that I've written a slightly modified version of the resnet50 architecture and am testing it on my own training dataset of 5000 images. The training and testing data has been split into 85% training and 15% testing. The resulting training accuracy is 94.26% and the testing accuracy is 89.02% after 50 epochs. I wanted to verify that model.evaluate was working properly and so I ran model.predict() on the testing data and it produced the same predictions. However, when doing model.predict(test_data[0:3]) to just see the predictions for the first 3 images in the test data, it produces different probability results than before.
For example when doing just model.predict(test_data), I end up getting these predictions for the first 3 images:
 [  3.86609372e-06   9.99959469e-01   8.28523935e-06 ...,   3.81386235e-06
    1.04268118e-07   1.21626453e-09]
 [  5.39615750e-03   2.21778057e-04   1.12958644e-02 ...,   1.02706067e-03
    5.01608439e-02   1.12831332e-01]
 [  1.74208861e-08   2.58701675e-07   4.56858857e-07 ...,   4.93999863e-08
    2.00246024e-08   1.40630873e-05]

So as you can see for example the very first image would be of class 2 with a 99% predicted chance.
However, when I run model.predict(test_data[0:3]), I end up getting different predictions for the same 3 images:
 [  1.27427978e-02   9.65294957e-01   1.36477800e-04   2.46044103e-04
    2.07989533e-02   2.01619656e-07   1.09049659e-04   3.54961463e-04
    2.36560169e-07   1.74340403e-05   2.95751437e-04   3.05204480e-06
    7.25281657e-09]
 [  1.03661343e-02   9.70191788e-04   7.98394233e-02   1.37828933e-02
    4.03248608e-01   2.28452999e-02   1.81689449e-02   4.52506207e-02
    4.14442839e-05   6.90634036e-03   5.04679279e-04   3.94435912e-01
    3.63953644e-03]
 [  4.40177857e-04   3.28276951e-06   5.55719156e-03   1.51521107e-02
    2.68901749e-06   2.38441480e-08   8.34578590e-04   5.70602715e-04
    3.51641923e-01   5.26319724e-03   4.39392490e-04   1.80980451e-02
    6.01996779e-01]

So as you can see, these probabilities are very different. The first image still does predict a class of 2, but in other cases, it predicts different classes which are flat out wrong but are correct when doing model.predict() on the entirety of the testing data. Similarly, if I do something like model.predict(test_data[0:4]), it changes again.
I'm so confused on why this is happening. If anyone has any insight or has encountered something similar, I would really appreciate if you could tell me what's going on.
I apologize if this isn't much information to go on, please let me know if there's any further info you need.


text:
Q: behavior of calling function of unmanaged dll is different between console app, asp.net app with iis express, and asp .net app on real iis [Resolved] this behavior was actually caused by the 64 bit version of the program (the dll is not compatible with 64 bit). When the program is running in 32 bit everything is fine (in all platform).
I actually integrate a piece of code on my app in order to read an chip card connected on the usb port.
The code was furnished by french social security (the dll and the .net wrapper of the unmanaged code) so i don't have documentation, neither support on this. the dll was built on the top of PKCS #11
I made the development on a console app and it works well.
Nom i integrate this on my asp.net webapp .net framework 4.0 (yes the chip card will be connected on the usb of the server) and the problems begin.

*

*with iisexpress, same behavior than the console app, it works well

*on real iis, i don't have exception but the code act like there is no chip card. No exception, just it don't detect the card.

*still on real iis, i changed the type of application pool to Local Service. With this, the chip card is now detected, but i have a bug somewhere in the code (really obscure code, i don't write it. In some line of code it expect receive an object which is null and it finished on null reference exception).

I don't know what to do now. so guys if you have some ideas which can help me to understand this behavior  and make it work on real iis, I take it. Now i don't have any other solutions.
Thanks for your help !

A: [Resolved] this behavior was actually caused by the 64 bit version of the program (the dll is not compatible with 64 bit). When the program is running in 32 bit everything is fine (in all platform)


text:
Q: using cURL to send XML POST request to PDBe I am trying to use cURL to send an XML POST request to a server hosting crystallographic data. I think I am going by the book, see below for the command I am using:
curl -X POST --data-urlencode '<!DOCTYPE query SYSTEM "http://www.ebi.ac.uk/pdbe-site/pdbemotif/query.dtd"><query><declaration><pfam name="p">PF00451</pfam></declaration></query>' http://www.ebi.ac.uk/pdbe-site/pdbemotif/hitlist.xml
I used --trace-ascii to see the data sent to the server, it is the url-encoded version of my XML query specified above. The query is valid when entered as text into the submission form hosted on the server http://www.ebi.ac.uk/pdbe-site/pdbemotif/xmlqueryprint.jsp , but it returns an error when submitted with cURL.
Would anyone be aware of additional formatting that might be required by the server?
Thanks for your time!


text:
Q: Removing Class Path and Module Path from an Eclipse Project I am trying to import some files into a java project that I created in eclipse. Other students in my class have indicated that when they go into their project properties, they do not have "classpath" and "modulepath", allowing them to add the files that they need directly into their project, both as direct files or as JAR files.
Whenever I make a Java Project, I always have these two options appear in my properties. While this may be fine, whenever I try to import the necessary folders into either path, I get errors. For example, I am trying to import files that will allow me to play .wav files in my program. But whenever the program runs, and an event would trigger the sound to play, I receive errors saying that the file I am referencing was not found.
How can I set up my project so that I do not have "classpath" or "modulepath" as options in my project properties? I think this is the root of my issue.


text:
Q: Ignore AndroidX and Want to use android support libraries alone in Android Studio 3.2 In my project I used Android support libraries previously. After upgrading to the Android Studio 3.2 AS loads AndroidX and some other support libraries(e.g. com.android.support:support-compat:28.0.0) by default. This gives me lot of manifest merger failed error. I tried enabling jetifier but actually I don't want to use AndroidX. I just wanted to use support libraries 28.0.0 only. So my question is how can I ignore that AndroidX packages which is loaded by default. So that I can use support libraries.

A: *

*Go to "REFACTOR" and then

*Click on "Migrate to AndroidX"

*It will ask to make a backup of your current project , so check the CheckBox then click
on Migrate.

*It will create a ".Zip" file of your project.

*It will ask again to change all the implementations to AndroidX , click Okay and.

*All your implementations will be migrated to AndroidX.

*At last you need to change your <....> angular bracket lines related to Androidx.

*If you are migrating your exixting project you need to change this mandatory or if you
are creating a new project than it will do it by its own.

*Example "android.support.v7.widget.CardView" to "androidx.cardview.widget.CardView"


text:
Q: SQL Server Updating with subquery or CTE, needs to be race condition safe I have two approaches for updating a status field in a batch of items at a time. One that uses a WHERE IN and other that uses a CTE. I like the CTE approach more, but if I had 2 processes calling this stored procedure at the same time would the first one be better or the bottom CTE. We are concerned with possible race conditions. If the CTE will not have race condition then I would like to use that. When I define the CTE is that processed at that point or is it done as an atomic action in the UPDATE?
The one with the WHERE IN:
CREATE TABLE #RowsIWant (PriceValueId BIGINT)

UPDATE PV
SET SyncRAGStatus = 'A',
    AuditUser = pv.AuditUser
OUTPUT Inserted.Id INTO #RowsIWant
FROM PriceValues AS PV
WHERE PV.Id IN (
    SELECT TOP (@batchSize) PV.Id
    FROM Prices AS P
    INNER JOIN PriceValues AS PV ON PV.PriceId = P.Id
    WHERE P.PriceListId = @priceListId
    AND PV.SyncRAGStatus = 'R'
    ORDER BY PV.UpdateInsertStatus DESC
)

The CTE one:
;WITH TopNRowsINeed AS
(
    SELECT TOP (@batchSize) PV.Id AS PriceValueId, PV.SyncRAGStatus, PV.AuditUser
    FROM Prices AS P
    INNER JOIN PriceValues  AS PV ON PV.PriceId = P.Id
    WHERE P.PriceListId = @priceListId
      AND PV.SyncRAGStatus = 'R'
    ORDER BY PV.UpdateInsertStatus DESC
)
UPDATE TopNRowsINeed
SET SyncRAGStatus = 'A'
OUTPUT Inserted.PriceValueId INTO #RowsIWant

A: Based on what Stu and Charlieface mentioned in the comments, I went for the CTE:
;WITH TopNRowsINeed AS (
    SELECT TOP (@batchSize) PV.Id AS PriceValueId, PV.SyncRAGStatus, PV.AuditUser
    FROM Prices AS P
    INNER JOIN PriceValues  AS PV ON PV.PriceId = P.Id
    WHERE P.PriceListId = @priceListId
    AND PV.SyncRAGStatus = 'R'
    ORDER BY PV.UpdateInsertStatus DESC
)

UPDATE TopNRowsINeed
SET SyncRAGStatus = 'A'
OUTPUT Inserted.PriceValueId INTO #RowsIWant

A: WITH TopNRowsINeed
AS
(
    SELECT TOP (@batchSize) PV.Id, PV.SyncRAGStatus
    FROM PriceValues PV WITH (UPDLOCK, SERIALIZABLE)
    WHERE PV.SyncRAGStatus = 'R'
    AND EXISTS
        (
            SELECT 1
            FROM Prices P
            WHERE P.Id = PV.PriceId
        )
    ORDER BY PV.UpdateInsertStatus DESC
)
UPDATE TopNRowsINeed
SET SyncRAGStatus = 'A'
OUTPUT Inserted.Id
INTO #RowsIWant;


text:
Q: How to get names of Whatsapp Contact on an Android My code is here I want to get contact name.How to get whatsapp contact name.
String adress = intent.getStringExtra("contact");
                String phone = adress.split("@")[0];
                String[] projection = new String[] {ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,
                        ContactsContract.CommonDataKinds.Phone.NUMBER,
                        ContactsContract.CommonDataKinds.Phone.NORMALIZED_NUMBER };
                ContentResolver cr=getContentResolver();
                String selection = ContactsContract.CommonDataKinds.Phone.NORMALIZED_NUMBER + " = " + phone;
                Cursor c = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, projection, selection, null, null);
                int contactnameColumn=c.getColumnIndex(ContactsContract.RawContacts.DISPLAY_NAME_PRIMARY);
                if (c != null && c.moveToFirst()) {
                    Log.e(TAG, "name: "+ c.getString(0));
                    Toast.makeText(getApplicationContext(),"name:"+c.getString(0),Toast.LENGTH_SHORT).show()


text:
Q: ASP.NET MVC CSVFile Parsing, How to handle Line Breaks using StreamReader and ReadLine method? I have ASP.NET MVC application where I am selecting CSV File and parsing that file.
While Parsing, if a particular Cell is having Line Breaks, then it is treating as next record from the Line Break. As is this Attached image , in the first row, for StreetName column, it is treating as one Row upo Terminal, And "Chalwell" as another Row.
How to handle LineBreaks in C# here?
My code is like this: Here ReadLine() method is used. Can we use any other method to consider whole cell as value and ignore LineBreaks?
public static List<T> ConvertCsvToDataTable<T>(StreamReader csvReader, ref Dictionary<int, List<string>> failures) where T : new()
        {
            var objects = new List<T>();
            var columnIndex = new Dictionary<string, int>();

            var headerLine = csvReader.ReadLine();
            var headers = headerLine.Split(Convert.ToChar(","));
            for (var i = 0; i < headers.Length; i++)
            {
                columnIndex.Add(headers[i], i);
            }

            var lineNumber = 1;
            while (!csvReader.EndOfStream)
            {
                var line = csvReader.ReadLine();

                if (line != null)
                {
                    var obj = new T();
                    var csvRow = Regex.Split(line, ",(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)");

                    var lineFailures = AssignValuesFromCsv(obj, csvRow, columnIndex);
                    if (lineFailures.Count > 0) failures.Add(lineNumber, lineFailures);

                    objects.Add(obj);
                }
                ++lineNumber;
            }
            return objects;
        }

Thanks
Sai


text:
Q: How many "words" of any length can be made from the letters in TREATS? So, I feel as if I nearly understand this problem. It's not asking for actual words in the English language, just combinations of the letters. If not for the fact that this question says "of any length", thus adding in combinations of 6 letters or less, I would just say 6! but I don't think that's correct. Any help?

A: Note that while you say "combination", I'm going to assume that that's not what you mean; a combination implies that there is no order, i.e. "TAR" is the same as "ART". What you want is a permutation, rather, a sum of all possible permutations of any length (possibly including $\emptyset$ though I doubt the question would really accept that as a word, and not just blank space). However, there are two Ts in "TREATS" and presumably they are not distinct. We'll need to take on the cases where there are two Ts and less than two Ts separately.
If there are less than 2 Ts, we can just treat is as a permutation of "TREAS" (or "TEARS", if you like), which is just every k-permutation of that word for $k$ from $0$ to $5$, (though, again, you should probably ask yourself whether silence is a word).
Hence, $\sum_{i=0}^{5} (5)_i$.
If there are 2 Ts, then we can think of putting 2 indistinct Ts in some place in the word, one to the left of the other, and find all of the ways to put the other letters down between them. First, we need to iterate over all possible numbers of letters we put between the Ts, meaning from $0$ to $4$. We'll also need to order them, so each term in the sum will have a falling factorial in it. Finally, figuring out where to put the other letters is like an integer composition; we have $x$ non-T letters and two dividers (the Ts), so we want to find out how many ways we can pick the two dividers out of a string of x+2 elements, resulting in $\binom{x+2}{2}$.
Hence, $\sum_{i=0}^4 (4)_i \binom{x+2}{2}$.
By rule of sums, $\sum_{i=0}^4 (4)_i \binom{i+2}{2} +\sum_{j=0}^{5} (5)_j$.
EDIT: For a word of six distinct letters, it is $\sum_{i=0}^6 (6)_i$.

A: We have the 4 letters "REAS" and the two Ts. From the four letters you can form $\Sigma_{n=0}^4 \Sigma_{k=0}^n {n \choose k}$ words (with inner sum representing an $n$ letter word). Each of the $n$-letter words can be complemented by either 0, 1 or 2 Ts. For 0 Ts  you have 1 position, for 1 T there are $n+1$ positions and for 2 Ts there are 5+1 over 2 positions (but with double counts so these must be divided by two). Yielding:
$\sum_{n=0}^4 \sum_{k=0}^n {n \choose k} \;[{n+1 \choose 0}+{n+1 \choose 1} + \frac{{n+1 \choose 2}}{2}] \; = \; 271$.

A: It is
$5+\binom25*2!+\binom35*3!+\binom45*4!+5!$ //Words without repetition of T's
+
$1+\binom14*\frac{3!}{2}+\binom24*\frac{4!}{2}+\binom34*\frac{5!}{2}+\binom44*\frac{6!}{2}$ //Words with repetition of 2 T's


text:
Q: NoClassDefFoundError raised by Spark when master is setted to yarn-client I have a simple spark (1.4.1 version) application written in Scala that consume data from a kinesis stream. If i run the application, using the spark-submit command, with the value for the master setted to local[*] everything works fine. If i choose to use as master yarn-client i have the following exception:
15/11/24 14:22:09 ERROR ReceiverTracker: Deregistered receiver for stream 1: Error starting receiver 1 - java.lang.NoClassDefFoundError: org/joda/time/format/DateTimeFormat
    at com.amazonaws.auth.AWS4Signer.<clinit>(AWS4Signer.java:44)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:422)
    at java.lang.Class.newInstance(Class.java:442)
    at com.amazonaws.auth.SignerFactory.createSigner(SignerFactory.java:119)
    at com.amazonaws.auth.SignerFactory.lookupAndCreateSigner(SignerFactory.java:105)
    at com.amazonaws.auth.SignerFactory.getSigner(SignerFactory.java:78)
    at com.amazonaws.AmazonWebServiceClient.computeSignerByServiceRegion(AmazonWebServiceClient.java:307)
    at com.amazonaws.AmazonWebServiceClient.computeSignerByURI(AmazonWebServiceClient.java:280)
    at com.amazonaws.AmazonWebServiceClient.setEndpoint(AmazonWebServiceClient.java:160)
    at com.amazonaws.services.kinesis.AmazonKinesisClient.setEndpoint(AmazonKinesisClient.java:2102)
    at com.amazonaws.services.kinesis.AmazonKinesisClient.init(AmazonKinesisClient.java:216)
    at com.amazonaws.services.kinesis.AmazonKinesisClient.<init>(AmazonKinesisClient.java:202)
    at com.amazonaws.services.kinesis.AmazonKinesisClient.<init>(AmazonKinesisClient.java:175)
    at com.amazonaws.services.kinesis.clientlibrary.lib.worker.Worker.<init>(Worker.java:106)
    at com.amazonaws.services.kinesis.clientlibrary.lib.worker.Worker.<init>(Worker.java:92)
    at org.apache.spark.streaming.kinesis.KinesisReceiver.onStart(KinesisReceiver.scala:133)
    at org.apache.spark.streaming.receiver.ReceiverSupervisor.startReceiver(ReceiverSupervisor.scala:125)
    at org.apache.spark.streaming.receiver.ReceiverSupervisor.start(ReceiverSupervisor.scala:109)
    at org.apache.spark.streaming.scheduler.ReceiverTracker$ReceiverLauncher$$anonfun$8.apply(ReceiverTracker.scala:308)
    at org.apache.spark.streaming.scheduler.ReceiverTracker$ReceiverLauncher$$anonfun$8.apply(ReceiverTracker.scala:300)
    at org.apache.spark.SparkContext$$anonfun$runJob$5.apply(SparkContext.scala:1767)
    at org.apache.spark.SparkContext$$anonfun$runJob$5.apply(SparkContext.scala:1767)
    at org.apache.spark.scheduler.ResultTask.runTask(ResultTask.scala:63)
    at org.apache.spark.scheduler.Task.run(Task.scala:70)
    at org.apache.spark.executor.Executor$TaskRunner.run(Executor.scala:213)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.ClassNotFoundException: org.joda.time.format.DateTimeFormat
    at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
    ... 31 more

Obviously i have created a fat jar using the assembly plugin for sbt that include the spark-streaming-kinesis-asl_2.10 library that has joda-time-2.9.1.jar as dependency. I've listed the file contained in my fat jar and the class is present. To be sure of its presence i've also tryed to use DateTimeFormat from the main class and i hadn't any problem.
I hope that someone could help me to solve this problem.
Thanks.

A: I suggest to check the classpath entries from the spark "Application Detail UI" => "Environment" tab and check if you see any joda-time entires there.


text:
Q: I try to clean/reset/clear a list in C# but it gives me InvalidOperationException error This is a part of an static int method:
int answer = 0;
foreach(int getal in savedNumbers)
{
    Console.WriteLine(getal);
    answer = answer + getal;
    savedNumbers.Clear(); // after this line, I'm getting an error.
}
return answer;

Please help me ... I don't know why savedNumbers.Clear() isn't working at that line.
EDIT: Thanks, problem is solved.

A: You can't modify the collection while enumerating over it. So, the exception is valid. Clear once you are done with enumerating it.

A: You can't modify a list while iterating that same list.

A: You are clearing the list in the middle of enumerating it.  You cannot modify the list when you are in the process of enumeration.
int answer = 0;
foreach(int getal in savedNumbers)
{
    Console.WriteLine(getal);
    answer = answer + getal;
}
savedNumbers.Clear();
return answer;

A: While iterating you cannot change the list/collection, while you can do the same using loop as stated below:
for (int i = 0 i < savedNumbers.Count; i++)
{
    var getal = savedNumbers[i];
    Console.WriteLine(getal);
    answer = answer + getal;
    savedNumbers.Clear();
}

You can't modify a collection while enumerating over it.  That rule exists even without threading issues considered.  From MSDN:

An enumerator remains valid as long as the collection remains unchanged. If changes are made to the collection, such as adding, modifying, or deleting elements, the enumerator is irrecoverably invalidated and its behavior is undefined.

References:

*

*Modifying .NET Dictionary while Enumerating through it

*Why does enumerating through a collection throw an exception but looping through its items does not

A: Msdn says: The foreach statement is used to iterate through the collection to get the desired information, but should not be used to change the contents of the collection to avoid unpredictable side effects


text:
Q: How do I prevent logging an encrypted airflow variable? I've set up an airflow which has an encrypted variable declared. I'm using BigQueryOperator. I use the encrypted variable in the SQL that is fed to the class. But the airflow logs the SQL after decrypting the variable. How can I prevent that from happening?

A: Unfortunately, there is no built-in way to achieve this.
A possible work-around is removing self.log.info('Executing: %s', self.sql) line in BigQueryOperator or creating a new Operator inheriting BigQueryOperator like below:
class CustomBQOperator(BigQueryOperator):
    @apply_defaults
    def __init__(self, *args, **kwargs):
        super(CustomBQOperator).__init__(*args, **kwargs)

    def execute(self, context):
        if self.bq_cursor is None:

            hook = BigQueryHook(
                bigquery_conn_id=self.bigquery_conn_id,
                use_legacy_sql=self.use_legacy_sql,
                delegate_to=self.delegate_to)
            conn = hook.get_conn()
            self.bq_cursor = conn.cursor()
        self.bq_cursor.run_query(
            self.sql,
            destination_dataset_table=self.destination_dataset_table,
            write_disposition=self.write_disposition,
            allow_large_results=self.allow_large_results,
            flatten_results=self.flatten_results,
            udf_config=self.udf_config,
            maximum_billing_tier=self.maximum_billing_tier,
            maximum_bytes_billed=self.maximum_bytes_billed,
            create_disposition=self.create_disposition,
            query_params=self.query_params,
            labels=self.labels,
            schema_update_options=self.schema_update_options,
            priority=self.priority,
            time_partitioning=self.time_partitioning,
            api_resource_configs=self.api_resource_configs,
            cluster_fields=self.cluster_fields,
        )

And then using this CustomBQOperator instead of BigQueryOperator


text:
Q: A first example from Brad Green's book "AngularJS" has a mistake It seems to be so simple but doesn't work:

{{greeting.text}}, World

have on the screen:
{{greeting.text}}, World

and in a console:
    Error: [ng:areq] Argument 'HelloController' is not a function, got undefined
http://errors.angularjs.org/1.3.0/ng/areq?p0=HelloController&p1=not%20a%20function%2C%20got%20undefined
    at http://localhost:8080/lib/angular.js:80:12
    at assertArg (http://localhost:8080/lib/angular.js:1610:11)
    at assertArgFn (http://localhost:8080/lib/angular.js:1620:3)
    at http://localhost:8080/lib/angular.js:8319:9
    at http://localhost:8080/lib/angular.js:7496:34
    at forEach (http://localhost:8080/lib/angular.js:343:20)
    at nodeLinkFn (http://localhost:8080/lib/angular.js:7483:11)
    at compositeLinkFn (http://localhost:8080/lib/angular.js:6991:13)
    at compositeLinkFn (http://localhost:8080/lib/angular.js:6994:13)
    at compositeLinkFn (http://localhost:8080/lib/angular.js:6994:13)

Cannot see why... except maybe because I use AngularJS v1.3.0?

A: Yes, it is because of 1.3.0. The change log describes the breaking change as:

$controller will no longer look for controllers on window. The old behavior of looking on window for controllers was originally intended for use in examples, demos, and toy apps. We found that allowing global controller functions encouraged poor practices, so we resolved to disable this behavior by default.

The change log goes on to explain that you can re-enable the "global" function approach with:

Although it's not recommended, you can re-enable the old behavior like this:

angular.module('myModule').config(['$controllerProvider', function($controllerProvider) {
  // this option might be handy for migrating old apps, but please don't use it
  // in new ones!
  $controllerProvider.allowGlobals();
}]);

A: Yes, it is an issue with AngularJS 1.3.0. Another way to circumvent it (maybe simpler and safer) is by explicitly including an older version of AngularJS. For example:

A: in Angular 1.4 this is working solution:
index.html
<!DOCTYPE html>

    <title></title>

      <input ng-model='greeting.text'>

{{greeting.text}}, World

controllers.js
var testApp = angular.module('testApp', []);

testApp.controller('HelloController', function ($scope) {
  $scope.greeting = { text: 'Hello' };
});


text:
Q: Perform the same operation to all the variables but first variable passed in a Perl function I am using a Perl function to dump a CSV file, where I pass certain values, and indie this function, I want to perform same operation for these passed variables except for the first variable, which is the file handle.
What I want to do is to check whether a passed argument (string) has commas in it, if so, make enclose them in quotation mark (") s.
But I need to assign these values to variable names, as I have to use them later for different purposes.
Following is my subroutine:
sub printCSVRowData
{
    my $CSVFileHandle = shift;

    foreach my $str (@_) {
        if ($str eq "" or not defined $str or $str =~ /^ *$/) {
            $str = "NA";
        }
        $str =~ s/\"//g;
    }

    my $firstCol = shift;
    my $secondCol = shift;
    my $thirdCol = shift;

    # Do some modifications

    print $CSVFileHandle "$firstCol, $secondCol, $thirdCol";
}

Now the issue is when I values to this subroutine, I get the following error message:

Modification of a read-only value attempted at  line  (where $str =~ s/\"//g; is called).

Can anyone help me on this ? What am I doing wrong here ? Is there any other way around for this ?

A: You are modifying @_, whose elements are the scalars passed as arguments. For this reason, modifying the elements of @_ isn't safe. That's why we copy the elements of @_ and the modify copies instead.
sub printCSVRowData {
    my ($csv, $fh, @fields) = @_;
    @fields = map { defined($_) && /\S/ ? $_ : "NA" } @fields;
    $csv->say($fh, \@fields);
}

You should be using Text::CSV_XS or similar.
my $csv = Text::CSV_XS->new({
    auto_diag => 2,
    binary    => 1,
});


text:
Q: UTC Timestamp Conversion to Datetime Returns Unexpected Dates I have a list of dictionary objects in Python, a sample of which looks like this
data = [{'utcDay': 15846, 'count': 956}, {'utcDay': 15847, 'count': 1408}, {'utcDay': 15848, 'count': 1664}, {'utcDay': 15849, 'count': 1858}, {'utcDay': 15850, 'count': 1972}, {'utcDay': 15851, 'count': 2071}, {'utcDay': 15852, 'count': 2179}, {'utcDay': 15853, 'count': 2281}, {'utcDay': 15854, 'count': 2389}, {'utcDay': 15855, 'count': 2457}, {'utcDay': 15856, 'count': 2503}, {'utcDay': 15857, 'count': 2537}, {'utcDay': 15858, 'count': 2611}, {'utcDay': 15859, 'count': 2668}, {'utcDay': 15860, 'count': 2711}, {'utcDay': 15861, 'count': 2764}, {'utcDay': 15862, 'count': 2857}, {'utcDay': 15863, 'count': 2950}, {'utcDay': 15864, 'count': 2998}]

I would like to convert the contents of all of the "utcDay" keys to a Datetime object.
When I execute the following two utc timestamp conversions
for x in data:
    print(datetime.fromtimestamp(x["utcDay"]))

for x in data:
   print(time.ctime(x["utcDay"]))

I get the same output which is
1970-01-01 15:24:06
1970-01-01 15:24:07
1970-01-01 15:24:08
1970-01-01 15:24:09
1970-01-01 15:24:10
1970-01-01 15:24:11
1970-01-01 15:24:12
1970-01-01 15:24:13
1970-01-01 15:24:14
1970-01-01 15:24:15
1970-01-01 15:24:16
1970-01-01 15:24:17
1970-01-01 15:24:18
1970-01-01 15:24:19
1970-01-01 15:24:20
1970-01-01 15:24:21
1970-01-01 15:24:22
1970-01-01 15:24:23
1970-01-01 15:24:24
1970-01-01 15:24:25
...

I'm unclear as to why every timestamp is coming out as being from the 1970s since the original data, which is plotted on the source website, ranges from c.May 2013 to today.
Even when I multiply these timestamps by units of 1,000 / 10,000 / 100,000 / 1,000,000 I do not get the expected results. For example, this is the output I get from multiplying by 1,000
1970-07-03 19:40:00
1970-07-03 19:56:40
1970-07-03 20:13:20
1970-07-03 20:30:00
1970-07-03 20:46:40
1970-07-03 21:03:20
1970-07-03 21:20:00
1970-07-03 21:36:40
1970-07-03 21:53:20
1970-07-03 22:10:00
1970-07-03 22:26:40
1970-07-03 22:43:20
1970-07-03 23:00:00
1970-07-03 23:16:40
1970-07-03 23:33:20
1970-07-03 23:50:00
1970-07-04 00:06:40
1970-07-04 00:23:20
1970-07-04 00:40:00
1970-07-04 00:56:40
1970-07-04 01:13:20
...

Thanks for looking at my question.


text:
Q: Cant install sonata admin with symfony 5 $ composer require sonata-project/admin-bundle
Using version ^3.87 for sonata-project/admin-bundle
./composer.json has been updated
Running composer update sonata-project/admin-bundle
Loading composer repositories with package information
Restricting packages listed in "symfony/symfony" to "5.2.*"
Updating dependencies
Your requirements could not be resolved to an installable set of packages.
Problem 1
- sonata-project/admin-bundle[3.87.0, ..., 3.x-dev] require symfony/console ^4.4 -> found symfony/console[v4.4.0-BETA1, ..., 4.4.x-dev] but it conflicts with your root composer.json require (5.2.*).
- Root composer.json requires sonata-project/admin-bundle ^3.87 -> satisfiable by sonata-project/admin-bundle[3.87.0, 3.x-dev].
Use the option --with-all-dependencies (-W) to allow upgrades, downgrades and removals for packages currently locked to specific versions.
Installation failed, reverting ./composer.json and ./composer.lock to their original content.

A: My suggestion is to use EasyAdmin bundle which is compatible with Symfony 5.3. It has only one bug which is related to viewing images thumbnail in easyadmin panel. For now the only solution is to use TextareaField instead of ImageField in DasboardCrudController.

A: According to an issue from their tracker and packagist.org, the most recent version of that package (which is 3.87.0) is not fully compatible with Symfony 5. You either need to wait until this is resolved, or downgrade Symfony in your application to v4.4


text:
Q: Start Internet Explorer, wait until the user closes it, then exit the script I have a script that opened IE with no toolbar and to navigate to a url (below)
Dim IE, URL
URL = "website.com"
Set IE = CreateObject("InternetExplorer.Application")
  IE.Navigate URL
  IE.Visible = 1
  IE.ToolBar = 0
  IE.Left = 0

I need to have the window appear like this for reasons,
I cant use kiosk mode.
What I need to do is:

*

*run the script (LaunchIE_noToolbar.vbs)

*open IE, hide toolbar, go to url

*wait in the background while the user does stuff which might be 10-15 minutes later

*recognize it's closed and exit the script

It seems simple enough, but I can't work it out, the waiting part is driving me nuts.
If you can do this in PowerShell that would be great too, I don't mind.

A: I'm not in front of a computer right now, but as I recall...
You can start a process aka start-process I think. Grab the process ID which is returned. Then wait for the process to complete, might be wait-process?  Do a "help process" at the PowerShell prompt for commands and syntax.

A: There may be a more elegant PowerShell solution, but this seems to work:
$url = "website.com"
$ie = New-Object -ComObject "InternetExplorer.Application"
$ie.Navigate($url)
$ie.Visible = 1
$ie.ToolBar = 0
$ie.Left = 0

# Wait for IE to exit.
while ($null -ne $ie.ReadyState) { # .ReadyState is only $null once the IE instance exits
  Start-Sleep -Milliseconds 100
}