text:
Q: Fedex WSDL C# - Setting the Invoice # value I'm using Fedex's WSDL in C# to generate COD shipping labels.  On Fedex shipping labels there is an "Invoice #" string on both the shipping label and the COD return label.  I want to set my orderid in the request to Fedex such that my orderid shows up as the Invoice #.
It's not obvious to me how to set the Invoice # in Fedex's wsdl request.  Has anybody done this?

A: The way in which you place the order id or invoice number in the labels is following:

*

*Set the invoice number in the package customer reference.

*Specify on the COD details node (on the reference indicator) that you want the COD label to include the invoice number as one of its reference.

Please, note that you can also include other references than invoice number (e.g.: PO, customer reference, and tracking).
Here is a sample SOAP envelope for the request depicting what I said before:
<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    <soap:Body>
        <ProcessShipmentRequest xmlns="http://fedex.com/ws/ship/v12">
            <WebAuthenticationDetail>
                <CspCredential>
                    <Key>CSP_KEY(IF YOU ARE ONE)</Key>
                    <Password>CIS_PASSWORD(IF YOU ARE ONE)</Password>
                </CspCredential>
                <UserCredential>
                    <Key>CSP_USER_KEY(IF YOU BELONG TO THE CSP)</Key>
                    <Password>CSP_PASSWORD(IF YOU BELONG TO THE CSP)</Password>
                </UserCredential>
            </WebAuthenticationDetail>
            <ClientDetail>
                <AccountNumber>ACCOUNT_NUMBER</AccountNumber>
                <MeterNumber>METER_NUMBER</MeterNumber>
                <ClientProductId>CLIENT_PRODUCT_ID(IF ONE IS PROVIDED)</ClientProductId>
                <ClientProductVersion>CLIENT_VERSION(IF ONE IS PROVIDED)</ClientProductVersion>
            </ClientDetail>
            <TransactionDetail>
                <CustomerTransactionId>261</CustomerTransactionId>
            </TransactionDetail>
            <Version>
                <ServiceId>ship</ServiceId>
                <Major>12</Major>
                <Intermediate>0</Intermediate>
                <Minor>0</Minor>
            </Version>
            <RequestedShipment>
                <ShipTimestamp>2013-08-21T14:00:00-04:00</ShipTimestamp>
                <DropoffType>REGULAR_PICKUP</DropoffType>
                <ServiceType>PRIORITY_OVERNIGHT</ServiceType>
                <PackagingType>YOUR_PACKAGING</PackagingType>
                <Shipper>
                    <AccountNumber>ACCOUNT_NUMBER</AccountNumber>
                    <Contact>
                        <PersonName>323199 323199</PersonName>
                        <CompanyName>CSP Testing</CompanyName>
                        <PhoneNumber>9012633035</PhoneNumber>
                        <EMailAddress>csp@fedex.com</EMailAddress>
                    </Contact>
                    <Address>
                        <StreetLines>99 Fedex parkway</StreetLines>
                        <City>ALAMEDA</City>
                        <StateOrProvinceCode>CA</StateOrProvinceCode>
                        <PostalCode>94501</PostalCode>
                        <CountryCode>US</CountryCode>
                    </Address>
                </Shipper>
                <Recipient>
                    <Contact>
                        <PersonName>323257 323257</PersonName>
                        <CompanyName>CSP Testing</CompanyName>
                        <PhoneNumber>9012633035</PhoneNumber>
                        <EMailAddress>csp@fedex.com</EMailAddress>
                    </Contact>
                    <Address>
                        <StreetLines>124 Fedex parkway</StreetLines>
                        <City>PADUCAH</City>
                        <StateOrProvinceCode>KY</StateOrProvinceCode>
                        <PostalCode>42001</PostalCode>
                        <CountryCode>US</CountryCode>
                    </Address>
                </Recipient>
                <Origin>
                    <Contact>
                        <PersonName>323199 323199</PersonName>
                        <CompanyName>CSP Testing</CompanyName>
                        <PhoneNumber>9012633035</PhoneNumber>
                        <EMailAddress>csp@fedex.com</EMailAddress>
                    </Contact>
                    <Address>
                        <StreetLines>99 Fedex parkway</StreetLines>
                        <City>ALAMEDA</City>
                        <StateOrProvinceCode>CA</StateOrProvinceCode>
                        <PostalCode>94501</PostalCode>
                        <CountryCode>US</CountryCode>
                    </Address>
                </Origin>
                <ShippingChargesPayment>
                    <PaymentType>SENDER</PaymentType>
                    <Payor>
                        <ResponsibleParty>
                            <AccountNumber>ACCOUNT_NUMBER</AccountNumber>
                            <Contact>
                                <PersonName>CSP Testing</PersonName>
                                <CompanyName>RTC Testing</CompanyName>
                            </Contact>
                            <Address>
                                <CountryCode>US</CountryCode>
                            </Address>
                        </ResponsibleParty>
                    </Payor>
                </ShippingChargesPayment>
                <SpecialServicesRequested>
                    <SpecialServiceTypes>COD</SpecialServiceTypes>
                    <CodDetail>
                        <CodCollectionAmount>
                            <Currency>USD</Currency>
                            <Amount>50</Amount>
                        </CodCollectionAmount>
                        <CollectionType>ANY</CollectionType>
                        <ReferenceIndicator>INVOICE</ReferenceIndicator>
                    </CodDetail>
                </SpecialServicesRequested>
                <CustomsClearanceDetail>
                    <DocumentContent>NON_DOCUMENTS</DocumentContent>
                </CustomsClearanceDetail>
                <LabelSpecification>
                    <LabelFormatType>COMMON2D</LabelFormatType>
                    <ImageType>PNG</ImageType>
                    <LabelStockType>PAPER_4X6</LabelStockType>
                </LabelSpecification>
                <RateRequestTypes>ACCOUNTACCOUNT</RateRequestTypes>
                <PackageCount>1</PackageCount>
                <RequestedPackageLineItems>
                    <SequenceNumber>1</SequenceNumber>
                    <GroupPackageCount>1</GroupPackageCount>
                    <InsuredValue>
                        <Currency>USD</Currency>
                        <Amount>5000</Amount>
                    </InsuredValue>
                    <Weight>
                        <Units>LB</Units>
                        <Value>20</Value>
                    </Weight>
                    <PhysicalPackaging>OTHER</PhysicalPackaging>
                    <ItemDescription>MacBook Pro</ItemDescription>
                    <CustomerReferences>
                        <CustomerReferenceType>INVOICE_NUMBER</CustomerReferenceType>
                        <Value>INVOICE12345</Value>
                    </CustomerReferences>
                    <SpecialServicesRequested>
                        <SpecialServiceTypes>SIGNATURE_OPTION</SpecialServiceTypes>
                        <SignatureOptionDetail>
                            <OptionType>SERVICE_DEFAULT</OptionType>
                        </SignatureOptionDetail>
                    </SpecialServicesRequested>
                </RequestedPackageLineItems>
            </RequestedShipment>
        </ProcessShipmentRequest>
    </soap:Body>
</soap:Envelope>

This is the generated shipping label:

This is the generated COD label:

I hope my reply is of help to you.
Best!


text:
Q: Styled media receiver source (Chromecast) Currently, I am working on a chromecast integration of my app.
Currently, you are given 3 options for your cast receiver application

*

*Styled Media Receiver

*Default media receiver

*Custom media receiver

I really like the styling of the styled media receiver, as it is very easy to style your receiver this way. However, sometimes I would be really like to extend the functionality of that receiver. Like a volume indicator, for example.
Is there a way I can obtain the source code of the styled media receiver? I checked the Github of google-cast but couldn't find it. Has anyone tried this?

A: Currently, source for the first two options that you had listed are not publicly available

redpajama_set_name: RedPajamaStackExchange


text:
Q: Matching Two Lists Against Eachother I have two Lists, List 1 and List 2. Both Lists have two columns, column A and column B, the values in column A(ID) & B(value) correspond with each other. I need to compare these two lists with each-other and find mismatches when they occur.
What I want to do is create a third column, Column C, to say if there is a match or mismatch between these two list, basically stating if the ID in one list has a different value in the other list, example:
A match would be: List 1: column A=tom, column B=5. List 2: column A=tom, column B=5.
A mismatch would be: List 1: column A=tom, column B=5. List 2: column A=tom, column B=2.
The problem is, List 2 has duplicates of column A that contain different corresponding values(column B). My rules would be: if there is ONE match between the two lists(even if a mismatch occurs later in the list) Label it as "MATCH", but if there is no matches for any of the ID's(column A) then label it as "MISMATCH".
Here is the formula I am using, it takes the original ID(column A) from LIST 1 and tries to find a match or mismatch from List 1 and List 2:
=IF(VLOOKUP(A1,A:B,2,FALSE)=VLOOKUP(A1,C:D,2,FALSE),"MATCH","MISMATCH")
I cant simply remove duplicates because they aren't just duplicates, it is a single ID(column A) with multiple values(Column B) in one list, but the formula I am using now will not account for my rule I want to implement and I don't really know where to start or how to make a formula that will understand that if an ID(Column A) contains one Match, even if there are other mismatches, to label it as a MATCH. The second problem I have is reporting it in a way were I can have the ID(Column A) and have its state(Match or Mismatch) in one single column without the duplicates, I guess this is tied to the original problem.
Sorry for the long explanation, but I appreciate any help in advance.
Sample Data:
List1:
ColumnA | ColumnB
tom | 1
Jon | 2
fred | 3
brad | 4
List 2:
Column A | Column B
tom | 1
Jon | 5
Jon | 1
fred | 1
fred | 2
fred | 3
brad | 2
(Desired Result)List 3:
ColumnA | ColumnB
tom | MATCH  *because tom has the same values in column B for both lists
Jon | MISMATCH *because jon has different values in column B for both lists for all of the times his ID shows up
fred | MATCH *because he has at least ONE match for Columns B in both lists even though   there are some mismatches, this is where the rule would come into place
brad | MISMATCH *because his value in column B in both lists do not match
Example Screen Shot:
Screen shot of example data

A: You could count how many times the match is found with the COUNTIF() function.  Then, wrap an IF statement around it to say whenever the count is greater than > 0, it is a Match, otherwise Mismatch.  See screenshot below:
Here's the formula I have in cell D4 below: =IF(COUNTIF(H4:H10,B4&C4)>0,"Yes","No")
Here's the formula I have in cell H4 below: =F4&G4
Hope this helps!

A: The way to look at this is that it's a match to a list based on two criteria. An easy way to match on multiple criteria is to join (concatenate) the individual criteria values together, and then do the same for the list that you're searching through. The following array formula will do this:
=IFERROR(IF(MATCH(A1&B1,$D$1:$D$7&$E$1:$E$7,0),"MATCH"),"MISMATCH")
NB - my columns A and B contain your List 1, my columns D and E are your List 2.
Enter this formula in C1 and press Ctrl + Shift + Enter (this turns the formula into an array formula), and then drag it down to cell C4.


text:
Q: Ansible Regexp groups, patterns or something else? I have to use ansible to manage a few DNS zones.
We use a playbook and some templates without any issue. However, the serial number of the zone(s) is manually modified by the end users and a lot of times they forget to update it.
So, I want to create a task that will parse the current serial from the zone file and then update it (YYYMMMDDXX format).
My main concern at the moment is how to get the current serial.
I have the current task:
- name: Get current serial in zone file
  lineinfile:
    path: "{{ bind_zone_file }}"
    regexp: "\s*(\d{10})\s*\;Serial"
    register: current_serial

It works as expected of course. However, it's not very helpful since I need do a lot of work with it.
My question is:
How do I register just the \1 part of the regex?

A: This might be a bit of a roundabout way, but I had a similar need. I used a filter. Applying that to your scenario, I think looks like this:
- name: Get current serial in zone file, in raw form
  lineinfile:
    path: "{{ bind_zone_file }}"
    regexp: "\s*(\d{10})\s*\;Serial"
    register: current_serial_raw

- name: Get current serial using a regex filter
  set_fact:
    current_serial: "{{ current_serial_raw | regex_search('\s*(\d{10})\s*\;Serial','\\1') | first }}"

The interesting part is the use of \\1 in the regex_search. | first is needed because regex_search in this form returns an array.
See if this inspires you further.


text:
Q: iOS 9 update now errors when I try to switch views So I am switching a to a new view inside of a view like this
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{

SKTransition *doors = [SKTransition fadeWithColor:[UIColor whiteColor] duration:.5];
GameScene *next = [[GameScene alloc]initWithSize:self.size];
next.highScore = self.highScore;

[self.view presentScene:next transition:doors];
self.timer.invalidate;

}

Xcode now gives me this error

"CAEAGLLayer: 0x7b1acc80 : calling -display has no effect."

Any ideas of whats going on here?


text:
Q: Getting error for regression using csv files in scikit I read the data from features.csv file and stored in a array.
i got the classlabels of those features and stored in a textfile.
Fitting the data:
y_rbf = svr_rbf.fit(train_input, train_lab)

But when i use the test set i am getting same value for all the records of test data.
But if i use test set as subset from training set the O/P is exact. I am unable to know whether my model is built or not. How to overcome this problem.
This is not for classification. It is for regression.


text:
Q: Remove event listeners in a foreach with a function passing arguments I need to remove multiple event listeners (by calling the method destroy) but to do this I have to have the function external. The problem is that this function has to pass 2 arguments (e and item) and I get this error:

Uncaught ReferenceError: item is not defined
at HTMLButtonElement.Accordion.clickHandler

because, I think, the item variable doesn't already exist (because it will be passed by the forEach).
Here my code:
export default class Accordion {

  constructor(el) {
    this.accordion = el;
    this.items = el.querySelectorAll('.accordion__item');

    // Specify a *unique* function for add and remove the event.
    this.clickHandler = (e) => this.onClickBtn(e, item);

    // Create click events
    this.bindEvents();
  }

  bindEvents() {
    // Create a click event for each item
    this.items.forEach(item => {
      let btn = item.querySelector('.accordion__btn');
      btn.addEventListener('click', this.clickHandler);
    });
  }

  destroy() {
    this.items.forEach(item => {
      let btn = item.querySelector('.accordion__btn');
      btn.removeEventListener('click', this.clickHandler);
    });
  }

  onClickBtn(e, item) {
    e.preventDefault();
    // DO THINGS
  }

}


text:
Q: LPAD without trimming in mysql I am trying to find a way to add 0 at the beginning of an ID without trimming it :
I am currently using LPAD(id,4,"0") witch works fine until 9999

*

*Request : SELECT LPAD(12345,4,"0");

*Excepted result : 12345

*Result : 1234
I am Looking for a Request who does LPAD(id, MAX(LENGTH(id),4), "0")
I found SELECT IF(LENGTH(12345)>4, 12345, LPAD(12345, 4, "0")); but i would prefer if the 4 was in a single place (to make it easier use it elsewhere).

*

*Is there a build-in function that does what i'm looking For ?

*Or is there an alternative to the function MAX() that would work in that situation ?

*Or should I stick with the IF(LENGTH) solution and it's drawbacks ?

Edit :
ZEROFILL doesn't fit my needs because I also need the id without 0s.
I mainly use the ID without the LPAD(), but when I do, I use it with a prefix : CONCAT("PFX", LPAD(id,4,"0"))
Thanks for your Help
PS: please tell me if i do anything wrong, it's my first time asking here.

A: Well I had similar problem with LPAD, it was truncating number to its pad length. According to https://dev.mysql.com/doc/refman/8.0/en/string-functions.html#function_lpad it is expected result.
As far as I can see, nobody mentioned answer that solved my same problem:
LPAD(id, GREATEST(LENGTH(id), 4), "0")

It works as expected. Pads any id's shorter than 4 characters with 0, and returns unchanged id's that are longer than 4 characters.
I'm leaving my answer here for other people, that will find this question in the future.

A: You can cat the length of a int field and also set zerofill like this:
CREATE TABLE `num` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `Numbers` int(5) unsigned zerofill DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

Insert values:
INSERT INTO `num` (`id`, `Numbers`)
VALUES
    (1, 1),
    (2, 22),
    (3, 123456);

See the result:
MariaDB []> select * from num;
+----+---------+
| id | Numbers |
+----+---------+
|  1 |   00001 |
|  2 |   00022 |
|  3 |  123456 |
+----+---------+
3 rows in set (0.000 sec)

MariaDB []>

without zerofill you can calc it like:
SELECT
  id,
  SUBSTRING( CONCAT('000000',Numbers),- GREATEST(LENGTH(Numbers),5))
FROM num;

Result:
MariaDB []>     SELECT
    ->       id,
    ->       SUBSTRING( CONCAT('000000',Numbers),- GREATEST(LENGTH(Numbers),5))
    ->     FROM num;
+----+--------------------------------------------------------------------+
| id | SUBSTRING( CONCAT('000000',Numbers),- GREATEST(LENGTH(Numbers),5)) |
+----+--------------------------------------------------------------------+
|  1 | 00001                                                              |
|  2 | 00022                                                              |
|  3 | 123456                                                             |
+----+--------------------------------------------------------------------+
3 rows in set (0.001 sec)

MariaDB []>

A: Ask yourself, why a number would need leading zeroes at all. No number in practical and theoretical math needs leading zeroes.
Maybe you want to visuals something, and not work with the result as a real number.
In that case, you can either declare the field in the table ZEROFILL and select it converted to char: SELECT CONVERT(id, CHAR);.
Other than that, the only way is a mix of CONCAT() and LENGTH(), that way you avoid stripping the ID to the value in LPAD().

A: LPAD
You can achieve this with an REGEXP_REPLACE to do a LPAD equivalent but without truncating the result. If you want a minimum length of 4 and padding with 0, you can do:
REGEXP_REPLACE(CONCAT('0000', id), '^0{0,4}(.{4,})$', '\\1')

You can adapt this by replacing '0000' with REPEAT('0', 4) to do it programmatically. The main advantage in this approach, is to not repeating the padded thing. In my use cases, I can have very long and complex things that I don't want to duplicate to only pad them, so this code fragment do its job.
RPAD
For those who have the problem for RPAD, you need a very close pattern:
REGEXP_REPLACE(CONCAT(id, '0000'), '^(.{4,}?)0{0,4}$', '\\1')

The two blocks in the pattern are essentially inverted but you can see .{4,}? instead of .{4,}. It's for set the greediness to lazy for the {4,} quantifier. It's needed here.


text:
Q: An error occurred while calling o442.pyWriteDynamicFrame. Decimal precision 136 exceeds max precision 38 I'm trying to extract data from Oracle/Data catalog on AWS Glue to S3 as json file and I'm getting the Decimal precision error. I also tried forcing the data type of the schema from decimal to string but I'm getting the same error.
This is where I'm getting error.
S3bucket_node3 = glueContext.write_dynamic_frame.from_options(
    frame=ApplyMapping_node2,
    connection_type="s3",
    format="json",
    connection_options={
        "path": "s3://s3path",
        "partitionKeys": [],
    },
    transformation_ctx="S3bucket_node3",
)


text:
Q: How do I check why a Kubernetes webpage keeps loading? I followed this Google cloud Kubernetes tutorial for python. I basically changed what's in their hello world function to plot with matplotlib (with some other functions beforehand to get data to plot). It all worked (with some changes to the dockerfile, to pip install modules, and use just python 3.7 instead of the slim version) until where it says to view a deployed app. I copy the external IP and try it in the browser, but it just loads. I'm not sure what to check to see why it won't finish loading.
So I'm wondering how I check where the problem is. The python code works fine elsewhere, outputting a plot with flask on a local computer

A: You can try proxying from your localhost directly to the pod to see if there's a problem with the load balancer.
kubectl port-forward your-pod-xxxxxxxxxx-xxxxx <local-port>:<pod-port>

Then you can just hit http://172.0.0.1:<local-port> on your browser.
You can also take a look at the pod logs:
kubectl logs your-pod-xxxxxxxxxx-xxxxx


text:
Q: "For item in list" loop, need explanation Okay so I have googled this for days now and still just can't grasp the idea of a "for variable in list" loop! I have been doing the Python course by Codecademy and one exercise I did wanted me to print a 5x5 board of "O"s. Now I successfully did it but I still have no idea how! I will give you the code I did and the result.
The code I wrote is:
board = []
for i in range(0, 5):
    board.append(["O"] * 5)
def print_board(board):
    for row in board:
        print row
print_board(board)

As you can see the goal of the code is to get this result which I did:
['O', 'O', 'O', 'O', 'O']
['O', 'O', 'O', 'O', 'O']
['O', 'O', 'O', 'O', 'O']
['O', 'O', 'O', 'O', 'O']
['O', 'O', 'O', 'O', 'O']

Could someone explain to me how the "for row in board" loop and the "for i in range(0, 5)" loop made this outcome? Thanks!

A: The general syntax is for item in iterator
That means, that every iteration of the loop, the variables item will contain the next item in iterator.
For example:
lst = [1,2,3,4,5]
for number in lst:
   print number #number is 1 then 2 then 3... every iteration its different according to lst

# output:
1
2
3
4
5

OK... now range() is a really nice function that lets you iterate over numbers easily.
It can get a start, end, step and returns a list of numbers that is all the numbers you asked for. For example range(1, 11, 2) will return [1, 3, 5, 7, 9] (11 not included)

A: for i in range(0, 5):
    board.append(["O"] * 5)

Here you're appending ['O', 'O', 'O', 'O', 'O'] (["0"] repeated five times) to the list called board five times. Note that this whole list is appended at once, if you append more such lists, board will be a list of lists, so at each valid index you could find a list.
for row in board:
    print row

This iterates over all the entries of board, which, once again, consists of lists.
That's why you're getting five lists each of which contain five letters '0'.


text:
Q: Elasticsearch Nest unit tests with Moq : fail to mock concrete class I need to mock some methods and properties in Nest.IElasticClient interface that is used in my repo.
As example I need to stub the Indices.Exists() method to return an ExistsResponse having an Exists property returning true.
The problem is that the concrete class has no interface implementation, nor setter on the Exists property, and is not declared virtual neither in Nest lib:
public class ExistsResponse : ResponseBase
{
    public ExistsResponse();
    public bool Exists { get; }
}

public ExistsResponse Exists(Indices index, Func<IndexExistsDescriptor, IIndexExistsRequest> selector = null);

So for the mocking I tried to set the property anyway on the concrete class, but it failed with all the following methods, I have no idea on how to do ...
/* Fail with exception :
System.NotSupportedException : Unsupported expression: x => x.Exists
    Non-overridable members (here: ExistsResponse.get_Exists) may not be used in setup / verification expressions.
*/
    var mock1 = new Mock<ExistsResponse>();
    obj.SetupGet(f => f.Exists).Returns(true);

/* Fail with exception :
 System.NotSupportedException : Unsupported expression: f => f.Exists
    Non-overridable members (here: ExistsResponse.get_Exists) may not be used in setup / verification expressions.
*/
    var mock2 = Mock.Of<ExistsResponse>(x => x.Exists == true);

/* Fail with exception :
System.ArgumentException : Property set method not found.
*/
    var mock3 = new ExistsResponse();
    var property = typeof(ExistsResponse).GetProperty("Exists", BindingFlags.Public | BindingFlags.Instance);
    property.SetValue(mock3, true);

/* Fail with exception :
System.NullReferenceException (setter is null)
*/
    var mock4 = new ExistsResponse();
    var setter = property.GetSetMethod(true);
    setter.Invoke(mock4, new object[] { true });

    // My Mock on the Indices.Exists method
    var elasticMock = new Mock<IElasticClient>();
    elasticMock
    .Setup(x => x.Indices.Exists(It.IsAny<string>(), null))
    .Returns(/*** my stubbed object here ***/); // <== how to stub the concrete class to return a ExistsResponse.Exists = true ?

My libs :
Nest 7.12.1
Moq 4.15.2
XUnit 2.4.1
.Net 5

Thank you for your help

A: It is usually not good to mock what you don't own but if you want to mock elastic client responses the best approach will be to use InMemorryConnection, you can instantiate a new elasticClient with InMemorryConnection like this:
InMemorry Elastic Client:
var connection = new InMemoryConnection();
var connectionPool = new SingleNodeConnectionPool(new Uri("http://localhost:9200"));
var settings = new ConnectionSettings(connectionPool, connection);
var client = new ElasticClient(settings);

Then you will need to fake the response and ask client to return it like below:
var response = new
{
    took = 1,
    timed_out = false,
    _shards = new
    {
        total = 2,
        successful = 2,
        failed = 0
    },
    hits = new
    {
        total = new { value = 25 },
        max_score = 1.0,
        hits = Enumerable.Range(1, 25).Select(i => (object)new
        {
            _index = "project",
            _type = "project",
            _id = $"Project {i}",
            _score = 1.0,
            _source = new { name = $"Project {i}" }
        }).ToArray()
    }
};

var responseBytes = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(response));
var connection = new InMemoryConnection(responseBytes, 200);
var connectionPool = new SingleNodeConnectionPool(new Uri("http://localhost:9200"));
var settings = new ConnectionSettings(connectionPool, connection).DefaultIndex("project");
var client = new ElasticClient(settings);

var searchResponse = client.Search<Project>(s => s.MatchAll());

You can find more information about InMemorryConnection here.
If you want to properly follow don't mock what you don't own you need to do following steps:

*

*Wrap ElasticClient and all Request and Responses of ElasticClient in this library, then you can easily mock what you need.

*You should test your wrapper class with Integration test to be sure your wrapped class work as expected.

UPDATE:
For mocking Indices.Exists you need only to send 200 OK so you only need to do this:
var connection = new InMemoryConnection(responseBytes, 200);


text:
Q: Debugging in Visual Studio 2012 is slow We have a large ASP.NET application that has been built over the last decade and is now running in .NET 4.0.
Recently, we upgraded to Visual Studio 2012 Premium (from 2010 Premium).
Our application compiles successfully, and when we run/debug our application its from a local IIS on each one of our developer workstations (versus using using the development server).
Ever since upgrading to 2012, when we are debugging our application, we have noticed the application to run VERY slow in loading ASP.NET pages, it can take nearly 20-30 seconds per page. But, when we access the application straight to the local IIS and without using the VS2012 debugger, it runs great. Something about debugging in Visual Studio 2012 on our application is slowing down our application performance significantly.
Is there a good tool we could use to capture what is going on in the background?
Also, this is happening on both Windows 7 Enterprise machines and Windows 8 Pro machines.  All 64 bit with 8+ GB of RAM, and Intel Core i7 processors.
Thanks for any help.

A: My debug on VS 2012 was very slow, it was taking 20~30 seconds for every step.
My solution was disable the .NET Reflector extension.
Go to Tools - Extensions and Updates - Disable .NET Reflector.

A: Try to delete all breakpoints, then clean and rebuild solution and debug it again.

A: Maybe your application is throwing and catching lots of exceptions?  This can really slow things down in debug mode.  Set the Exceptions properties to break on CLR exceptions and see if this is the case.


text:
Q: Is there a time delay before thin film interference begins? I was thinking about an experiment mentioned by Feynman in his book QED.  He was describing the partial reflection and partial transmission of light at an air/glass boundary and explaining that for certain conditions you might see 8% of the light reflected but that this is just an average.  Depending on the thickness of the glass you will observer between 0% and 16% reflection.  He then mentions that this cycling between maximum and minimum reflection has been observed to occur or 100 000 000 cycles corresponding to a thickness of glass of 50 metres.
If we use a classical electromagnetic wave model of light (which is not what Feynman is doing) wouldn't we expect a delay between when the light begins to reflect and when the effects of thin film interference begin because of the slight delay for the EM wave to reach the far surface of the glass and come back to begin interference.  So we might observe 8% reflection and then $\frac{100}{c}$ seconds later it might change to some other value depending on the thickness.
Has this been observed?  I would assume not because it seems to contradict the photon model, most obviously in the case of light so dim it hits the glass with a interval of over $\frac{100}{c}$ between each photon.


text:
Q: Displaying the last post on static homepage (It might not be the first time this question is asked, but every time I found someone else asking it elsewhere, the post was very old and the method used wasn't efficient anymore.)
► I'd like to be able to show the last article of a specific category (let's say the category is "news") on my homepage (it's a wordpress page).
I've already made a custom template for it, but I just don't know what to call to display the last article.
Important : It isn't the only thing I want to display. In fact I would need to display the article on the right side of the page (so far I've tried setting up a table with two columns and putting it in the right one, but this may not be the best method).
The best thing would be to be able to display the article "raw", what I mean here is that if I put links in the post, clicking on the  tag in the homepage will directly take me to the reffered link and not to the post itself.
Let me know if you guys need anything else :)

A: Alright, I think I found my answer.
As I've said, I created a new php template in my theme named "New Index" and associated my homepage to it.
This template was at first a copy of the original index.php
Now here is the code I added for it to make what I wanted :
<?php $the_query = new WP_Query( 'posts_per_page=1&category_name=news' ); ?>
<?php while ($the_query -> have_posts()) : $the_query -> the_post(); ?>

<?php the_title(); ?>

<?php the_time('j F Y'); ?>

<?php the_content(); ?>

<?php
    endwhile;
    wp_reset_postdata();
?>

This may not be the optimal solution though, I'd be curious to hear tips about it.


text: Q: How do i add a PDF version map into the spotfire application? Trying to workout how i take a pdf map and present it in spotfire so i can mark out sections using latitude and longitude? I am looking to plot points on this map.


text:
Q: Opening the SaveDialog intermittently crashes application Good morning,
I have researched this to no end and have tried several solutions with no success. This anomaly happens maybe 1 in 4 attempts to save in testing. When the save button is clicked, the SaveDialog will start to appear, freeze for a second and shut down the application. I have tried [StaThread], but it did not help. Any suggestions would be appreciated.  Thanks in advance. My code is below..
private void button4_Click(object sender, EventArgs e)
    {
       try

        {

            using (SaveFileDialog SFD = new SaveFileDialog() { Filter = "Excel Workbook|*.xls", ValidateNames = true })
            {
                SFD.FileName = textBox11.Text.ToString();
                if (SFD.ShowDialog() == DialogResult.OK)

                {
                    Microsoft.Office.Interop.Excel.Application app = new Microsoft.Office.Interop.Excel.Application();
                    Workbook wb = app.Workbooks.Add(XlSheetType.xlWorksheet);
                    Worksheet ws = (Worksheet)app.ActiveSheet;
                    ws.Name = textBox11.Text.ToString();
                    app.Visible = false;

                    int i = 2;
                    foreach (ListViewItem item in lstLocal.Items)

                    wb.SaveAs(SFD.FileName, XlFileFormat.xlWorkbookNormal, Type.Missing, Type.Missing, false, false, XlSaveAsAccessMode.xlNoChange, XlSaveConflictResolution.xlLocalSessionChanges, Type.Missing, Type.Missing);
                    wb.Close();
                    app.Quit();
                    wb = null;
                    app = null;

                    MessageBox.Show("File has been saved!", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
        }
        catch
        {
            MessageBox.Show("Something went wrong!", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }

A: For closure on this, it turned out to be an anomaly with my developing rig. I have since had to wipe it and re-install Win10/vS2017 for other reasons and the problem no longer exists. Compiled app on new install no longer has this issue on the developing rig or any others. Strange~  Thank you for the help and suggestions.


text:
Q: sqlalchemy / pandas - How do I create an sqlalchemy `selectable` to pass to pd.read_sql? I'm completely new to sqlalchemy, and I've been trying to better understand how pd.read_sql can be used.
I've succesfully run the following:
import sqlalchemy as sa
import pandas as pd
df = pd.DataFrame( index=range(10,30), data=np.random.rand(20, 10) )
eng = sa.create_engine('sqlite:///test.db')
df.reset_index().to_sql('test_table', eng, index=False)
df2 = pd.read_sql( 'test_table' , eng ) # Don't understand this function

I've figured out I can just load whatever I stored in the table by passing the table name as the first argument of pd.read_sql but what if I wanted to load only the elements for which column index is greater than some number.
Question
How do I create an sqlalchemy selectable for the first argument of  pd.read_sql to only load a subset of the database/table?
Comment:
In this case I know that this is trivial to do after I've loaded df2 but if the size of the db is very large I'd like to avoid having to load the entire db in memory first.

A: Getting the table in 3 different ways. (Not sure what the differences are).
then using the .select() method on that table and the .where on that result gets what I want.
import sqlalchemy as sa
eng = sa.create_engine('sqlite:///test.db')
# First way to load table
m = sa.MetaData()
m.reflect(bind=eng)
t1 = m.tables['test_table']

# Second way
m2 = sa.MetaData(bind=eng)
t2 = sa.Table('test_table', m2, autoload=True)

# Third way
t3 = sa.Table('test_table', sa.MetaData(), autoload_with=eng)

# I can then use either of the t's to do the following
df3 = pd.read_sql(t.select().where(t.c.index > 15), eng)


text:
Q: Change timezone for logging On a new server, I've changed timezone from UTC to my local timezone, Europe/London:
sudo ln -sf /usr/share/zoneinfo/Europe/London /etc/localtime

That gives me the desired time when, for example, I run date. However, new items in log files (e.g. /var/log/secure) are timestamped with the 'old' timezone, which is an hour off (worse, they don't even indicate timezone, but that's a whole other issue!).
I haven't restarted anything since I changed /etc/localtime; does everything require a reboot to get in sync, or is there an appropriate daemon I can ping in order to refresh the timezone?

A: Most services are using syslog and it would be enough to restart syslog or respective rsyslog.
For example at Debian
service rsyslog restart


text:
Q: Excel Interop : Can you listen for a change in range value? Is it possible, and if so how, to listen to changes in an Excel range from within C# using the MS interop libraries?
I know how to read the value in a named range, but don't know how to listen and automatically pick up changes. Been through Google and not found anything to solve this...

A: I don't think Range object has a Change event. You can listen to the Worksheet Change event and probably do a bit more checking to figure out if the change is the one you want to catch.


text:
Q: Redirect user by IP in htaccess So I've been trying to complete some construction on my website. However, I want it so that if a user does not match my IP, they will be redirected to a "under construction" page. However, I want this IP match to work for all of the pages on domain.com, except for the under construction one.
Is there a way that I can add a function like this in .htacess in the root folder of my website?

A: Try adding these rules to the htaccess file:
RewriteEngine On
RewriteCond %{REMOTE_ADDR} !^12\.34\.56\.78$
RewriteRule !^/?under_construction.html /under_construction.html [L,R]

Where 12.34.56.78 is your IP address and /under_construction.html is your under construction page. You'll need to make sure there are no other htaccess files in subdirectories that use mod_rewrite (as it would supercede these rules).


text:
Q: How do I access a JSON object's fields in SQL? I pulled JSON data from a third-party API and I am trying to automate its entry into an SQL database. The format of the JSON is as follows :
{ "fields": {
    "Example.FirstName": "Bob",
    "Example.LastName": "Test",
    "Example.Salary": "$50000"
    },
    "UserId": "1001231234"
}

I can retrieve the UserId, but anything within fields I am not sure how to access. I figured it would just be fields.Example.FirstName but I keep getting null.
This is what I have done
Declare @JSON varchar(max)
SELECT @JSON=BulkColumn
FROM OPENROWSET (BULK 'C:\Python38\Data.JSON', SINGLE_CLOB) as import
SELECT * FROM OPENJSON (@JSON)
WITH
(
    [fields.Example.FirstName] varchar(50),
    [UserId] varchar(50)
)

If anyone can explain the syntax of how to access the data in fields, it would be much appreciated.
I am using Microsoft SQL Server if that helps.

A: I think you want:
select *
from openjson (@json)
with (
    firstname varchar(50) '$.fields."Example.FirstName"',
    lastname  varchar(50) '$.fields."Example.LastName"',
    salary    varchar(50) '$.fields."Example.Salary"',
    UserId    varchar(50)
)


text:
Q: GraphQL Fetch Working in Page Component Only I'm using fetch() to query GraphQL in lib/api.js like so:
const API_URL = process.env.WORDPRESS_API_URL

async function fetchAPI(query, { variables } = {}) {
  const headers = { 'Content-Type': 'application/json' }

  const res = await fetch(API_URL, {
    method: 'POST',
    headers,
    body: JSON.stringify({
      query,
      variables,
    }),
  })

  const json = await res.json()
  if (json.errors) {
    console.error(json.errors)
    throw new Error('Failed to fetch API')
  }
  return json.data
}

...
export async function getPostsByCategory(slug, batchSize, endCursor) {
  const data = await fetchAPI(
    `
    query ($slug: String!, $batchSize: Int, $endCursor: String) {
      posts(first: $batchSize, after: $endCursor, where: {categoryName: $slug}) {
        pageInfo {
          hasNextPage
          endCursor
        }
        edges {
          node {
            id
            categories {
              edges {
                node {
                  name
                  slug
                  id
                }
              }
            }
            date
            featuredImage {
              node {
                sourceUrl(size: MEDIUM)
                altText
              }
            }
            slug
            title
          }
        }
      }
    }
  `,
    {
      variables: { slug, batchSize, endCursor },
    }
  )
  return data
}

If I call getPostsByCategory() in my page component [slug].js inside of getStaticProps() it returns data as expected. If, however, I use the same function getStaticProps() outside of get static props like so...
async function getPostsByCategory() {
    const moreArticles = await getMorePostsByCategory(categorySlug, 24, posts.pageInfo.endCursor)
    setFilteredArticles(...posts.edges, ...moreArticles.edges)
}

...

<div onClick={loadMoreArticles}>
    Load More
</div>

I get the unexpected token in json at position 0 graphql error.
If, instead, I move the entire fetch logic into the page component like so...
async function getPostsByCategory() {
    const headers = { 'Content-Type': 'application/json' }
    const query =
        `query ($slug: String!, $batchSize: Int, $endCursor: String) {
            morePosts: posts(first: $batchSize, after: $endCursor, where: {categoryName: $slug}) {
              pageInfo {
                hasNextPage
                endCursor
              }
              edges {
                cursor
                node {
                  id
                  categories {
                    edges {
                      node {
                        name
                        slug
                        id
                      }
                    }
                  }
                  date
                  featuredImage {
                    node {
                      sourceUrl(size: MEDIUM)
                      altText
                    }
                  }
                  slug
                  title
                }
              }
            }
          }
        `
    const variables = {slug:categorySlug, batchSize:24, endCursor: endCursor || posts?.pageInfo.endCursor}
    const res = await fetch('http://localhost:10083/graphql', {
        method: 'POST',
        headers,
        body: JSON.stringify({
            query,
            variables
        }
            ),
    })
    const json = await res.json()
    if (json.errors) {
        console.error(json.errors)
        throw new Error('Failed to fetch API')
    }

    return json?.data
}

... we return the expected data. I'm wondering if there's some limitation to fetching data in page components I don't know of. Any information about this is appreciated.


text:
Q: Meaning of font-size on SVG I have the following SVG file:
<svg height="1000.0" version="1.1" viewBox="0 0 5.0 5.0" width="1000" xmlns:xlink="http://www.w3.org/1999/xlink" xmlns="http://www.w3.org/2000/svg">
   <g>
      <g fill="none" stroke="none" />
      <g stroke-width="0.005" stroke="black">
         <g fill="black" font-family="Arial, sans-serif" font-size="0.05" stroke="none" text-anchor="start" transform="translate(0.0125 -0.025)">
            <text x="4.50" y="5.00">101°</text>
         </g>
         <line x1="0.00" x2="5.00" y1="5.00" y2="5.00" />
      </g>
      <g stroke-width="0.005" stroke="black">
         <g fill="black" font-family="Arial, sans-serif" font-size="0.05" stroke="none" text-anchor="start" transform="translate(0.025 0.00625)">
            <text x="-0.00" y="0.05">11°</text>
         </g>
         <line x1="0.00" x2="0.00" y1="5.00" y2="0.00" />
      </g>
   </g>
</svg>

The font size is 0.05, which is very small. The font-size attribute in svg refer to the font-size property CSS specification. There is no unit, so I looked in the following Stackoverflow question. If I change the size from 0.05 to 0.0.5px, I have the same result, so I assume that the browser (in my case Edge or Firefox, or Chrome all have have the same result) consider no unit as pixel units.
It seems that the size of the font depend on the viewbox, because with the current svg file, I have the following result:

Now if I remove the viewbox, with this svg specification:
<svg height="1000.0" version="1.1" width="1000" xmlns:xlink="http://www.w3.org/1999/xlink" xmlns="http://www.w3.org/2000/svg">
   <g>
      <g fill="none" stroke="none" />
      <g stroke-width="0.005" stroke="black">
         <g fill="black" font-family="Arial, sans-serif" font-size="0.05" stroke="none" text-anchor="start" transform="translate(0.0125 -0.025)">
            <text x="4.50" y="5.00">101°</text>
         </g>
         <line x1="0.00" x2="5.00" y1="5.00" y2="5.00" />
      </g>
      <g stroke-width="0.005" stroke="black">
         <g fill="black" font-family="Arial, sans-serif" font-size="0.05px" stroke="none" text-anchor="start" transform="translate(0.025 0.00625)">
            <text x="-0.00" y="0.05">11°</text>
         </g>
         <line x1="0.00" x2="0.00" y1="5.00" y2="0.00" />
      </g>
   </g>
</svg>

I have the following result (so not visible font because too small):

What's the algorithm to use with a (for example pixel-unit) font-size in SVG, relative to the viewbox?

A: Numbers without units or with px units are called userspace coordinates/sizes. They are local to the coordinate system in use where the element is placed. A viewBox of 0 0 5 5 describes a drawing region that is 5 units both in width and height. A text that is a child element and has font-size: 0.05 is 1/100 of the viewBox height.
The userspace coordinate system has no units and is abstract in the sense that it has to be fitted in some space (the "viewport") before it is rendered. You can use units in the userspace context, but they need to be converted into unitless userspace numbers. (For px, trivially just delete the unit.)
Only afterwards, when you know the size of the viewport and how to fit the drawing region inside, you can compute real-world pixel (for a screen), or point (for printing), or centimeter (for a plotter) values.
If the <svg> element has a width and height of 1000px, the drawing region defined by the viewBox is rendered by multiplying the userspace units with a factor of 200px, so that it fills the element. In other words: what in  terms of the coordinate system inside the viewBox is a length of 1, is 200px in regard to the rendered <svg> element. A text with a font size of 0.05 is rendered accordingly at a size of 0.05 * 200px = 10px.
If there is no viewBox attribute present, the factor is simply 1px. A userspace unit of 1 is rendered at 1px, a font size of 0.05 is rendered as 0.05px.


text:
Q: grails config keeps changing In my GSP I have the following code(as debugging)
${grailsApplication.config.myConfig.provider}

For the longest time I had in my config:
myConfig.provider='a'

I have completed the projet for provider a and switched it to b
myConfig.provider='b'

I have cleaned the project, even deleted my target folder, yet when I navigate to the page it still prints "a"


text:
Q: adding text between items on radio button control list I need to add some text between the list items, but I haven't seen a way to do this. I've looked at adding space between the items, but I can't figure out how to add text between the list items.
    <asp:RadioButtonList ID="RadioButtonList1" runat="server" >
 need to add text here
    <asp:ListItem Value="10.00" Selected="True">this is item1</asp:ListItem>
 need to add text here
    <asp:ListItem Value="10.00">this is item2 </asp:ListItem>
 need to add text here
    <asp:ListItem Value="10.00"> this is item3 </asp:ListItem>

</asp:RadioButtonList>

A: You can use several RadioButton controls to achieve that, also group them if needed.
RadioButtonList will not allow you to insert text in between. Here is a quote from MSDN:

The RadioButtonList control does not permit you to insert text between
  the buttons, but is far easier to use if you want to bind the buttons
  to a data source. It is also slightly easier to write code that checks
  which button has been selected.

A: I would create a custom RadioButtonList control so that you can implement your own custom ListItem type and render the values in your customer ListItem's properties appropriately.
ListItem is sealed, so you can't inherit from it.  However you could make your own class that mimics ListItem, and add a couple more properties for the addition text you want to be able to display per list item.
Then, in the Render method of your custom Radio Button List, you could render a  tag and your text in between those before outputting the normal list item properties - text and value.
HTH


text:
Q: How can I limit rows showing in an ng-repeat? I have an ng-repeat that looks like this:

{{ subject.name }}

Is there some way that I can limit the display of rows to rows where subject.id is less than 50 if roleId > 1 and otherwise show all rows?
$scope.roleId = 0 means no filter
$scope.roleId > 0 means filter to show only rows in $scope.subjects where subject.id is less than 50

A: You can accomplish this using ng-if or use a filter

50">

The part about the role id in question is not clear

A: Use Limit to Filter

{{ subject.name }}

then set the $scope.quantity in your controller based on your business logic.
Use a Custom Filter
to use a custom filter you just set a new $scope function in your controller.
$scope.yourFilter = function (items) {
    // probably need some more logic but you get the idea
    return items.id < 50;
};

thin in the filter it should look like this

{{ subject.name }}

A: Add a filter

{{ subject.name }}

And in your controller, have this function:
$scope.filterFn = function (item) {
    if ($scope.roleId > 1) {
        return (item.Id < 50) ? true : false;
    }
    else
        return true;
};

If I understood your comments correctly.


text:
Q: Tensorflow throwing InvalidArgumentError: Incompatible shapes after custom loss function, before end of epoch I've been debugging this problem since morning and haven't been able to make any progress. I'm trying to train a model with batch_size of more than 1. The code works for batch_size=1, but not for any bigger number. Please help if possible.
Code for the custom Loss function is (All the print statements were added during the debug process):
def mobilenet_loss(y_true, y_pred):

    '''
    y_pred will be an tensor of (None, 21, 21, 3) where the last axis corresponds to the classes from class_list

    y_true will be an integer 0, 1 or 2 that would indicate which class the true value belongs to

    Since y_pred is the output of a Softmax function, the sum of elements in the last dim will be 1.0
    Using y_true, we will construct a tensor y_true_array with ones in the index of y_true and zeros in others
    We will be trying to minimize sum(y_true_array - y_pred)

    '''

    diagnostics = True
    if diagnostics: tf.print("ytrue =", y_true, tf.shape(y_true) ," y_pred shape =", tf.shape(y_pred))

    one_class_shape = tf.concat([tf.shape(y_pred)[:-1], tf.constant([1])] , axis=0)
    if diagnostics: tf.print("one_class_shape =", one_class_shape)

    y_true_shape = tf.shape(y_true)
    y_true_copy = tf.identity(y_true)
    tf.print("y_true_shape - ", y_true_shape)

    y_true_compare_0 = tf.zeros(y_true_shape, dtype=tf.int64, name="compare_0_zeros")
    y_true_compare_1 = tf.ones(y_true_shape, dtype=tf.int64, name="compare_1_ones")
    tf.print("y_true_compare_0 =", tf.shape(y_true_compare_0))
    tf.print("y_true_compare_1 =", tf.shape(y_true_compare_1))

    def concat_0(): return tf.concat([  tf.ones(one_class_shape, dtype=tf.float32, name="loss_ones_0")
                                      , tf.zeros(one_class_shape, dtype=tf.float32, name="loss_zeros_0")
                                      , tf.zeros(one_class_shape, dtype=tf.float32, name="loss_zeros_0_1")]
                                      , axis=-1, name="concat_0")
    def concat_1(): return tf.concat([  tf.zeros(one_class_shape, dtype=tf.float32, name="loss_zeros_1")
                                      , tf.ones(one_class_shape, dtype=tf.float32, name="loss_ones_1")
                                      , tf.zeros(one_class_shape, dtype=tf.float32, name="loss_zeros_1_1")]
                                      , axis=-1, name="concat_1")
    def concat_2(): return tf.concat([  tf.zeros(one_class_shape, dtype=tf.float32, name="loss_zeros_2")
                                      , tf.zeros(one_class_shape, dtype=tf.float32, name="loss_zeros_2_1")
                                      , tf.ones(one_class_shape, dtype=tf.float32, name="loss_ones_2")]
                                      , axis=-1, name="concat_2")
    def equals_1_check():
        return tf.cond(tf.experimental.numpy.all(tf.math.equal(tf.cast(tf.reduce_sum(y_true_copy), dtype=tf.float64)
                                , tf.divide(tf.reduce_sum(y_true_compare_1)
                                            , tf.size(y_true_copy, out_type=tf.int64)
                                            ,name="div_equals_1_check")
                                , name="equals_1_check")
                        )
                        , concat_1
                        , concat_2
                        , name="second_condition")

    tf.print("y_true_compare_0", y_true_compare_0)
    y_true_array = tf.cond(tf.experimental.numpy.all(
                            tf.math.equal(tf.cast(tf.reduce_sum(y_true_copy), dtype=tf.float64)
                                       , tf.divide(tf.reduce_sum(y_true_compare_0)
                                                   , tf.size(y_true_copy, out_type=tf.int64)
                                                   , name="div_equals_0_check")
                                      , name="equals_0_check"))
        , concat_0
        , equals_1_check
        , name="first_condition")

    tf.print("div_equals_0_check shape = ", tf.divide(tf.reduce_sum(y_true_compare_0)
                                           , tf.size(y_true_copy, out_type=tf.int64), name="div_equals_0_check_1"))
    tf.print("div_equals_1_check shape = ",tf.divide(tf.reduce_sum(y_true_compare_1)
                                            , tf.size(y_true_copy, out_type=tf.int64),name="div_equals_1_check_1"))
    if diagnostics: tf.print("after y_true_array =", tf.shape(y_true_array), y_true_array.get_shape())

    error = tf.math.subtract(y_true_array, y_pred, name="error")
    if diagnostics: tf.print("error shape = ", tf.shape(error))

    loss = tf.math.reduce_sum(error, name='final_loss')
    if diagnostics: tf.print("loss shape = ", tf.shape(loss), loss)

    return loss

This is what I use to initialize the model
model = Model(inputs = inputs, outputs = mobilenet_output, name="main_model")

model.compile(optimizer = 'adam'
              , loss =mobilenet_loss
              , metrics = [ 'accuracy']

              )

model.fit(x = train_generator, steps_per_epoch = 1, epochs=2, batch_size=batch_size, shuffle=False)

Error Message:
Epoch 1/2
ytrue = [[2]
 [2]] [2 1]  y_pred shape = [2 31 31 3]
one_class_shape = [2 31 31 1]
y_true_shape -  [2 1]
y_true_compare_0 = [2 1]
y_true_compare_1 = [2 1]
y_true_compare_0 [[0]
 [0]]
div_equals_0_check shape =  0
div_equals_1_check shape =  1
after y_true_array = [2 31 31 3] TensorShape([2, 31, 31, 3])
error shape =  [2 31 31 3]
loss shape =  [] -21462.2773
ytrue = [[2]
 [2]] [2 1]  y_pred shape = [2 31 31 3]
one_class_shape = [2 31 31 1]
y_true_shape -  [2 1]
y_true_compare_0 = [2 1]
y_true_compare_1 = [2 1]
y_true_compare_0 [[0]
 [0]]
div_equals_0_check shape =  0
div_equals_1_check shape =  1
after y_true_array = [2 31 31 3] TensorShape([2, 31, 31, 3])
error shape =  [2 31 31 3]
loss shape =  [] -8.79764557e-05
---------------------------------------------------------------------------
InvalidArgumentError                      Traceback (most recent call last)
<ipython-input-39-739652b805f0> in <module>
----> 1 model.fit(x = train_generator, steps_per_epoch = 1, epochs=2, batch_size=batch_size, shuffle=False)

~/opt/anaconda3/envs/bigthinx/lib/python3.7/site-packages/tensorflow/python/keras/engine/training.py in fit(self, x, y, batch_size, epochs, verbose, callbacks, validation_split, validation_data, shuffle, class_weight, sample_weight, initial_epoch, steps_per_epoch, validation_steps, validation_batch_size, validation_freq, max_queue_size, workers, use_multiprocessing)
   1098                 _r=1):
   1099               callbacks.on_train_batch_begin(step)
-> 1100               tmp_logs = self.train_function(iterator)
   1101               if data_handler.should_sync:
   1102                 context.async_wait()

~/opt/anaconda3/envs/bigthinx/lib/python3.7/site-packages/tensorflow/python/eager/def_function.py in __call__(self, *args, **kwds)
    826     tracing_count = self.experimental_get_tracing_count()
    827     with trace.Trace(self._name) as tm:
--> 828       result = self._call(*args, **kwds)
    829       compiler = "xla" if self._experimental_compile else "nonXla"
    830       new_tracing_count = self.experimental_get_tracing_count()

~/opt/anaconda3/envs/bigthinx/lib/python3.7/site-packages/tensorflow/python/eager/def_function.py in _call(self, *args, **kwds)
    886         # Lifting succeeded, so variables are initialized and we can run the
    887         # stateless function.
--> 888         return self._stateless_fn(*args, **kwds)
    889     else:
    890       _, _, _, filtered_flat_args = \

~/opt/anaconda3/envs/bigthinx/lib/python3.7/site-packages/tensorflow/python/eager/function.py in __call__(self, *args, **kwargs)
   2941        filtered_flat_args) = self._maybe_define_function(args, kwargs)
   2942     return graph_function._call_flat(
-> 2943         filtered_flat_args, captured_inputs=graph_function.captured_inputs)  # pylint: disable=protected-access
   2944
   2945   @property

~/opt/anaconda3/envs/bigthinx/lib/python3.7/site-packages/tensorflow/python/eager/function.py in _call_flat(self, args, captured_inputs, cancellation_manager)
   1917       # No tape is watching; skip to running the function.
   1918       return self._build_call_outputs(self._inference_function.call(
-> 1919           ctx, args, cancellation_manager=cancellation_manager))
   1920     forward_backward = self._select_forward_and_backward_functions(
   1921         args,

~/opt/anaconda3/envs/bigthinx/lib/python3.7/site-packages/tensorflow/python/eager/function.py in call(self, ctx, args, cancellation_manager)
    558               inputs=args,
    559               attrs=attrs,
--> 560               ctx=ctx)
    561         else:
    562           outputs = execute.execute_with_cancellation(

~/opt/anaconda3/envs/bigthinx/lib/python3.7/site-packages/tensorflow/python/eager/execute.py in quick_execute(op_name, num_outputs, inputs, attrs, ctx, name)
     58     ctx.ensure_initialized()
     59     tensors = pywrap_tfe.TFE_Py_Execute(ctx._handle, device_name, op_name,
---> 60                                         inputs, attrs, num_outputs)
     61   except core._NotOkStatusException as e:
     62     if name is not None:

InvalidArgumentError:  Incompatible shapes: [2,1] vs. [2,31,31]
     [[node Equal (defined at <ipython-input-39-739652b805f0>:1) ]] [Op:__inference_train_function_26226]

Function call stack:
train_function

Weirdly enough the code works just fine when I make the batch_size = 1
Here is the log from the same model with batch_size=1
Epoch 1/2
ytrue = [[2]] [1 1]  y_pred shape = [1 31 31 3]
one_class_shape = [1 31 31 1]
y_true_shape -  [1 1]
y_true_compare_0 = [1 1]
y_true_compare_1 = [1 1]
y_true_compare_0 [[0]]
div_equals_0_check shape =  0
div_equals_1_check shape =  1
after y_true_array = [1 31 31 3] TensorShape([1, 31, 31, 3])
error shape =  [1 31 31 3]
loss shape =  [] -1222.78308
ytrue = [[2]] [1 1]  y_pred shape = [1 31 31 3]
one_class_shape = [1 31 31 1]
y_true_shape -  [1 1]
y_true_compare_0 = [1 1]
y_true_compare_1 = [1 1]
y_true_compare_0 [[0]]
div_equals_0_check shape =  0
div_equals_1_check shape =  1
after y_true_array = [1 31 31 3] TensorShape([1, 31, 31, 3])
error shape =  [1 31 31 3]
loss shape =  [] -8.76188278e-06
1/1 [==============================] - 15s 15s/step - loss: -1222.7831 - mobnet_features_loss: -1222.7831 - Predictions_loss: -8.7619e-06 - mobnet_features_accuracy: 0.3777 - Predictions_accuracy: 0.3777
Epoch 2/2
ytrue = [[2]] [1 1]  y_pred shape = [1 31 31 3]
one_class_shape = [1 31 31 1]
y_true_shape -  [1 1]
y_true_compare_0 = [1 1]
y_true_compare_1 = [1 1]
y_true_compare_0 [[0]]
div_equals_0_check shape =  0
div_equals_1_check shape =  1
after y_true_array = [1 31 31 3] TensorShape([1, 31, 31, 3])
error shape =  [1 31 31 3]
loss shape =  [] -4929.66
ytrue = [[2]] [1 1]  y_pred shape = [1 31 31 3]
one_class_shape = [1 31 31 1]
y_true_shape -  [1 1]
y_true_compare_0 = [1 1]
y_true_compare_1 = [1 1]
y_true_compare_0 [[0]]
div_equals_0_check shape =  0
div_equals_1_check shape =  1
after y_true_array = [1 31 31 3] TensorShape([1, 31, 31, 3])
error shape =  [1 31 31 3]
loss shape =  [] 4.91845421e-05
1/1 [==============================] - 12s 12s/step - loss: -4929.6602 - mobnet_features_loss: -4929.6602 - Predictions_loss: 4.9185e-05 - mobnet_features_accuracy: 0.3049 - Predictions_accuracy: 0.3049

A: Found the solution to the problem I had posted here.

*

*I reshaped loss to be of shape [batch, final_conv_width, final_conv_height, feature_classes]

*I created a custom training loop with tf.GradientTape and optimizer.apply_gradients functions.

@tf.function
def grad(model, inputs, targets):
    with tf.GradientTape() as tape:
        y_pred = model(x)
        tf.print("in grad function y_pred shape = ", tf.type_spec_from_value(y_pred))
        loss_value = mobilenet_loss(targets, y_pred)
    return loss_value, tape.gradient(loss_value, model.trainable_variables)

num_epochs = 2
optimizer = tf.keras.optimizers.Adam()
avg_loss = tf.keras.metrics.Mean()

for epoch in range(num_epochs):
    x, y = next(train_generator)
    # Optimize the model

    loss_value, gradients = grad(model, x, y)

    optimizer.apply_gradients(zip(gradients, model.trainable_variables))
    avg_loss(loss_value)
    print(" epoch %d/%d, loss=%.4f "%(epoch +1, num_epochs, avg_loss.result()))


text:
Q: Run multiple test opening mutilple instances of windows application(VB .NET) using one UFT instance Application Under test is developed using .net vb .
Clarification 1 :
is it possible to run multiple tests parellel using one instance of UFT in a one machine ?
Clarification 2  :
Can we open multiple instances of the windows application and run different tests on each instance of the the opened windows application in parellel .

A: This will not workout with windows application. Even the application is minimized the objects will not be able to identify with UFT until the window is activated. Both the criteria will not work as the objects are just like that identified by their properties not by creation time as we use it for browser. Only option is running multiple test cases in multiple machines

A: UFT doesn't support running tests in parallel. Note that UFT simulates users, each tests assumes it controls where the focus is (sometimes by taking control of the mouse and keyboard for typing). If multiple tests are trying to do this you may get unexpected results just like you would if you had two mice connected to your computer and two people tried to do different things at the same time.
Consider the following two tests:
Test A

*

*Click username edit field

*Type "hello"

Test B

*

*Click password edit field

*Type "world"

When run in parallel you may get:

*

*Click password edit field

*Click username edit field

*Type "hello"

*Type "world"


text:
Q: How to get list of all views in Laravel 5.3? I'm trying to configure autocomplete input with all created blade views so is there option to get an array of all views? There is View::exists() to check for specific view but how to get all of them?
public function index(){
$allviews = Storage::files('');
return view('pages.dashboard', ['allviews' => $allviews]);
}

In my view I have this code
@foreach($allviews as $view)
<li>{{ $view }}</li>
@endforeach

It only shows .gitignore file

A: use File facade to scan the directory and give content of it.
check here https://laravel.com/docs/5.3/filesystem#directories
configure your view disk in config/filesystems.php add below snippet in disks array :
'disks' => [

    // ...

    'views' => [
        'driver' => 'local',
        'root' => base_path('resources/views'),
    ],
],

Storage::disk('views')->files('') //will list all directory and contents available in resources/views
Storage::disk('views')->files('auth') //will give content of resources/views/auth directory


text:
Q: How to create a new dictionary from old one using a given mapping? What I am seeking is a Python function that seeks an old dictionary and a mapping. A new dictionary should be returned using the given mapping from the old dictionary.
old_dic = {"a":"1", "b":"2", "c":"3", "d":"4"}
mapping_dic = {"a":"e", "c":"f", "d":"g"}

Hence, a new dictionary should be formed containing the keys e,f, and g. It should look like:
new_dic = {"e":"1", "f":"3", "g":"4"}

A: dict comprehension:
{v: old_dic[k] for k,v in mapping_dic.items()}

outputs:
{'e': '1', 'f': '3', 'g': '4'}

A: This could work, but maybe there's a better way:
new_dic = dict((mapping_dic[key], val) for key, val in old_dic.items() if key in mapping_dic)

A: Try this:
def numberofbagels(oldmap, trans):
    newmap = {}
    for key in oldmap:
        if key in trans:
            newmap[trans[key]] = oldmap[key]
    return newmap

old_dic = {"a":"1", "b":"2", "c":"3", "d":"4"}
mapping_dic = {"a":"e", "c":"f", "d":"g"}

print "%s"%(str(numberofbagels(old_dic,mapping_dic)))


text:
Q: SwiftUI: How to pass arguments to class from view? I have a class that conforms to ObservableObject, which takes some arguments. When I then use @ObservedObject var someName = className() in my view to access all the functions and data in the class, I get an error saying:

Missing arguments for parameters 'pickedVideo', 'pickedImage', 'retrievedImages', 'retrievedVideos' in call

I am aware that I somehow have to pass the arguments from my view to the class.
But how do I pass variables from my view to my class?
Class:
class DBFunctions : ObservableObject {

    init(pickedVideo: [String], pickedImage: [UIImage], retrievedImages: [UIImage], retrievedVideos: [AVPlayer]) {
        self.pickedVideo = pickedVideo
        self.pickedImage = pickedImage
        self.retrievedImages = retrievedImages
        self.retrievedVideos = retrievedVideos
    }

    var pickedVideo : [String]
    var pickedImage : [UIImage]
    var retrievedImages : [UIImage]
    var retrievedVideos : [AVPlayer]

    func somefunc() {

    }
}

View:
struct ContentView: View {
    @ObservedObject var helpFuncs = DBFunctions()

    @State var showPicker: Bool = false
    @State var pickedImage: [UIImage] = []
    @State var retrievedImages = [UIImage]()
    @State var player : AVPlayer?

    @State var width : CGFloat = 0
    @State var retrievedVideos = [AVPlayer]()
    @State var pickedVideo: [String] = []

    @State var isPaused = false

    var body: some View {
        VStack{
            Button(action: {
                helpFuncs.uploadImage()
            }) {
                Text("Upload Image")
            }
        }
    }

A: What you are doing is something like an anti-pattern... The ObservableObject should be getting their "truth" from the Model, and not from the view. So, normally speaking, or those values initialize themselves, or you get their from the Model.
To be clear, you should create an object first, from model data, then pass its instance to the View. That's what MVVM is all about.
Fell free to increase your question if something that I answered was not clear enough.
Edit1: If you need to communicate something (like a choice) from the View to the ObservableObject, you should do this via "Intents"... that is normally a func in the ObservableObject class. Those Intents (in my way to architect this is failable), if the Intent goes well, ObservableObject change the Model and Publish their new results to the View, which redraws itself. If the "Intent" not go through, or I launch an Alert (if it's critical) or I simply ignore.

A: As mentioned, you are not using ObservableObject as it is meant to be used.
Look at this link, it gives you some good examples of how to use ObservableObject and manage data in your app
https://developer.apple.com/documentation/swiftui/managing-model-data-in-your-app
Try something like this example code:
class DBFunctions : ObservableObject {
    @Published var pickedVideo : [String]  // <-- here  @Published
    @Published var pickedImage : [UIImage]
    @Published var retrievedImages : [UIImage]
    @Published var retrievedVideos : [AVPlayer]

    init() {
        self.pickedVideo = []
        self.pickedImage = []
        self.retrievedImages = []
        self.retrievedVideos = []
    }

    func uploadImage() {  }
}

struct ContentView: View {
    @StateObject var helpFuncs = DBFunctions() // <-- here

    @State var showPicker: Bool = false
    @State var player : AVPlayer?
    @State var width : CGFloat = 0
    @State var isPaused = false

    // do not use these, use the ones in your helpFuncs model directly
    // like: helpFuncs.pickedImage = ...
 //   @State var pickedImage: [UIImage] = []
 //   @State var retrievedImages = [UIImage]()
 //   @State var retrievedVideos = [AVPlayer]()
 //   @State var pickedVideo: [String] = []

    var body: some View {
        VStack{
            Button(action: {
                helpFuncs.uploadImage()
            }) {
                Text("Upload Image")
            }
        }
        .onAppear {
            // here do some initialisation of your helpFuncs, for example
        }
    }
}

With your original code (and question), You can of course pass some initial values, like this:
@ObservedObject var helpFuncs = DBFunctions(pickedVideo: [], pickedImage: [], retrievedImages: [], retrievedVideos: [])


text:
Q: How to order in django on two columns when one of the column is null I would like to order the dataset based upon the two columns let's say created_date and updated_date.
If updated_date is null it should order be using created_date otherwise using updated_date column.

A: You can work with a .annotate() [Django-doc] and then .order_by(…) [Django-doc]:
from django.db.models.functions import Coalesce

MyModel.objects.annotate(
    my_date=Coalesce('updated_date', 'created_date')
).order_by('my_date')
Since django-3.2 you can work with .alias(…) [Django-doc] to prevent calculating this both as column and in the ORDER BY clause:
from django.db.models.functions import Coalesce

MyModel.objects.alias(
    my_date=Coalesce('updated_date', 'created_date')
).order_by('my_date')


text:
Q: Emails on firebase login, someone else could sign my email up without my consent? I need to implement a confirmation feature for firebase password authentication, and would like to know if anyone has a good idea on implementation. (I could otherwise write a web app to manage this.)
If there is no good solution, I may just decide to forgo password based authentication, as I do not find it to be meaningful without some sort of confirmation on the user identity.
On a side, more important note:
The current issue is that Firebase does not allow controls on who can write to the password auth solution that is currently provided. Combine this with the fact that there is no email confirmation feature, someone else could feasibly sign my email up. Is this how firebase is intended to have the login work?
After signing up, someone could log in, and use my email as the 'profile' while using the features of the application. This can be done without having confirmed that this person is actually the account holder of the email provided.
What if someone used my email to make terrorist threats or other, less than desirable, illegal activities?

A: I'm sure you've moved on by now, but for those who stumble upon this question the new firebase console does provide an email confirmation feature. At firebase.google.com, simply click on Auth on the sidebar and then click the Email Templates tab and, if you have the email sign in method enabled, you can implement the email confirmation feature there where it says Email Address Verification.


text:
Q: Accurate floating-point computation of the sum and difference of two products The difference of two products and the sum of two products are two primitives found in a variety of common computations. diff_of_products (a,b,c,d) := ab - cd and sum_of_products(a,b,c,d) := ab + cd are closely-related companion functions that differ only by the sign of some of their operands. Examples for the use of these primitives are:
Computation of a complex multiplication with x = (a + i b) and y = (c + i d):
x*y = diff_of_products (a, c, b, d) + i sum_of_products (a, d, b, c)
Computation of the determinant of a 2x2 matrix: diff_of_products (a, d, b, c):
| a  b |
| c  d |

In a right-angle triangle computation of the  length of the opposite cathesus from the hypothenuse h and adjacent cathetus a: diff_of_products (h, h, a, a)
Computation of the two real solutions of a quadratic equation with positive discriminant:
q = -(b + copysign (sqrt (diff_of_products (b, b, 4a, c)), b)) / 2
x0 = q / a
x1 = c / q
Computation of a 3D cross product a = b ⨯ c:
ax = diff_of_products (by, cz, bz, cy)
ay = diff_of_products (bz, cx, bx, cz)
az = diff_of_products (bx, cy, by, cx)
When computing with IEEE-754 binary floating-point formats, besides obvious issues with potential overflow and underflow, naive implementations of either function can suffer from catastrophic cancellation when the two products are similar in magnitude but of opposite signs for sum_of_products() or same sign for diff_of_products().
Focusing only on the accuracy aspect, how can one implement these functions robustly in the context of IEEE-754 binary arithmetic? The availability of fused multiply-add operations can be assumed, as this operation is supported by most modern processor architectures and exposed, via standard functions,  in many programming languages. Without loss of generality, discussion can be restricted to single precision (IEEE-754 binary32) format for ease of exposition and testing.

A: The utility of the fused-multiply add (FMA) operation in providing protection against subtractive cancellation stems from the participation of the full double-width product in the final addition. To my knowledge, the first publicl record of its utility for accurately and robustly computing the solutions of quadratic equations are two sets of informal notes by renowned floating-point expert William Kahan:
William Kahan, "Matlab's Loss is Nobody's Gain". August 1998, revised July 2004 (online)
William Kahan, "On the Cost of Floating-Point Computation Without Extra-Precise Arithmetic". November 2004 (online)
The standard work on numerical computing by Higham was the first in which I encountered Kahan's algorithm applied to the computation of the determinant of a 2x2 matrix (p. 65):
Nicholas J. Higham, "Accuracy and Stability of Numerical Algorithms", SIAM 1996
A different algorithm for the computation of ab+cd, also based on FMA, was published by three Intel researchers in the context of Intel's first CPU with FMA support, the Itanium processor (p. 273):
Marius Cornea, John Harrison, and Ping Tak Peter Tang: "Scientific Computing on Itanium-based Systems." Intel Press 2002
In recent years, four papers by French researchers examined both algorithms in detail and provided error bounds with mathematical proofs. For binary floating-point arithmetic, provided there is no overflow or underflow in intermediate computation, the maximum relative error of both Kahan's algorithm and the Cornea-Harrison-Tang (CHT) algorithm were shown to be twice the unit round-off asymptotically, that is, 2u. For IEEE-754 binary32 or single precision this error bound is 2-23 and for IEEE-754 binary64 or double precision this error bound is 2-52.
Furthermore it was shown that the error in Kahan's algorithm is at most 1.5 ulps for binary floating-point arithmetic. From the literature I am not aware of an equivalent result, that is, a proven ulp error bound, for the CHT algorithm. My own experiments using the code below suggest an error bound of 1.25 ulp.
Sylvie Boldo, "Kahan's algorithm for a correct discriminant computation at last formally proven",
IEEE Transactions on Computers, Vol. 58, No. 2, February 2009, pp. 220-225 (online)
Claude-Pierre Jeannerod, Nicolas Louvet, and Jean-Michel Muller, "Further Analysis of Kahan's Algorithm for the Accurate Computation of 2x2 Determinants", Mathematics of Computation, Vol. 82, No. 284, Oct. 2013, pp. 2245-2264 (online)
Jean-Michel Muller, "On the Error of Computing ab+cd using Cornea, Harrison and Tang's Method", ACM Transactions on Mathematical Software, Vol. 41, No.2, January 2015, Article 7 (online)
Claude-Pierre Jeannerod, "A Radix-Independent Error Analysis of the Cornea-Harrison-Tang Method", ACM Transactions on Mathematical Software Vol. 42, No. 3, May 2016, Article 19 (online)
While Kahan's algorithm requires four floating-point operations, two of which are FMAs, the CHT algorithm requires seven floating-point operations, two of which are FMAs. I constructed the test framework below to explore what other trade-offs may exist. I experimentally confirmed the bounds from the literature on the relative error of both algorithms and the ulp error of Kahan's algorithm. My experiments indicate that the CHT algorithm provides a smaller ulp error bound of 1.25 ulp, but that it also produces incorrectly-rounded results at roughly twice the rate of Kahan's algorithm.
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include <float.h>
#include <math.h>

#define TEST_SUM  (0)  // function under test. 0: a*b-c*d; 1: a*b+c*d
#define USE_CHT   (0)  // algorithm. 0: Kahan; 1: Cornea-Harrison-Tang

/*
  Compute a*b-c*d with error <= 1.5 ulp. Maximum relative err = 2**-23

  Claude-Pierre Jeannerod, Nicolas Louvet, and Jean-Michel Muller,
  "Further Analysis of Kahan's Algorithm for the Accurate Computation
  of 2x2 Determinants", Mathematics of Computation, Vol. 82, No. 284,
  Oct. 2013, pp. 2245-2264
*/
float diff_of_products_kahan (float a, float b, float c, float d)
{
    float w = d * c;
    float e = fmaf (c, -d, w);
    float f = fmaf (a, b, -w);
    return f + e;
}

/*
  Compute a*b-c*d with error <= 1.25 ulp (?). Maximum relative err = 2**-23

  Claude-Pierre Jeannerod, "A Radix-Independent Error Analysis of the
  Cornea-Harrison-Tang Method", ACM Transactions on Mathematical Software
  Vol. 42, No. 3, Article 19 (May 2016).
*/
float diff_of_products_cht (float a, float b, float c, float d)
{
    float p1 = a * b;
    float p2 = c * d;
    float e1 = fmaf (a, b, -p1);
    float e2 = fmaf (c, -d, p2);
    float r = p1 - p2;
    float e = e1 + e2;
    return r + e;
}

/*
  Compute a*b+c*d with error <= 1.5 ulp. Maximum relative err = 2**-23

  Jean-Michel Muller, "On the Error of Computing ab+cd using Cornea,
  Harrison and Tang's Method", ACM Transactions on Mathematical Software,
  Vol. 41, No.2, Article 7, (January 2015)
*/
float sum_of_products_kahan (float a, float b, float c, float d)
{
    float w = c * d;
    float e = fmaf (c, -d, w);
    float f = fmaf (a, b, w);
    return f - e;
}

/*
  Compute a*b+c*d with error <= 1.25 ulp (?). Maximum relative err = 2**-23

  Claude-Pierre Jeannerod, "A Radix-Independent Error Analysis of the
  Cornea-Harrison-Tang Method", ACM Transactions on Mathematical Software
  Vol. 42, No. 3, Article 19 (May 2016).
*/
float sum_of_products_cht (float a, float b, float c, float d)
{
    float p1 = a * b;
    float p2 = c * d;
    float e1 = fmaf (a, b, -p1);
    float e2 = fmaf (c, d, -p2);
    float r = p1 + p2;
    float e = e1 + e2;
    return r + e;
}

// Fixes via: Greg Rose, KISS: A Bit Too Simple. http://eprint.iacr.org/2011/007
static unsigned int z=362436069,w=521288629,jsr=362436069,jcong=123456789;
#define znew (z=36969*(z&0xffff)+(z>>16))
#define wnew (w=18000*(w&0xffff)+(w>>16))
#define MWC  ((znew<<16)+wnew)
#define SHR3 (jsr^=(jsr<<13),jsr^=(jsr>>17),jsr^=(jsr<<5)) /* 2^32-1 */
#define CONG (jcong=69069*jcong+13579)                     /* 2^32 */
#define KISS ((MWC^CONG)+SHR3)

typedef struct {
    double y;
    double x;
} dbldbl;

dbldbl make_dbldbl (double head, double tail)
{
    dbldbl z;
    z.x = tail;
    z.y = head;
    return z;
}

dbldbl add_dbldbl (dbldbl a, dbldbl b) {
    dbldbl z;
    double t1, t2, t3, t4, t5;
    t1 = a.y + b.y;
    t2 = t1 - a.y;
    t3 = (a.y + (t2 - t1)) + (b.y - t2);
    t4 = a.x + b.x;
    t2 = t4 - a.x;
    t5 = (a.x + (t2 - t4)) + (b.x - t2);
    t3 = t3 + t4;
    t4 = t1 + t3;
    t3 = (t1 - t4) + t3;
    t3 = t3 + t5;
    z.y = t4 + t3;
    z.x = (t4 - z.y) + t3;
    return z;
}

dbldbl sub_dbldbl (dbldbl a, dbldbl b)
{
    dbldbl z;
    double t1, t2, t3, t4, t5;
    t1 = a.y - b.y;
    t2 = t1 - a.y;
    t3 = (a.y + (t2 - t1)) - (b.y + t2);
    t4 = a.x - b.x;
    t2 = t4 - a.x;
    t5 = (a.x + (t2 - t4)) - (b.x + t2);
    t3 = t3 + t4;
    t4 = t1 + t3;
    t3 = (t1 - t4) + t3;
    t3 = t3 + t5;
    z.y = t4 + t3;
    z.x = (t4 - z.y) + t3;
    return z;
}

dbldbl mul_dbldbl (dbldbl a, dbldbl b)
{
    dbldbl t, z;
    t.y = a.y * b.y;
    t.x = fma (a.y, b.y, -t.y);
    t.x = fma (a.x, b.x, t.x);
    t.x = fma (a.y, b.x, t.x);
    t.x = fma (a.x, b.y, t.x);
    z.y = t.y + t.x;
    z.x = (t.y - z.y) + t.x;
    return z;
}

double prod_diff_ref (float a, float b, float c, float d)
{
    dbldbl t = sub_dbldbl (
        mul_dbldbl (make_dbldbl ((double)a, 0), make_dbldbl ((double)b, 0)),
        mul_dbldbl (make_dbldbl ((double)c, 0), make_dbldbl ((double)d, 0))
        );
    return t.x + t.y;
}

double prod_sum_ref (float a, float b, float c, float d)
{
    dbldbl t = add_dbldbl (
        mul_dbldbl (make_dbldbl ((double)a, 0), make_dbldbl ((double)b, 0)),
        mul_dbldbl (make_dbldbl ((double)c, 0), make_dbldbl ((double)d, 0))
        );
    return t.x + t.y;
}

float __uint32_as_float (uint32_t a)
{
    float r;
    memcpy (&r, &a, sizeof r);
    return r;
}

uint32_t __float_as_uint32 (float a)
{
    uint32_t r;
    memcpy (&r, &a, sizeof r);
    return r;
}

uint64_t __double_as_uint64 (double a)
{
    uint64_t r;
    memcpy (&r, &a, sizeof r);
    return r;
}

static double floatUlpErr (float res, double ref)
{
    uint64_t i, j, err;
    int expoRef;

    /* ulp error cannot be computed if either operand is NaN, infinity, zero */
    if (isnan(res) || isnan (ref) || isinf(res) || isinf (ref) ||
        (res == 0.0f) || (ref == 0.0f)) {
        return 0.0;
    }
    /* Convert the float result to an "extended float". This is like a float
       with 56 instead of 24 effective mantissa bits.
    */
    i = ((uint64_t)__float_as_uint32(res)) << 32;
    /* Convert the double reference to an "extended float". If the reference is
       >= 2^129, we need to clamp to the maximum "extended float". If reference
       is < 2^-126, we need to denormalize because of float's limited exponent
       range.
    */
    expoRef = (int)(((__double_as_uint64(ref) >> 52) & 0x7ff) - 1023);
    if (expoRef >= 129) {
        j = (__double_as_uint64(ref) & 0x8000000000000000ULL) |
            0x7fffffffffffffffULL;
    } else if (expoRef < -126) {
        j = ((__double_as_uint64(ref) << 11) | 0x8000000000000000ULL) >> 8;
        j = j >> (-(expoRef + 126));
        j = j | (__double_as_uint64(ref) & 0x8000000000000000ULL);
    } else {
        j = ((__double_as_uint64(ref) << 11) & 0x7fffffffffffffffULL) >> 8;
        j = j | ((uint64_t)(expoRef + 127) << 55);
        j = j | (__double_as_uint64(ref) & 0x8000000000000000ULL);
    }
    err = (i < j) ? (j - i) : (i - j);
    return err / 4294967296.0;
}

int main (void)
{
    const float ULMT = sqrtf (FLT_MAX) / 2; // avoid overflow
    const float LLMT = sqrtf (FLT_MIN) * 2; // avoid underflow
    const uint64_t N = 1ULL << 38;
    double ref, ulp, relerr, maxrelerr = 0, maxulp = 0;
    uint64_t count = 0LL, incorrectly_rounded = 0LL;
    uint32_t ai, bi, ci, di;
    float af, bf, cf, df, resf;

#if TEST_SUM
    printf ("testing a*b+c*d ");
#else
    printf ("testing a*b-c*d ");
#endif // TEST_SUM
#if USE_CHT
    printf ("using Cornea-Harrison-Tang algorithm\n");
#else
    printf ("using Kahan algorithm\n");
#endif

    do {
        do {
            ai = KISS;
            af = __uint32_as_float (ai);
        } while (!isfinite(af) || (fabsf (af) > ULMT) || (fabsf (af) < LLMT));
        do {
            bi = KISS;
            bf = __uint32_as_float (bi);
        } while (!isfinite(bf) || (fabsf (bf) > ULMT) || (fabsf (bf) < LLMT));
        do {
            ci = KISS;
            cf = __uint32_as_float (ci);
        } while (!isfinite(cf) || (fabsf (cf) > ULMT) || (fabsf (cf) < LLMT));
        do {
            di = KISS;
            df = __uint32_as_float (di);
        } while (!isfinite(df) || (fabsf (df) > ULMT) || (fabsf (df) < LLMT));
        count++;
#if TEST_SUM
#if USE_CHT
        resf = sum_of_products_cht (af, bf, cf, df);
#else // USE_CHT
        resf = sum_of_products_kahan (af, bf, cf, df);
#endif // USE_CHT
        ref = prod_sum_ref (af, bf, cf, df);
#else // TEST_SUM
#if USE_CHT
        resf = diff_of_products_cht (af, bf, cf, df);
#else // USE_CHT
        resf = diff_of_products_kahan (af, bf, cf, df);
#endif // USE_CHT
        ref = prod_diff_ref (af, bf, cf, df);
#endif // TEST_SUM
        ulp = floatUlpErr (resf, ref);
        incorrectly_rounded += ulp > 0.5;
        relerr = fabs ((resf - ref) / ref);
        if ((ulp > maxulp) || ((ulp == maxulp) && (relerr > maxrelerr))) {
            maxulp = ulp;
            maxrelerr = relerr;
            printf ("%13llu %12llu ulp=%.9f a=% 15.8e b=% 15.8e c=% 15.8e d=% 15.8e res=% 16.6a ref=% 23.13a relerr=%13.9e\n",
                    count, incorrectly_rounded, ulp, af, bf, cf, df, resf, ref, relerr);
        }
    } while (count <= N);

    return EXIT_SUCCESS;
}


text:
Q: Use a PWM or other controller for 24V/500W application I've been gaining understanding about using PWM for a motor speed controller. I'm developing a project (go kart) that uses a 24V DC starter motor and I want to build a motor speed controller that is somewhat rudimentary/simple.
Is it possible to utilize Arduino technology or some kind of PWM connected to a relay that switches the power supply on and off to the motor at the cycle speed that will act as a 'throttle'?
Or, is there a rudimentary means of controlling the motor speed in 4 or 5 stages (less elegant but equally as effective...)?
Any links to other resources or advice is greatly appreciated.

A: You've got the right idea with PWM, but relays are totally inappropriate as the switches in this case.  You want to run the PWM at least a fw 100 Hz, and that would be slow.  That's fast enough for the motor to work well enough, but could cause audible whine.  That is why most motor controllers pulse at 25-30 kHz, just past the audio range.
Probably the best way to switch the voltage to your motor is with a low side FET, or perhap several in parallel.  Use good FET gate drivers intended for that purpose, and control those from the PWM output of your microcontroller.
A starter motor is not really a good fit for what you are trying to do, but you should be able to get some results like you expect.  In general, start motors take a lot of current, have high torque, but aren't meant for sustained operation in several ways.


text:
Q: Is it reasonable to change the input shape for a trained convolutional neural network I've seen a number of super-resolution networks that seem to imply that it's fine to train a network on inputs of (x,y,d) but then pass in images of arbitrary sizes into a model for prediction, that in Keras for example is specified with the placeholder values (None,None,3) and will accept any size.
for example https://github.com/krasserm/super-resolution is trained on inputs of 24x24x3 but accepts arbitrary sized images for resize, the demo code using 124x118x3.
Is this a sane practice? Does the network when given a larger input simply slide a window over it applying the same weights as it learnt on the smaller size image?

A: There will be absolutely no problem with the convolutions, they will work exactly as they are expected to, with the same weights, same kernel size, etc. etc.
The only possible problem is: the model may not have learned the new scale of your images (because it has never seen this scale before) and may give you poor results.
On the other hand, the model could be trained with many sizes/scales, becoming more robust to variation.

There will be a problem with Flatten, Reshape, etc.
Only GlobalMaxPooling2D and GlobalAveragePooling2D will support different sizes.

A: Your guess is correct. Convolutional layers learn to distinguish features at the scale of their kernel, not at the scale of the image as a whole. A layer with a 3x3 kernel will learn to identify a feature up to 3x3 pixels large and will be able to identify that feature in an image whether the image is itself 3x3, 100x100, or 1080x1920.


text:
Q: Java image library - turn grid image into array If I have an image of a table of boxes, with some coloured in, is there an image processing library that can help me turn this into an array?
Thanks

A: You can use a thresholding function to binarize the image into dark/light pixels so dark pixels are 0 and light ones are 1.
Then you would want to remove image artifacts using dilation and erosion functions to remove noise (all these are well defined on Wikipedia).
Finally if you know where the boxes are, you can just get the value in the center of each box to determine the array value, or possibly use an area near the center and take the prevailing value (i.e. more 0's is a filled in square, more 1's is and empty square).
If you are scanning these boxes and there is a lot of variation in the position of the boxes, you will have to perform some level of image registration using known points, or fiducials.
As far as what tools to use to do this, I'd recommend first trying this manually using a tool like ImageJ, which has a UI and can also be used programatically since it is written all in Java.
Other good libraries for this include OpenCV and the Java Advanced Imaging API.
Your results will definitely vary depending on the input images and how consistenly lit and positioned they are.
The best way to see how it will do for your data is to try applying these processing steps manually to see where your threshold value should be, how much dilating/eroding you need to get consistent results.


text:
Q: Use SQL formula from different table I have a formula:
COUNT(T1.ID)/COUNT(T2.ID) * 100

I need to get the answer:
select count(t1.id)/count(t2.id)*100 FROM T1
  inner join T2  on T1.id=T1.id
WHERE T1.Status=0

I need to divide the count of T1 where T1.Status = 0 with the count
of all the records in T2 and multiply it by 100.
I tried this but the answer is wrong.  What is the correct way to do it?

A:
I need to divide the count of the records from T1 where T1.Status = 0 with the count of all the records in T2, and multiply it by 100.

SELECT 100 * COUNT(t1.id) / (SELECT COUNT(*) FROM T2) AS percent
  FROM T1
 WHERE T1.Status = 0;

A: Your join appears to be incorrect. Should it be:
select count(t1.id)/count(t2.id)*100 FROM T1
  inner join T2  on T1.id=**T2**.id
WHERE T1.Status=0

A: Your INNER JOIN was slightly wrong (you were using T1.ID = T1.ID, which is always true except when T1.ID is null). Fixing that should work.
select count(t1.id)/count(t2.id)*100 FROM T1
   inner join T2
       on T1.id = T2.id
WHERE t1.Status = 0

You should also note that the result for this should always be 100, except when there is no items in T1 with a Status = 0 (in this case you will get a divide by zero error). This is because you are performing an INNER JOIN, so the number of rows from each table will always be the same as each other, the division will always equal 1.


text:
Q: Unsafe attempt to load URL Nodejs res.send I am trying to send xml via NodeJs. My code is
res.set('Content-Type', 'application/xml');
res.send(body);

But chrome says
Unsafe attempt to load URL http://localhost:3030/my-file.xml from frame with URL http://localhost:3030/my-file.xml. Domains, protocols and ports must match.

How can I fix this?

A: This doesn't work is due to a security concern that Chrome has blocked XML files from accessing local files in the same directory, while HTML files can access.
Workaround:
On Windows: from the command prompt run
C:\Users\USERNAME\AppData\Local\Google\Chrome\Application\chrome.exe --allow-file-access-from-files

(replacing USERNAME with your username)
On Ubuntu:
for chromium browser type
chromium-browser --allow-file-access-from-files

for google chrome
google-chrome --allow-file-access-from-files

Maybe you have to kill all running windows processes for chrome.exe in the windows task manager.


text:
Q: Do promises in AngularJS catch every exception/error? I've inherited a codebase at work that contains a dozen or so examples of the following pattern:
var promise = null;
try {
    promise = backendService.getResults(input);
}
catch (exception) {
    console.err(exception);
}
if (promise !== null) {
    promise.then(function (response) {
        // do stuff
    })
    .catch(function (error) {
        console.err(error);
    });
}

Where backendService is an Angular service that in turn calls a REST service through $http.
So here's my question: is that try/catch really necessary? Will there ever be any scenario where a particular error/exception is thrown that the promise's .catch fails to catch?
This has been the subject of a bit of debate on the team all morning, and the only resolution we've come up with is that we don't think it's necessary, but (a) changing it breaks the tests that were written alongside it (which would also need to be changed), and (b) well... it's defensive coding, right? It's not a Bad Thing.
The merits of actually bothering to refactor it into oblivion when there are more important things to do aren't what I'm asking about, though. I just want to know if it's a reasonable pattern when promises are being passed around like this (in AngularJS specifically, if that makes a difference), or just paranoia.

A:
Do promises in AngularJS catch every exception/error?

No. Only exceptions that are thrown from inside then/catch callbacks are automatically caught. All errors happening outside of them will need to be handled explicitly.

Will there ever be any scenario where a particular error/exception is thrown that the promise's .catch fails to catch?

Yes. That backendService.getResults(input) call might not return a promise, but it can throw an exception. Or it doesn't even get that far when backendService is null, and you'll get a ReferenceError or .getResults is not a function and you'll get a TypeError.

is that try/catch really necessary?

Not really. In the latter case, that your code has a grave mistake, you probably don't care to throw and crash. The former case, that backendService.getResults(input) throws, is heavily despised. Asynchronous functions should never throw but only return promises - exactly for the reason that you don't have to write two error handling statements then.

well... it's defensive coding, right? It's not a Bad Thing.

Yeah, pretty much. But it is questionable here. A synchronous exceptions is really unexpected here, not just a service whose failure can be handled. The logging message in the catch block should signify that.
Notice that it also isn't defensive enough. It doesn't catch the probably more likely mistake where getResults() does return, but something that is not a promise. Calling .then() on that might throw. Similarly, the if (promise !== null) is dubious, as it hides when null is returned erroneously (we really could need try-catch-else here).

A:
is that try/catch really necessary?

Not really. As long as your backendService.getResults() returns a promise. Like return $http(...)

Will there ever be any scenario where a particular error/exception is
  thrown that the promise's .catch fails to catch?

I don't think so, since any error will be a rejected promise, it will fall into your .catch() handler

well... it's defensive coding, right? It's not a Bad Thing.

It depends... Javascript try/catch is has some performance issues. So if you're using just for the sake of making sure, you could remove it :)
Take a further look at try-catch discussion here if you wish: Javascript Try-Catch Performance Vs. Error Checking Code


text:
Q: Missing libtiff4 while installing Canon MX410 driver on Ubuntu 21.04 I'm really excited  about uing Ubuntu as my main OK. But I still have a couple of things to resolve before I can do that. The first one is to be able to connect to my Canon MX410 printer.  I have found the installation drivers but there was a few dependencies that failed.  So far I was able to find them all but one:  libtiff4
I found several things on the net explaining how to install them but they all failed.  The one that I think I should be using is:
sudo apt install libtiff4
But it cannot find that library.
I installed libtiff5 but the installation driver is still expecting the libtiff4.
I also tried;
sudo apt-get install libtiff4
that failed to find the library.
also tried the libtiff4-dev without success.
I've been on this case for several days now so I can't really tell you everything I tried but my guess is that I tried them all. This is why I'm here now.
Anyboday know what else I should try?

A: That did it.  Thank you Knud Larsen for the link to the libtiff4.  After installing that library, I was finally able to print.