text:
Q: How do you load an external image with SDWebImage? I'm trying to use an external image as a tab bar button. I've seen this with few apps so I thought I'd give it a go.
HackingWithWift mentioned using SDWebImage
import SDWebImage
import UIKit

class ViewController {

    let imageView = UIImageView()
    var tabBar = UITabBar()

    // viewDidLoad

    imageView.sd_setImage(with: URL(string: "https://randomuser.me/api/portraits/men/32.jpg"), placeholderImage: UIImage(named: "tablogo")) { image, error, foo, url in

        print(image, error, foo, url)

        // Assume no errors!

        let img = self.resizeImage(image: image!, newWidth: 25)

        let itemAvatar = UITabBarItem(title: "Profile", image: img, selectedImage: img)

        self.tabBar.frame = CGRect(x: 0, y: self.view.frame.height - 75, width: self.view.frame.width, height: 50)
        self.tabBar.items = [self.itemAvatar]
        self.view.addSubview(self.tabBar)
    }
}

Nothing happened so I thought I needed to resize the image first so I found this answer.
func resizeImage(image: UIImage, newWidth: CGFloat) -> UIImage {
    let scale = newWidth / image.size.width
    let newHeight = image.size.height * scale
    UIGraphicsBeginImageContext(CGSizeMake(newWidth, newHeight))
    image.draw(in: CGRectMake(0, 0, newWidth, newHeight))
    let newImage = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()

    return newImage!
}

When the view loaded, my tab bar is shown with a square and no image.

How can I resolve this?

A: Try to add RenderingMode to your image
UIImage(named: "tablogo")?.withRenderingMode(.alwaysOriginal)


text:
Q: Can i have multiple select but only return one result set If I have multiple selects like so:
select * from A where A.name = 'linköping'

IF @@ROWCOUNT = 0
begin
    select * from A where A.amount = 45
end

...I get 1 result set if the first select returns stuff. But if it runs the second, I get two result sets; the first with no rows and the second with some rows.
Is there a way to only return the second result set if the second select is run ?
I write code like this because of Andrey Gordeev's answer to this post: Can you have if-then-else logic in SQL?
(MSSQL 2000)
Thanks!

A: You will need to prevent the first select by checking if you will get any results back before running the select.
For example:
IF EXISTS (SELECT 1 FROM A WHERE A.name = 'linköping')
BEGIN
    SELECT * FROM A WHERE A.name = 'linköping'
END
ELSE
BEGIN
    SELECT * FROM A WHERE A.amount = 45
END

A: This will work with IF-ELSE Logic. [Tested]
DECLARE @count as int
set @count = (SELECT count(1) from A where A.name = 'linköping')
if (@count = 0)
BEGIN
    select * from A where A.amount = 45
END
ELSE
BEGIN
select * from A where A.name = 'linköping'
END

A: No it is not possible The returning results are depending on number of select statements.
If you want to do the single select follow @RB or @Jwalin Shah solution.

A: Try this
IF @@ROWCOUNT = 0
BEGIN
    select * from A where A.amount = 45
END
ELSE
BEGIN
    select * from A where A.name = 'linköping'
END

redpajama_set_name: RedPajamaStackExchange


text:
Q: How do I hide rows in a Google spreadsheet using a script based on a character in a column? I'm using the below script to hide all rows with a value of "1" in column B.
function myfunction () {
function onOpen() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getSheetByName("CSSMaster");
  var maxRows = sheet.getMaxRows();

  //show all the rows
  sheet.showRows(1, maxRows);

  //get data from clumn B
  var data = sheet.getRange('B:B').getValues();

  //iterate over all rows
  for(var i=0; i< data.length; i++){
    //compare first character, if 1, then hide row
    if(data[i][0].charAt(0) == '1'){
      sheet.hideRows(i+1);
    }
  }
}
}

I go to my spreadsheet and enter the following: =myfunction(B:B) , I see "thinking" but nothing happens. What am I doing wrong? (I'm VERY new to Google scripts and am guessing this is a very basic error.)

A: Your instincts are right - it's a very basic error. First, make sure that you're actually running the code you intend to.
In this example, you've got a function inside a function. When you invoke myFunction() from the spreadsheet, execution will begin but won't find any code to run. Because onOpen() is enclosed in myFunction(), but there is no call in myFunction() to onOpen(), there's nothing to do.
Sort that out - you probably just need to get rid of the declaration and closing brace for onOpen().
Next, you're passing a 2-dimensional array of values when you invoke myFunction(B:B), but you have no parameter handing in the function. (You retrieve the values explicitly with getRange('B:B').getValues().)
General advice: learn some JavaScript (I recommend CodeAcademy), and try your hand at some of the Google Apps Script tutorials. With the competence and confidence from those, you should have no problem getting this working on your own.


text:
Q: How do I set main URL a priority of 1.0 and subdirectory urls priority of 0.5 in sitemap.xml How can I make the root index in the sitemap a priority of 1.0 and the rest of the sub directory files a priority of 0.5?
I'm using this php code to generate my sitemap on the fly when page is accessed.
As it is right now, it gives a priority of whatever the set value is
$url -> appendChild( $priority = $xml->createElement('priority', '0.5') );
for every url in the sitemap like in this example:

PHP code that creates sitemap:
<?
$ignore = array( 'images', 'css', 'includes', 'cgi-bin', 'xml-sitemap.php' );

  function getFileList($dir, $recurse=false) {
  global $ignore;

    $retval = array();

    // open pointer to directory and read list of files
    $d = @dir($dir) or die("getFileList: Failed opening directory $dir for reading");
    while ( false !== ( $entry = $d->read() ) ) {

        // Check if this dir needs to be ignored, if so, skip it.
        if ( in_array( utf8_encode( $entry ), $ignore ) )
            continue;

      // skip hidden files
      if($entry[0] == ".") continue;
      if(is_dir("$dir$entry")) {
        $retval[] = array(
          "name" => "$dir$entry/",
          "type" => filetype("$dir$entry"),
          "size" => 0,
          "lastmod" => filemtime("$dir$entry")
        );
        if($recurse && is_readable("$dir$entry/")) {
          $retval = array_merge($retval, getFileList("$dir$entry/", true));
        }
      } elseif(is_readable("$dir$entry")) {
        $retval[] = array(
          "name" => str_replace('./','/', $dir),
          "type" => mime_content_type("$dir$entry"),
          "size" => filesize("$dir$entry"),
          "lastmod" => filemtime("$dir$entry")
        );
      }
    }
    $d->close();

    return $retval;
  }

  $dirlist = getFileList("./", true);

    // sitemap creation
    $time  = time();
    $sitemap = $_SERVER['DOCUMENT_ROOT'].'/sitemap.xml';
    if ($time - filemtime($sitemap) >= 1) { // 1 days

        $xml = new DomDocument('1.0', 'utf-8');
        $xml->formatOutput = true;

        // creating base node
        $urlset = $xml->createElement('urlset');
        $urlset -> appendChild(
            new DomAttr('xmlns', 'http://www.sitemaps.org/schemas/sitemap/0.9')
        );

            // appending it to document
        $xml -> appendChild($urlset);

        // building the xml document with your website content
        foreach($dirlist as $file)
        {
        if($file['type'] != 'text/x-php') continue;
            //Creating single url node
            $url = $xml->createElement('url');

            //Filling node with entry info
            $url -> appendChild( $xml->createElement('loc', 'http://www.airsahara.in'.$file['name']) );
            $url -> appendChild( $lastmod = $xml->createElement('lastmod', date('Y-m-d', $file['lastmod'])) );
            $url -> appendChild( $changefreq = $xml->createElement('changefreq', 'monthly') );
            $url -> appendChild( $priority = $xml->createElement('priority', '0.5') );

            // append url to urlset node
            $urlset -> appendChild($url);

        }
        $xml->save($sitemap);
    } // if time

    ?>

A: I'm answering my own question because I figured it out.
I simply did this. I took this line of code and expanded it with an if and else statement.
went from this
$url -> appendChild( $priority = $xml->createElement('priority', '0.5') );

to this
    if($file['name'] != '/') {
    $url -> appendChild( $priority = $xml->createElement('priority', '0.5') );
    } else {
        $url -> appendChild( $priority = $xml->createElement('priority', '1.0') );
    }

Update: As per the comments of hakre
        if ($file['name'] != '/') {
            $p = '0.5';
            } else {
                $p = '1.0';
            }
        $url -> appendChild( $priority = $xml->createElement('priority', $p) );

And this would be the shorthand of the if else statement
        $file['name'] != '/' ? $p = '0.5' : $p = '1.0';
        $url -> appendChild( $priority = $xml->createElement('priority', $p) );


text:
Q: Is it possible to apply group membership when authenticating a user with django-mama-cas and django-cas-ng? I am using django-mama-cas (2.4.0) and django-cas-ng (3.5.10) to manage user authorisation (single sign on, single log off, group membership) across a few django (1.11) projects. I am able to apply user attributes  (first_name, last_name, email address) from the cas server to the cas-ng clients using
the callback 'mama_cas.callbacks.user_name_attributes' in mama-cas and setting CAS_APPLY_ATTRIBUTES_TO_USER = True on my cas-ng clients.
On my mama-cas server, I also add the user to a number of groups (snippet below) which I want to then apply to the users on the cas-ng clients.
group = Group.objects.get(name=groupname)
user.groups.add(group)

However, when I try using the callback 'mama_cas.callbacks.user_model_attributes' in mama-cas none of the group memberships are applied to my clients (I check this via the admin interface and via the django shell).
Is applying group membership from mama-cas to cas-ng possible or am I doing something wrong? If it's not possible my next best idea was to create some boolean custom user attributes, i.e. user.is_member_groupA etc but would welcome advice.
Thanks in advance
Update 1:
From the mama-cas callbacks.py I see that only fields within user._meta_fields are added to the dict of attributes returned and that user.groups etc are not included here. From this I presume that group memberships are not intended to be applied from mama-cas to cas-ng as I am trying?


text:
Q: Append new sub document to an array in the main struct I have the following go structs in my MongoDB database:
type Station struct {
    ID          bson.ObjectId `bson:"_id" json:"id"`
    Name        string        `bson:"name" json:"name"`
    Sensors     []Sensor `bson:"sensors" json:"sensors"`
}

type Sensor struct {
    ID             bson.ObjectId `bson:"_id" json:"id"`
    Type string `  bson:"type" json:"type"`
    Value float64 `bson:"value" json:"value"`
}

When I make a POST request at the endpoint localhost:3000/stations/<IDofTheStation/sensors, it should add a new sensor to the specified station.
Currently I have this code
func AddSensorToStation(w http.ResponseWriter, r *http.Request) {
    defer r.Body.Close()
    params := mux.Vars(r)

    station, err := dao.FindById(params["id"])
    if err != nil {
        respondWithError(w, http.StatusBadRequest, "Invalid Station ID")
        return
    }

    sensor := Sensor{Type: "test"}

    station.Sensors = append(station.Sensors, sensor)

    if err := dao.Update(station); err != nil {
        respondWithError(w, http.StatusInternalServerError, err.Error())
        return
    }

    respondWithJson(w, http.StatusOK, station)
}

The problem is that it does not automatically generate an ID for the new sensor that I want to add, thus it throws the error "ObjectIDs must be exactly 12 bytes long (got 0)"
What is the best way to append a new Sensor instance to the Sensors array where the DB generates the id for the sensor?

A: MongoDB won't ever generate an ID for a sub-document on the server-side.
Do you really need the ID on the sensor? MongoDB won't complain about a sub-document not having an ID (or its ID being in a wrong format) because a subdocument can have an arbitrary structure - so it can easily exist without an ID.
If you do need the ID for some reason then you can, of course, create one on the client side:
sensor.ID := bson.NewObjectId()


text:
Q: How to clean up after failed Intern functional tests? I have some functional tests that run using Intern (3) and the last step in the test is to do some cleanup, including clearing localStorage on the remote browser, and switching back to the original window by storing the window handle right away and switching back to it before the tests end (so any subsequent tests don't fail because they're trying to run on a closed window if the previous test ended on a different one). However if some chaijs assertions fail in a .then() the cleanup code at the end gets skipped. Is there a better way to do cleanup for functional tests that will still get run even when some assertions fail?
this.leadfoot.remote
    .get(require.toUrl(url))
    .execute(function() { return document.querySelector('#welcome').textContent})
    .then(welcome => {
        assert.equal(welcome, 'hello world', 'properly greeted');
    })
    .execute(function() {
        localStorage.clear();
    });

If the assertion fails it'll never clear localStorage at the end and if the next test that runs expects localStorage to be empty it will fail too. Is there a better way to clean up after a functional test?

A: Use an afterEach method.
afterEach() {
    return this.remote
        .execute(function () {
            localStorage.clear();
        });
},

'my test'() {
    return this.remote
        .get(...)
        .execute(...)
        .then(welcome => {
            assert.equal(welcome, ...);
        });
}

A: in our project we do it like this:
afterEach: function() {
        var command = this.remote;
        if(intern.variables.currentCase && !intern.variables.currentCase.hasPassed) {
            command = command.execute(function () {
               localStorage.clear();
            });
        }
        return command;
    },

and local Storage.clear() will be executed only if the test has failed:


text:
Q: SQL - Grouping with order condition I am new with SQL and have some data in table and want to make grouping based on column CLASS and STATUS with condition based on the value in both column. It will group based on the highest order
The Table shown below
Scenario 1
Table Source :

ID
Class
Status

001
Platinum
ACTIVE

001
Gold
ACTIVE

001
Silver
ACTIVE

001
Regular
ACTIVE

Output after Grouping:

ID
Class
Status

001
Platinum
ACTIVE

Scenario 2
Table Source :

ID
Class
Status

001
Gold
ACTIVE

001
Silver
INACTIVE

001
Regular
INACTIVE

Output after Grouping:

ID
Class
Status

001
Gold
ACTIVE

So basically the grouping will be determined by the value of CLASS and Status
For CLASS the order of grouping is
Platinum > Gold > Silver > Regular
For Status the order of grouping is
ACTIVE > INACTIVE
Is there any way to do this?
Thanks

A: you can use sql case statement to define the order for each class and subject. then sort the resulting table as subquery.
select t1.ID, t1.class, t1.Status from (
    select ID, Class, Status (case when 'Platinum' then 1 when 'Gold' then 2 when 'Silver' then 3 else 4 end) as sort_order1,
        (case when 'active' then 1 else 2 end) as sort_order2
    from table1)
order by t1.sort_order1, t1.sort_order2


text:
Q: 400 bad request c# I have a little problem when i try to call a Web Service (Navision) it works with Postman but not with the code generate by him.
I create a project console in .Net Core 3.0 and the reference RestSharp (use in the code of Postman).
When i run the program i have always a
StatusCode: 400, ReasonPhrase: 'Bad Request', Version: 1.1, Content: System.Net.Http.HttpConnectionResponseContent, Headers:
{
  Server: Microsoft-HTTPAPI/2.0
  Date: Thu, 30 Jul 2020 15:48:44 GMT
  Content-Length: 0
}

I try with HttpClient but i have the same result.
There is my code :
var client = new RestClient("http://..../Codeunit/OrderIntegrationXML");
client.Timeout = -1;
var request = new RestRequest(Method.POST);
request.AddHeader("Accept-Encoding", "gzip,deflate");
request.AddHeader("Content-Type", "text/xml;charset=UTF-8");
request.AddHeader("SOAPAction", "urn:microsoft-dynamics-schemas/codeunit/OrderIntegrationXML:InsertOrderXMLWS");
request.AddHeader("Content-Length", "3445");
request.AddHeader("Host", "....");
request.AddHeader("Connection", "Keep-Alive");
request.AddHeader("Authorization", @"NTLM TlRMTVNTUAADAAAAGAAYAEAAAAD6APoAWAAAABgAGABSAQAACgAKAGoBAAAWABYAdAEAAAAAAACKAQAANQIIIDGc+rMQNjBw51iSNdthdYVdWjSNgaXiObFF1YN5hjakUOfgw7DmgQkBAQAAAAAAAPDxIMLFZdYBXVo0jYGl4jkAAAAAAgAYAEwARQBDAE8AUQBTAFAATwBSAFQASQBGAAEAEgBTAFIAVgBOAEEAVgBBAFMAMgAEACQAbABlAGMAbwBxAHMAcABvAHIAdABpAGYALgBsAG8AYwBhAGwAAwA4AFMAUgBWAE4AQQBWAEEAUwAyAC4AbABlAGMAbwBxAHMAcABvAHIAdABpAGYALgBsAG8AYwBhAGwABQAkAGwAZQBjAG8AcQBzAHAAbwByAHQAaQBmAC4AbABvAGMAYQBsAAcACAD13x3CxWXWAQAAAABMAEUAQwBPAFEAUwBQAE8AUgBUAEkARgBhAGQAbABsAGUAUwBPAEcARQBDAE8AUQBNADIAMAA0AA==");

request.AddParameter("text/xml;charset=UTF-8", "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:ord=\"urn:microsoft-dynamics-schemas/codeunit/OrderIntegrationXML\" xmlns:x62=\"urn:microsoft-dynamics-nav/xmlports/x62000\">\r\n   <soapenv:Header/>\r\n   <soapenv:Body>\r\n      <ord:InsertOrderXMLWS>\r\n         <ord:p_OriginType>?</ord:p_OriginType>\r\n         <ord:p_OriginOrderNo>?</ord:p_OriginOrderNo>\r\n         <ord:p_MappingSalesOrderImport TransferDate=\"?\" OriginType=\"?\" QueueLabel=\"?\">\r\n            <!--1 or more repetitions:-->\r\n            <x62:SalesOrder>\r\n               e\r\n               <x62:OriginOrderNumber>?</x62:OriginOrderNumber>\r\n               gero\r\n               <x62:Company>?</x62:Company>\r\n               cum\r\n               <x62:SellToCustomer>?</x62:SellToCustomer>\r\n               sonoras\r\n               <x62:BillToCustomer>?</x62:BillToCustomer>\r\n               aeoliam\r\n               <x62:ShipToCode>?</x62:ShipToCode>\r\n               quae\r\n               <!--1 or more repetitions:-->\r\n               <x62:YourReference>?</x62:YourReference>\r\n               ventos\r\n               <x62:ShipmentMethodCode>?</x62:ShipmentMethodCode>\r\n               verrantque\r\n               <x62:LocationCode>?</x62:LocationCode>\r\n               temperat\r\n               <x62:CurrencyCode>?</x62:CurrencyCode>\r\n               per\r\n               <!--1 or more repetitions:-->\r\n               <x62:TransportMethod>?</x62:TransportMethod>\r\n               turbine\r\n               <x62:SaleOrderType>?</x62:SaleOrderType>\r\n               circum\r\n               <x62:PreparationType>?</x62:PreparationType>\r\n               regemque\r\n               <x62:SalesPersonCode>?</x62:SalesPersonCode>\r\n               nimborum\r\n               <!--1 or more repetitions:-->\r\n               <x62:Comment>?</x62:Comment>\r\n               fremunt\r\n               <x62:DotationContractCode>?</x62:DotationContractCode>\r\n               foedere\r\n               <!--1 or more repetitions:-->\r\n               <x62:Lines>\r\n                  ferant\r\n                  <!--1 or more repetitions:-->\r\n                  <x62:Line>\r\n                     <x62:OriginOrderNumber>?</x62:OriginOrderNumber>\r\n                     <x62:OriginOrderLineNumber>0</x62:OriginOrderLineNumber>\r\n                     <x62:ItemNumber>?</x62:ItemNumber>\r\n                     <x62:SeriesNumber>?</x62:SeriesNumber>\r\n                     <x62:VariantCode>?</x62:VariantCode>\r\n                     <x62:RequestedDeliveryDate>0001-01-01</x62:RequestedDeliveryDate>\r\n                     <x62:Quantity>0</x62:Quantity>\r\n                     <x62:CustomerRateGroup>?</x62:CustomerRateGroup>\r\n                     <x62:TradeTermTypeName>?</x62:TradeTermTypeName>\r\n                     <x62:LineDiscount1>0</x62:LineDiscount1>\r\n                     <x62:LineDiscount2>0</x62:LineDiscount2>\r\n                     <x62:LineDiscount3>0</x62:LineDiscount3>\r\n                     <x62:LineDiscount4>0</x62:LineDiscount4>\r\n                     <x62:LineDiscount5>0</x62:LineDiscount5>\r\n                     <x62:OriginUnitPrice>0</x62:OriginUnitPrice>\r\n                     <!--Optional:-->\r\n                     <x62:JerseyNumber>?</x62:JerseyNumber>\r\n                  </x62:Line>\r\n                  profundum\r\n               </x62:Lines>\r\n               sceptra\r\n            </x62:SalesOrder>\r\n         </ord:p_MappingSalesOrderImport>\r\n      </ord:InsertOrderXMLWS>\r\n   </soapenv:Body>\r\n</soapenv:Envelope>", ParameterType.RequestBody);
IRestResponse responseZ = client.Execute(request);
Console.WriteLine(responseZ.Content);

Update : the request (catch with fiddler and with a light xml ) :
POST http://.../Codeunit/OrderIntegrationXML?wsdl HTTP/1.1
Accept-Encoding: gzip, deflate
SOAPAction: "urn:microsoft-dynamics-schemas/codeunit/OrderIntegrationXML:InsertOrderXMLWS"
Host: ...
Connection: Keep-Alive
Authorization: NTLM TlRMTVNTUAADAAAAGAAYAEAAAAD6APoAWAAAABgAGABSAQAACgAKAGoBAAAWABYAdAEAAAAAAACKAQAANQIIILBaGvPsioy+B4lYWuqIouke/Eu984yP0hKYh6dzm+imf4Y+Qy+QH8UBAQAAAAAAAKAjmmGaadYBHvxLvfOMj9IAAAAAAgAYAEwARQBDAE8AUQBTAFAATwBSAFQASQBGAAEAEgBTAFIAVgBOAEEAVgBBAFMAMgAEACQAbABlAGMAbwBxAHMAcABvAHIAdABpAGYALgBsAG8AYwBhAGwAAwA4AFMAUgBWAE4AQQBWAEEAUwAyAC4AbABlAGMAbwBxAHMAcABvAHIAdABpAGYALgBsAG8AYwBhAGwABQAkAGwAZQBjAG8AcQBzAHAAbwByAHQAaQBmAC4AbABvAGMAYQBsAAcACACo8pVhmmnWAQAAAABMAEUAQwBPAFEAUwBQAE8AUgBUAEkARgBhAGQAbABsAGUAUwBPAEcARQBDAE8AUQBNADIAMAA0AA==
User-Agent: Apache-HttpClient/4.1.1 (java 1.5)
Content-Type: text/xml; charset=utf-8
Content-Length: 451

<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ord="urn:microsoft-dynamics-schemas/codeunit/OrderIntegrationXML" xmlns:x62="urn:microsoft-dynamics-nav/xmlports/x62000">
   <soapenv:Header/>
   <soapenv:Body>
      <ord:InsertOrderXMLWS>
         <ord:p_OriginType>a</ord:p_OriginType>
         <ord:p_OriginOrderNo>z</ord:p_OriginOrderNo>
      </ord:InsertOrderXMLWS>
   </soapenv:Body>
 </soapenv:Envelope>

Any helps would be apprecieted

A: Have you tried implementing a user-agent?
add this code after defining the restclient.

client.UserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.132 Safari/537.36";

A: Ok I found the problem, the NTLM authentication can't be hard coded.
So for RestSharp:
var client = new RestClient(".../Codeunit/OrderIntegrationXML?wsdl");
client.Timeout = -1;
client.Authenticator = new NtlmAuthenticator();

var request = new RestRequest(Method.POST);

request.AddHeader("Host", "....");
request.AddHeader("Accept-Encoding", "gzip,deflate");
request.AddHeader("SOAPAction", @"""urn:microsoft-dynamics-schemas/codeunit/OrderIntegrationXML:InsertOrderXMLWS""");
request.AddHeader("Content-Type", "text/xml;charset=UTF-8");
request.AddHeader("Connection", "Keep-Alive");
request.AddHeader("User-Agent", "Apache-HttpClient/4.1.1");

request.AddParameter("text/xml;charset=UTF-8", "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:ord=\"urn:microsoft-dynamics-schemas/codeunit/OrderIntegrationXML\" xmlns:x62=\"urn:microsoft-dynamics-nav/xmlports/x62000\">\r\n   <soapenv:Header/>\r\n   <soapenv:Body>\r\n      <ord:InsertOrderXMLWS>\r\n         <ord:p_OriginType>?</ord:p_OriginType>\r\n         <ord:p_OriginOrderNo>?</ord:p_OriginOrderNo>\r\n         <ord:p_MappingSalesOrderImport TransferDate=\"2001-01-01\" OriginType=\"?\" QueueLabel=\"?\">\r\n            <!--1 or more repetitions:-->\r\n            <x62:SalesOrder>\r\n               e\r\n               <x62:OriginOrderNumber>?</x62:OriginOrderNumber>\r\n               gero\r\n               <x62:Company>JOOR</x62:Company>\r\n               cum\r\n               <x62:SellToCustomer>?</x62:SellToCustomer>\r\n               sonoras\r\n               <x62:BillToCustomer>?</x62:BillToCustomer>\r\n               aeoliam\r\n               <x62:ShipToCode>?</x62:ShipToCode>\r\n               quae\r\n               <!--1 or more repetitions:-->\r\n               <x62:YourReference>?</x62:YourReference>\r\n               ventos\r\n               <x62:ShipmentMethodCode>?</x62:ShipmentMethodCode>\r\n               verrantque\r\n               <x62:LocationCode>?</x62:LocationCode>\r\n               temperat\r\n               <x62:CurrencyCode>?</x62:CurrencyCode>\r\n               per\r\n               <!--1 or more repetitions:-->\r\n               <x62:TransportMethod>?</x62:TransportMethod>\r\n               turbine\r\n               <x62:SaleOrderType>?</x62:SaleOrderType>\r\n               circum\r\n               <x62:PreparationType>?</x62:PreparationType>\r\n               regemque\r\n               <x62:SalesPersonCode>?</x62:SalesPersonCode>\r\n               nimborum\r\n               <!--1 or more repetitions:-->\r\n               <x62:Comment>?</x62:Comment>\r\n               fremunt\r\n               <x62:DotationContractCode>?</x62:DotationContractCode>\r\n               foedere\r\n               <!--1 or more repetitions:-->\r\n               <x62:Lines>\r\n                  ferant\r\n                  <!--1 or more repetitions:-->\r\n                  <x62:Line>\r\n                     <x62:OriginOrderNumber>?</x62:OriginOrderNumber>\r\n                     <x62:OriginOrderLineNumber>0</x62:OriginOrderLineNumber>\r\n                     <x62:ItemNumber>?</x62:ItemNumber>\r\n                     <x62:SeriesNumber>?</x62:SeriesNumber>\r\n                     <x62:VariantCode>?</x62:VariantCode>\r\n                     <x62:RequestedDeliveryDate>0001-01-01</x62:RequestedDeliveryDate>\r\n                     <x62:Quantity>0</x62:Quantity>\r\n                     <x62:CustomerRateGroup>?</x62:CustomerRateGroup>\r\n                     <x62:TradeTermTypeName>?</x62:TradeTermTypeName>\r\n                     <x62:LineDiscount1>0</x62:LineDiscount1>\r\n                     <x62:LineDiscount2>0</x62:LineDiscount2>\r\n                     <x62:LineDiscount3>0</x62:LineDiscount3>\r\n                     <x62:LineDiscount4>0</x62:LineDiscount4>\r\n                     <x62:LineDiscount5>0</x62:LineDiscount5>\r\n                     <x62:OriginUnitPrice>0</x62:OriginUnitPrice>\r\n                     <!--Optional:-->\r\n                     <x62:JerseyNumber>?</x62:JerseyNumber>\r\n                  </x62:Line>\r\n                  profundum\r\n               </x62:Lines>\r\n               sceptra\r\n            </x62:SalesOrder>\r\n         </ord:p_MappingSalesOrderImport>\r\n      </ord:InsertOrderXMLWS>\r\n   </soapenv:Body>\r\n</soapenv:Envelope>", ParameterType.RequestBody);
IRestResponse responseZ = client.Execute(request);
Console.WriteLine(responseZ.Content);

For httpClient
 static readonly CredentialCache credentialsCache = new CredentialCache { { new Uri("http:.../Codeunit/OrderIntegrationXML"), "NTLM", CredentialCache.DefaultNetworkCredentials } };
 static readonly HttpClient client = new HttpClient(new LoggingHandler(new HttpClientHandler() {UseDefaultCredentials = false , Credentials = credentialsCache, AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip }));

Thanks to the community


text:
Q: How to hide page loading process inside webview while control is inside onpagestarted() in android? i don't want to show page loading process inside webview while control is inside onpagestarted() android. what i want is, to show the the contents in web view when complete page is downloaded. the code i am using is`
    web.setWebViewClient(new myWebClient());
    web.getSettings().setJavaScriptEnabled(true);

    web.loadUrl("http://iba.edu.pk/");

and `WebViewClient class is as follows
public class myWebClient extends WebViewClient
{
    @Override
    public void onPageStarted(WebView view, String url, Bitmap favicon) {
        // TODO Auto-generated method stub
        //web.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ONLY);

        Log.d("Main"," onPageStarted");
        super.onPageStarted(view, url, favicon);

    }

    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        // TODO Auto-generated method stub
        Log.d("Main"," shouldOverrideUrlLoading");
        view.loadUrl(url);

        return true;

    }

    @Override
    public void onPageFinished(WebView view, String url) {
        // TODO Auto-generated method stub
        super.onPageFinished(view, url);
        Log.d("Main"," on Page finsihed");

        progressBar.setVisibility(View.GONE);
    }
}


text:
Q: How do I create a busy handler in sqlite3 using Deno? I have multiple processes writing to sqlite db simultaneously using this library: https://github.com/dyedgreen/deno-sqlite
I tried setting PRAGMA busy_timeout = 30000 but that didn't fix my problem.
I have one long running process that queries db sequentially in a loop and if I run that, the whole app freezes and users can no longer read from db.
I read something about creating an sqlite_busy_handler. Does anyone know how to solve this issue?

A: SQlite doesn't really allow concurrent writes, you can get something close if you use the WAL. https://www.sqlite.org/cgi/src/doc/begin-concurrent/doc/begin_concurrent.md


text:
Q: What are the pros/cons of using "www"? Duplicate:

Should I default my website to www.foo or not?

To be quite honest, I'm ignorant as to what the differences between "http://example.com" and "http://www.example.com" are.
I typically always use the shorter version, without the "www," just for the sake of the length. But I know (think) that there can be cookie conflicts when users try to access a site when they alternate the version they're using. So on all of my sites I just have "http://www.foo.com/bar" redirected to "http://foo.com/bar". But is there anything to be said about using the "www"?

A: www is just a subdomain like any other.  There's nothing inherently special about it.  Back when most of the interaction with the Internet was services other than HTTP, it made sense to have the HTTP traffic use a specific subdomain.  Nowadays, the vast majority of domain names exist simply to serve up HTTP traffic, so the distinction is unnecessary.  I think it's generally preferred to use the "shorter version" as you call it, and redirect www to the main domain.

A: The www subdomain is a reminiscence of the old times when you had an ftp subdomain for the FTP server and so on. There are no reasons to keep it. Many serious sites, including stackoverflow.com here even redirect www.site.com to site.com.

A: Just make the WWW a CNAME for the domain and direct all traffic to the domain name

A: www is a subdomain and was typically used to separate a web server from other servers running on the same domain. Other subdomains can be used like ftp or irc.
Personally I think people still use it just to keep "compatible" and because a lot of people using the internet believe that www is actually part of the domain name itself.

A: Yes, there can be cookie conflicts, and I've seen this numerous times on web forums.
As to the advisability of either approach, I can't really tell you that one is better than the other, but I CAN say that (in light of the aforementioned cookie issue), you should accept both but have one of them redirect to the other so that all URL's are going to use the same format.


text:
Q: Adding a DPDT switch into schematic I'm learning to use Kicad and got stuck trying to add a DPDT switch to my schematic. When I try to add it, I couldn't find one in the components library when I search for it. How can I add it to my schematic on Kicad?

A: Switches like this are in the switches library.
You can add the library by selecting "Component Libraries" from the Preferences Menu, then selecting add.
On Linux the standard libraries are in /usr/share/kicad/library
If you're on another OS, the relevant directory is probably somewhere in the Current Search Path List in the original Component Libraries dialogue box described above. I'm sure a search for *.lib will make the appropriate library obvious if you're not running Linux.
The kicad forum is excellent by the way.


text:
Q: WPF Dependency Property In Nested User Control I have the following WPF Control which is used to Show A Text With An Image Beside it
XAML Code
<UserControl x:Class="WFWorkSpaceWPF.UserControls.StackedImageTextCtl"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
         xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
         mc:Ignorable="d"
         Name="StackedImageText"
         >
<Grid>
    <StackPanel Orientation="Horizontal">
        <Image Source="{Binding ElementName=StackedImageText, Path=ImageSource}" />
        <TextBlock Text="{Binding ElementName=StackedImageText, Path=Text}" />
    </StackPanel>
</Grid>

CS
 public partial class StackedImageTextCtl : UserControl
{
    public StackedImageTextCtl()
    {
        InitializeComponent();
    }
    #region "Properties"
    public string Text
    {
        get { return (string)GetValue(TextProperty); }
        set { SetValue(TextProperty, value); }
    }

    public static readonly DependencyProperty TextProperty =
      DependencyProperty.Register("Text", typeof(string), typeof(StackedImageTextCtl), new UIPropertyMetadata(""));

    public ImageSource ImageSource
    {
        get { return (ImageSource)GetValue(ImageSourceProperty); }
        set { SetValue(ImageSourceProperty, value); }
    }

    public static readonly DependencyProperty ImageSourceProperty =
       DependencyProperty.Register("ImageSource", typeof(ImageSource), typeof(StackedImageTextCtl), new UIPropertyMetadata(null));
    #endregion
}

In my project i want to reuse this control in other three user controls where it will be added as a part of these controls, As you see that the StackedImageTextCtl exposes Two Properties (Text and Image Source) that the parent User Controls needs to provide to it and these three controls will take the value from the container window throw XAML, I know that One of the ways to do so is to replicate defining the properties in each of these three user control and Using AddOwner functionality, but i am looking for a more better approach that won't require any repeat in code, can anyone please direct me to such way?.

A: This is your UserControl:
<UserControl ...>
    <StackPanel Orientation="Horizontal">
        <Image Source="{Binding ImageSource}" Width="16"/>
        <TextBlock Text="{Binding Text}" />
    </StackPanel>
</UserControl>

and its code:
in addition to Text and ImageSource, there is State which represents the Add/Edit/delete state of this control, and there is StackCtlState which is an attached property and when attached to a FrameworkElement it represents the Add/Edit/delete state of that control.
    public StackedImageTextCtl()
    {
        InitializeComponent();
        DataContext = this;
    }
    //Text Dependency Property
    public string Text
    {
        get { return (string)GetValue(TextProperty); }
        set { SetValue(TextProperty, value); }
    }
    public static readonly DependencyProperty TextProperty =
        DependencyProperty.Register("Text", typeof(string), typeof(StackedImageTextCtl), new UIPropertyMetadata(null));
    //ImageSource Dependency Property
    public ImageSource ImageSource
    {
        get { return (ImageSource)GetValue(ImageSourceProperty); }
        set { SetValue(ImageSourceProperty, value); }
    }
    public static readonly DependencyProperty ImageSourceProperty =
        DependencyProperty.Register("ImageSource", typeof(ImageSource), typeof(StackedImageTextCtl), new UIPropertyMetadata(null));
    //State Dependency Property
    public AddEditDelete State
    {
        get { return (AddEditDelete)GetValue(StateProperty); }
        set { SetValue(StateProperty, value); }
    }
    public static readonly DependencyProperty StateProperty =
        DependencyProperty.Register("State", typeof(AddEditDelete), typeof(StackedImageTextCtl), new UIPropertyMetadata(AddEditDelete.Add));

    public static AddEditDelete GetStackCtlState(DependencyObject obj)
    {
        return (AddEditDelete)obj.GetValue(StackCtlStateProperty);
    }

    public static void SetStackCtlState(DependencyObject obj, AddEditDelete value)
    {
        obj.SetValue(StackCtlStateProperty, value);
    }
    public static readonly DependencyProperty StackCtlStateProperty =
        DependencyProperty.RegisterAttached("StackCtlState", typeof(AddEditDelete), typeof(StackedImageTextCtl), new UIPropertyMetadata(AddEditDelete.Add));

I also define an enum:
public enum AddEditDelete { Add, Edit, Delete }

In Window xaml:
Each Button or ToggleButton have their attached property StackCtlState set to the desired value and also have their style set to one of styles for Button or ToggleButton.
Then these styles add a StackedImageTextCtl to the contents of styled button/togglebutton in the proper way that resources can be reused. (if you set just Content and don't set Template instead it will only show the contents of the last Button or last ToggleButton) The added StackedImageTextCtl has a State equal to the attached value of its TemplatedParent which is Button or ToggleButton.
At last the style uses Trigger to set the values for Text and Image, based on State of the StackedImageTextCtl.
<Window...
     xmlns:myNamespace="clr-namespace:WpfApplication1">

<Window.Resources>
    <Style TargetType="{x:Type myNamespace:StackedImageTextCtl}">
        <Style.Triggers>
            <Trigger Property="State" Value="Add">
                <Setter Property="Text" Value="ADD"/>
                <Setter Property="ImageSource" Value="/blue_1.jpg"/>
            </Trigger>
            <Trigger Property="State" Value="Edit">
                <Setter Property="Text" Value="EDIT"/>
                <Setter Property="ImageSource" Value="/blue_2.jpg"/>
            </Trigger>
            <Trigger Property="State" Value="Delete">
                <Setter Property="Text" Value="DELETE"/>
                <Setter Property="ImageSource" Value="/blue_3.jpg"/>
            </Trigger>
        </Style.Triggers>
    </Style>
    <Style x:Key="stackButtonStyle" TargetType="{x:Type Button}">
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate>
                    <Button>
                        <myNamespace:StackedImageTextCtl State="{TemplateBinding myNamespace:StackedImageTextCtl.StackCtlState}"/>
                    </Button>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
    <Style x:Key="stackToggleButtonStyle" TargetType="{x:Type ToggleButton}">
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate>
                    <ToggleButton>
                        <myNamespace:StackedImageTextCtl State="{TemplateBinding myNamespace:StackedImageTextCtl.StackCtlState}"/>
                    </ToggleButton>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
</Window.Resources>

<StackPanel>
    <Button Style="{StaticResource stackButtonStyle}" myNamespace:StackedImageTextCtl.StackCtlState="Add"/>
    <Button Style="{StaticResource stackButtonStyle}" myNamespace:StackedImageTextCtl.StackCtlState="Edit"/>
    <ToggleButton Style="{StaticResource stackToggleButtonStyle}" myNamespace:StackedImageTextCtl.StackCtlState="Delete"/>
</StackPanel>


text:
Q: System.IO.File Current Directory Use Only TXT File I have a folder location
Z:\MyFolder\Hours

And in this folder, I have two files, a PowerShell script and a text (txt) file; I will only ever have these two files in this folder, but the text file name changes every week. My PowerShell script is below and works, but what I would like it to do it to get the current directory it is stored (or was opened) from, open the only txt file in the directory, and run the script on it. Currently, the opening and saving of the txt file is hard-coded, and I would like to use this same script on some files that names change daily. I appreciate anyone's help!
    $r = @{
    "Mon" = "Monday";
    "Tue" = "Tuesday";
    "Wed" = "Wednesday";
    "Thu" = "Thursday";
    "Fri" = "Friday";
    "Sat" = "Saturday";
    "Sun" = "Sunday"
}

$regexes = $r.keys | foreach {[System.Text.RegularExpressions.Regex]::Escape($_)}
$regex = [regex]($regexes -join '|')

$callback = { $r[$args[0].Value] }

$file = [System.IO.File]::ReadAllText("Z:\MyFolder\Hours\file.txt")
$file = $regex.Replace($file, $callback)
Set-Content -Path Z:\MyFolder\Hours\file.txt -Value $file

A: See my answer for how to get directory from which script is executing.
How can I customize powershell when running inside of the VSCode integrated terminal?
For getting the only (or first) txt file in a directory do something like:
$file = Get-ChildItem -Path 'Z:\MyFolder\Hours' -Filter *.txt | Select -First 1 | Select -ExpandProperty FullName

This should get you going.

A: I worked out my problem with the solution shown below:
(Get-Content *.txt) | Foreach-Object {
    $_ -replace 'Mon\b', 'Monday' `
       -replace 'Tue\b', 'Tuesday' `
       -replace 'Wed\b', 'Wednesday' `
       -replace 'Thu\b', 'Thursday' `
       -replace 'Fri\b', 'Friday' `
       -replace 'Sat\b', 'Saturday' `
       -replace 'Sun\b', 'Sunday'
    } | Set-Content *.txt

This allows for the PowerShell script to open in the current directory, open the only text (txt) file within that directory, make the replacements, and save the file.


text:
Q: Changes not loading even after hard refresh Got a very weird issue, so I'm using Docker containers to de-couple a new app.
Container 1 = Laravel
Container 2 = React
My containers spin up with no issues, I've CLI'd onto the React container and ran npx create-react-app ./ which has created a new app.
I've then ran npm start and the standard React page loads up.
Now when I make any changes to any files the changes don't get refreshed in the browser.  To be clear I'm not talking about hot reloading, if I manually hit the refresh button the changes still do not show.  I've ran in incognito mode to ensure it's not a local cache issue which hasn't solved it.  I've also checked the files in the container and the files themselves update.  If I stop NPM and then start it again and then refresh the browser the changes then show.
How can I get this to work without the need to npm start on every change?


text:
Q: First Silverlight application causing problem. Developer Runtime error I have installed Visual Studio 2010 and Silverlight 4 tools. Still, i am getting an error while running my Silverlight application :-
Unable to Start Debugging. The Silverlight Developer Runtime is not installed. Please install a matching version
Why is this happening? Thanks in advance :)

A: Make sure you uninstall the current Silverlight runtime from the control panel (add/remove programs) and reinstall the Silverlight Tool to get the developer (debuggable) version of the Silverlight Runtime instead.
The tools do not replace an existing installed version of Silverlight, so must be removed manually first.


text:
Q: Return all related entities with Entity Framework I'm playing with Entity Framework for the first time. I'm writing the following simply query:
public List<Request> GetResult(string code)
{
    List<Request> requests = new List<Request>();

    using (var db = new Context())
    {
        requests = (from c in db.Requests where c.Code == code select c).ToList();
    }

    return requests;
}

There are a few related entities to the Request object such as a Results table that has a 1-to-1 relation with the Request table. However they are all coming back null.
How can I query with Entity Framework and return a entity and ALL its related entities?
TIA

A: Single query using eager loading
db.Requests.Where(req => req.Code == code)
    .Include(req => req.Results) // Joining is performed here
    .Include(req => req.SomeOtherProperty)
    .ToList()

Multiple queries using explicit loading
// Hits the database once.
var requests = db.Requests.Where(req => req.Code == code).ToList();
var requestIDs = requests.Select(req => req.ID);
// Hits the database another time to load your Results property.
db.Results.Where(res => requestIDs.Contains(res.RequestID)).Load();

If lazy loading is enabled, everytime you access the Results property of Request list, a query is executed to on the database to load it for you, which could result in the N+1 problem. Lazy loading is not yet available on EntityFramework Core though.

A: If you want to choose objects to be loaded use
db.Entry(Requests).Reference(p => p.Code).Load();

If you want to load all automatically on your datacontext constructor set
this.Configuration.LazyLoadingEnabled = true;


text:
Q: mongodb query in 2 collections I have define 2 reconds in 2 collections separately in one mongo db like this
order:

{

    "_id" : ObjectId("53142f58c781abdd1d836fcd"),
    "number" : "order1",
    "user" : ObjectId("53159bd7d941aba0621073e3")
}

user

{

    "_id" : ObjectId("53159bd7d941aba0621073e3"),
    "name" : "user1",
    "gender" : "male"

}

when I use this command in console, it can not execute
db.orders.find({user: db.user['_id']}) or db.orders.find({user: user['_id']}),
is there anything wrong? Thanks!

A: Another way is to:
> var user = db.users.findOne({name: 'user1'});
> db.orders.find({user: user._id});

This way can be a bit more flexible especially if you want to return orders for multiple users etc.
Taking your comment:

Thanks, but actually, I want to search all the orders of all users, not only one user. So what would I do? Thanks

db.users.find().forEach(function(doc){
    printJson(db.orders.find({user: doc._id}));
});

A: I think you want:
db.order.find({'user':db.users.findOne({'name':'user1'})._id})

All you need to do is to make a query and check the output before inserting it into the query.
i.e. check that:
db.users.findOne({'name':'user1'})._id

has the output:
ObjectId("53159bd7d941aba0621073e3")

If you want to run larger queries, you're going to have to change your structure. Remember that Mongodb doesn't do joins so you'll need to do create a user document that looks like this:
user
{
 "name":"user1",
 "gender":"male",
 "orders":[
    {
     'number':'order1'
    }
 ]
}

You can then update this using:
 db.user.update({'_id':ObjectId('blah')}, {'orders':{$push:{'number':'order2'}})

This will then start you with order tracking.
Mongo will be able to find using the following:
 db.user.find({'orders.numbers':'order2'})

returning the full user record

A: Maybe you can help this solution:
use orders
db.getCollection('order').find({},{'_id':1})
db.getCollection('user').find({},{'_id':1})


text:
Q: jquery.append() - only the last element of my list is appended, previous ones are erased I have a page like this :

and some javascript to fill my calendar like this
function getWeek(){
    $.getJSON("/getWeek",function(events){
        var eventHeight = $("#hoursTable > div").height();
        var eventWidth = $("#daysTable > div").width();
        var startWeek = events[0]// timestamp of the start of the week
        for(var i = 1; i < events.length; i ++){
            $(".day").empty();
            var startHour = (events[i].startDate - startWeek)/3600
            var duration = (events[i].stopDate - startWeek)/3600 - startHour
            var dayStart = Math.floor(startHour/24);
            var startHour = startHour - dayStart * 24
            divEvent = $('
')
                .width(eventWidth-2)
                .height(duration*eventHeight)
                .css("border","1px solid black")
                .css("margin-top",startHour*eventHeight)
                .html(events[i].name);
            divEvent.appendTo("#day"+dayStart);
            console.log(divEvent);
        }
    });
}

my problem being : events contain 3 element I'd like to display but only the last is displayed.
If I stop my "for" at the first iteration I can see the first div appended, but it seems that if my loop goes for three iteration the two previous are deleted.
The console.log() display some "not-anymore" existing element.
Any idea ?

A: By calling $(".day").empty(); at the top of the loop, you're removing all of the events before you add each new one.
You need to move that line before the for loop.

A: Inside your loop you're calling $(".day").empty(); which is erasing any added in previous iterations...you need to move that outside/before the for loop so it doesn't do this anymore.
So this:
    for(var i = 1; i < events.length; i ++){
        $(".day").empty();

Should be this:
    $(".day").empty();
    for(var i = 1; i < events.length; i ++){

A: can we see the returned structure of your "/getWeek" json....
cause I think the issue is that in function(events){...}, events is not an array...
I think you should have something like events.data.length, then events.data[i].somevariable


text:
Q: Javascript filter by test and boolean values I feel like I should the answer to this but its escaping me right now.
Say I have an array of Vendors (this is dummy data):
[
  {
    "user_updated": null,
    "user_created": "128a84b5-275c-4f00-942e-e8ba6d85c60e",
    "date_created": "2021-03-13T23:41:09Z",
    "date_updated": null,
    "website": "www.example.com",
    "payment_information": "IBAN: THEIR1234IBAN567",
    "tax_id": null,
    "vat_id": "1234567890",
    "services": "Produzione video, animazioni",
    "name": "Video Productions Ltd.",
    "address": "Viale Lorenteggio, 20\nMilano 20142",
    "notes": "Competenze di alto livello",
    "id": 1,
    "inactive": false
  }
]

I want to filter by name, services, website which I was able to do using:
data() {
  return {
    filter: ''
  }
},
computed: {
  filteredVendors() {
    return this.vendors.filter(({name, notes, services, website}) => {
      const filter = this.filter.toLowerCase()

      return (
        name.toLowerCase().includes(filter) || notes.toLowerCase().includes(filter)... // so on and so forth
      )
    })
  }
}

But I can't seem to make the boolean (inactive) field to work. How can I filter by either inactive false or inactive true?
EDIT:
Ended up getting it to work using this, but is it efficient?

Thank you!

A: To filter a list of data:
data.filter(x => x.inactive)

var data = [
{
    "user_updated": null,
    "user_created": "128a84b5-275c-4f00-942e-e8ba6d85c60e",
    "date_created": "2021-03-13T23:41:09Z",
    "date_updated": null,
    "website": "www.example.com",
    "payment_information": "IBAN: THEIR1234IBAN567",
    "tax_id": null,
    "vat_id": "1234567890",
    "services": "Produzione video, animazioni",
    "name": "Video Productions Ltd.",
    "address": "Viale Lorenteggio, 20\nMilano 20142",
    "notes": "Competenze di alto livello",
    "id": 1,
    "inactive": false
}
];

console.log(data.filter(x => x.inactive))

console.log(data.filter(x => x.id == 1))


text:
Q: How to move row to bottom of Google sheet for multiple tabs in a sheet I found this question and answer which was helpful but I'm wondering how to apply the script (also pasted below) to multiple tabs within a sheet. The column (column 2) to check for an edit to trigger the line to move to the bottom is going to be the same on all sheets (Sheet1, Sheet2, Sheet3).
    function onEdit(e) {

  const row = e.range.getRow();
  const col = e.range.getColumn();
  const as = e.source.getActiveSheet();
  if(as.getName() == "Sheet1" && col == 2  && row > 1 && !as.getRange(row,col).getValue()=='') {
    const row_new = as.getRange(row,1,1,col);
    row_new.copyTo(as.getRange(as.getLastRow()+1,1,1,col));
    as.deleteRow(row);
  }
}

Thanks in advance!

A: Applying onEdit to multiple sheets
function onEdit(e) {
  const sh = e.range.getSheet();
  const shts = ['Sheet1','Sheet2','Sheet3'];
  const idx = shts.indexOf(sh.getName())
  if(~idx && e.range.columnStart == 2  && e.range.rowStart > 1 && e.value) {
    const row_new = sh.getRange(e.range.rowStart,1,1,e.range.columnStart);
    row_new.copyTo(sh.getRange(sh.getLastRow()+1,1,1,e.range.columnStart));
    sh.deleteRow(e.range.rowStart);
  }
}


text:
Q: Which pool to choose from Java Util concurrent I have a bunch of tasks:
public class ProcessDay implements Runnable{
    @Override
    public void run(){
        List<ProcessHour> hr = //required hours
        //do some post actions
    }
}

public class ProcessHour implements Runnable{
    @Override
    public void run(){
        List<ProcessMinutes> mins = //required minutes
        //do some post actions
    }
}

ProcessSeconds, ProcessMonth, ... etc
And so forth. It would be convinient to use ForkJoinPool here but it's not good from performance standpoint, because ProcessXXX tasks are being submitted to a cluster of machines and hence the method invocation itself is very short.
So for performance it's good to use Executors.cachedThreadPoolExecutor. But is there a way to combine ForkJoinPool with chachedThreadPool semantic. I mean creating threads on demand and release them if not used.
Maybe there is a better approach to this? Can you suggest something?

A:
I mean creating threads on demand and release them if not used.

That is how cached thread pool operates. It starts with 0 threads and creates a new one each time when there is a new task to process and all threads in the pool are busy. Thread is terminated if it was idle for 60 seconds.
Default cached thread pool is created using the following ThreadPoolExecutor constructor:
return new ThreadPoolExecutor(0,
                              Integer.MAX_VALUE,
                              60L,
                              TimeUnit.SECONDS,
                              new SynchronousQueue<Runnable>())

It created with 0 possible idle threads in pool, unlimited maximum number of threads, 60 seconds timeout before idle thread is terminated, and queue implementation that doesn't store tasks and just transfers them between pool and its threads. Such pool is suitable for lots of short-lived tasks that is probably your case. As you can see it's also pretty easy to adjust it configuration according to your needs using direct ThreadPoolExecutor constructor.


text:
Q: How to add raise event in style I can't find how to add in a button style the raise event to click button when there is a touchdown (with touch screen), do you know how to add this in the style?
I need to do it because when using touch screen the clickEvent is not fire at first time, generally at second touch (when focus is set to window).
 <Style TargetType="{x:Type Button}">
    <Style.Triggers>
        <EventTrigger RoutedEvent="TouchDown">

How to add the Raise click event??
        </EventTrigger>
    </Style.Triggers>
</Style>

Thank you for your help.


text:
Q: Flask on cheroot/gunicorn scalability I have developed a HTTP API endpoint using flask which accepts json data on POST requests and sends back json response.
I have tried using multiple WSGI servers: gunicorn, cheroot, Bjoern behind Nginx as a reverse proxy.
I noticed that no matter which WSGI server I use, the application is unable to handle a sustained loads of 500 requests per second. A sudden burst of 500 is handled fine. But not when it is sustained. The requests start getting delayed responses and quite a few requests just time out.
The flask web is deployed on a 24 core physical server. So it has 48 logical cores. I am using a C++ application on another similar 24 core server to fire these requests asynchronously. One request every 2ms, thus 500 per second.
Consider the below example of the simple single file flask application on cheroot WSGI server I created to benchmark the performance. It only logs the request json and sends back a response json. Even this is unable to handle a sustained load of 500 requests on a powerful 24 core physical server. The CPU usage is always below 5% during the test.
import os
import json
import logging
from logging.handlers import TimedRotatingFileHandler
from flask import Flask
from flask import request, jsonify
from cheroot.wsgi import PathInfoDispatcher
from cheroot.wsgi import Server

app = Flask(__name__)

# Setup logger for the app
if not os.path.exists('logs'):
        os.mkdir('logs')
file_handler = TimedRotatingFileHandler('logs/simpleflaskapp.log', when='midnight', interval=1, backupCount=10)
file_handler.setFormatter(logging.Formatter(
    '%(asctime)s %(levelname)s: %(message)s [in %(pathname)s:%(lineno)d]'))
file_handler.setLevel(logging.INFO)
app.logger.addHandler(file_handler)

app.logger.setLevel(logging.INFO)
app.logger.info("simpleflaskapp startup")
# end setup logger

@app.route( '/test', methods = [ 'POST' ] )
def test():
    app.logger.info(json.dumps(request.json))
    res = {
        "statusCode": 200,
        "message": "OK",
    }
    return jsonify(res)

d = PathInfoDispatcher({'/': app})
server = Server(('0.0.0.0', 8000), d, numthreads=os.cpu_count(), request_queue_size=int(os.cpu_count()/2))

if __name__ == '__main__':
    try:
        server.start()
    except KeyboardInterrupt:
        server.stop()

The author of the blog post https://www.appdynamics.com/blog/engineering/a-performance-analysis-of-python-wsgi-servers-part-2/ is able to serve multiple thousands of requests per second on a 2 core machine. What am I doing wrong?
Eliminating the disk IO by commenting out logging in the above sample app, allows me to reach 666 requests per second. But not more. This is still low considering the hardware I am running it on.
I have already checked the Nginx configuration and it is configured to handle much higher loads. I have also tried firing requests directly to the WSGI server skipping Nginx and the results of that are worse.

A: Answering my own question.
After going nowhere with trying various WSGI servers with flask, I decided to give cherrypy a try. Turns out even that has similar limitation on concurrency.
Then I came across Sanic. I wrote the same test application on sanic and I am able consistently handle even 10000 requests per second.
Migrating my project from flask to sanic now.


text:
Q: Plotting dates given in columns in gnuplot I want to plot data on the y axis and dates in the x axis and I have it all in columns. I have data following the format
2016.0000000000000  10.000000000000000  14.000000000000000  117.62999700000000
2016.0000000000000  10.000000000000000  13.000000000000000  116.98000300000000
2016.0000000000000  10.000000000000000  12.000000000000000  117.33999600000000
2016.0000000000000  10.000000000000000  11.000000000000000  116.30000300000000
2016.0000000000000  10.000000000000000  10.000000000000000  116.05000300000000
2016.0000000000000  10.000000000000000  7.0000000000000000  114.05999799999999
2016.0000000000000  10.000000000000000  6.0000000000000000  113.88999900000000

in a file, where the structure is year, month, day, data, with tabs as separators. The code I've tried running is:
set xdata time
set timefmt "\"%Y\t%m\t%d\""
set xrange ['"2016\t10\t14"':'"2006\t10\t16"']

plot "data.txt" u 1:2

but apparently this isn't taking the dates as x values and the data as y values, since this error message comes out when running:
line 5: warning: Skipping data file with no valid points
line 5: Can't plot with an empty x range!

Line 5 referring to the line including the plot command. How can I tell the program that what I want to plot is the data versus the dates?

A: set xdata time
set timefmt "%Y %m %d"
set xrange ["2016 10 06":"2006 10 16"]

plot "data.txt" u (sprintf("%d %d %d",$1,$2,$3)):4


text:
Q: If date from database is before current date Basically what I'm trying to do is do an if command to check a date returned from database vs the current date (todays date or tomorrows date if i go on the page tomorrow)
I was thinking of something along the lines of
$date = "2013-11-10 20:28:41";
if ($date < Curdate)
{
    echo "expired";
}

if anyone can give me any insight on the correct commands for this, I would really appreciate it.

A: $dt = new DateTime($date);
$now = new DateTime();
if ($dt < $now) {
  echo "before";
}
else {
  echo "after";
}

A: $now = new DateTime(); // Now
$date = new DateTime('2013-11-10 20:28:41'); // From the DB
if ($date < $now)
{
    echo "expired";
}

Reference: DateTime()


text:
Q: Scala: Passing instance of child class to parent class function Why does the Scala repl say:
<console>:10: error: type mismatch;
 found   : Car#Door
 required: _1.Door where val _1: Car

When I run this statement:
var c = New Car
c.is_door_open(c.door)

That refers to this class:
class Car {
    var door = new Door(true)

    class Door (var state: Boolean = true) {  }

    def is_door_open(d: Door) {
         println(d.state)
    }
}

A: When you have an inner class as Door here, each instance of class Car defines a different Door type. In is_door_open(d: Door), Door means a Door of the enclosing instance of Car. The type Car#Door in the error message means a Door of any Car, it is the common type to all doors.
When you call c.is_door_open(c.door) the Car of c.door must be the same as the the c of c.is_door_open, as that is what the declaration of is_door_open requires (it should have been d: Car#Door otherwise). And moreover, they must be the same to the satisfaction of the compiler, which has some precise rules for that. Here it seems obvious the cars are the same. Not so, because c is a var, so not a stable identifier.
Imagine the code c.is_door_open({c = new Car; c.door}). Contrived of course, but this shows that you cannot rely on both occurence of c being the same car.
So among your solutions, depending of what your real code may be :

*

*Make c a val instead of a var

*declare is_door_open parameter as d: Car#Door

*Stop making Door dependant on instance of Car, declare it outside the class, if you want it to be Car.Door, put it in a companion object Car rather than in class Car

*Make is_door_open a method of Door (without a Door argument then) rather than Car. It has full access to the enclosing Car (with Car.this as in java, or declaring an alias for this in Car with class Car {car => )


text:
Q: ssh connect and commands programmatically I'm trying to make a script connecting via an SSH connection to a server and executing some commands. The first part works:
#!/usr/bin/expect -f
spawn ssh address
expect "password:"
send "password\r"
interact

but after that I want to execute some more commands, e.g cd to directory, launch some more scripts etc. Is there any way to implement these things ?

A: try following:
#!/usr/bin/expect
set login "any_user"
set addr "some_address"
set pw "any_pwd"

spawn ssh -t $login@$addr
expect "$login@$addr\'s password:"
send "$pw\r"
expect "~" ; # put here string from your server prompt
send "mkdir some_dir\r"
interact

This is one of the command, you could try other commands like cd, any other scripts too in it and let us know if any queries.


text:
Q: What is the difference in the execution of callback of 'click' event triggered by the user and that triggered programmatically? I was going through an article of Jake Archibald on tasks, microtasks etc. In his example we see that the 'console logs' are printed in certain order for user based click event and different order for click event triggered programmatically. I request if someone could please explain it in a bit more detail about click callback execution in these two cases.
HTML

CSS
.outer-test {
  background: #D4D4D4;
  padding: 25px;
  width: 92px;
  margin: 0 auto;
}

.inner-test {
  background: #ADADAD;
  padding: 46px;
  width: 0;
}

JS(First case)
var outer = document.querySelector('.outer-test');
var inner = document.querySelector('.inner-test');

new MutationObserver(function() {
  console.log('mutate');
}).observe(outer, {
  attributes: true
});

function onClick() {
  console.log('click');

  setTimeout(function() {
    console.log('timeout');
  },0);

  Promise.resolve().then(function() {
    console.log('promise');
  });

  outer.setAttribute('data-random', Math.random());
}

inner.addEventListener('click', onClick);
outer.addEventListener('click', onClick);

JS(Second Case)
var outer = document.querySelector('.outer-test');
var inner = document.querySelector('.inner-test');

new MutationObserver(function() {
  console.log('mutate');
}).observe(outer, {
  attributes: true
});

function onClick() {
  console.log('click');

  setTimeout(function() {
    console.log('timeout');
  },0);

  Promise.resolve().then(function() {
    console.log('promise');
  });

  outer.setAttribute('data-random', Math.random());
}

inner.addEventListener('click', onClick);
outer.addEventListener('click', onClick);

inner.click();  //<========

For reference: https://jakearchibald.com/2015/tasks-microtasks-queues-and-schedules/

A:
.click() causes the event to dispatch synchronously, so the script that calls .click() is still in the stack between callbacks.

He glances over the answer but that's basically it. Not going to pretend I fully understand the details but as I read it: since the click is triggered from within the JavaScript in the same "frame" as the code that is setting up the event listeners AND triggering the event this way is synchronous the callbacks are run directly after because it doesn't allow to check the microtask queue for the mutation.
In the first case the "setup" finishes and that "frame" ends. So it's only by clicking in the browser that things fire, which will then happen in another frame (asynchronously) and since no other "frame" is running at that point it goes ahead and check the microtask queue for the mutation first.

The above rule ensures microtasks don't interrupt JavaScript that's mid-execution.

And this seems to be the reason for why that isn't done which makes sense since it's all single threaded (you know, sort of) that it makes sense to let that "frame" finish.
So the quirk is really in that firing a event programatically forces it all into synchronous land.


text:
Q: Set object attributes to every variable used in a method in python How can I set (almost) all local variables in an object's method to be attributes of that object?
class Obj(object):
    def do_something(self):
        localstr = 'hello world'
        localnum = 1
        #TODO store vars in the object for easier inspection

x = Obj()
x.do_something()
print x.localstr, x.localnum

A: Inspired by Python update object from dictionary, I came up with the following:
class Obj(object):
    def do_something(self):
        localstr = 'hello world'
        localnum = 1

        # store vars in the object for easier inspection
        l = locals().copy()
        del l['self']
        for key,value in l.iteritems():
            setattr(self, key, value)

x = Obj()
x.do_something()
print x.localstr, x.localnum

A: There is already a python debugger that let you inspect local variables, so there is no point in polluting the objects with random instance attributes.
Also your approach does not work if more than one method use the same local variable names, since it would be possible that a method overwrites some of the instance attributes, leaving the state of the object in an ambiguous state.
Also your solution goes against the DRY principle, since you must add the code before every return.
An other disadvantage is that often you want to know the state of the local variables in more than one place during method execution, and this is not possible with your answer.
If you really want to save the local variables manually, then something like this is probably much better than your solution:
import inspect
from collections import defaultdict

class LogLocals(object):

    NO_BREAK_POINT = object()

    def __init__(self):
        self.__locals = defaultdict(defaultdict(list))

    def register_locals(self, local_vars, method_name=None,
                              break_point=NO_BREAK_POINT):
        if method_name is None:
            method_name = inspect.currentframe(1).f_code.co_name
        self.__locals[method_name][break_point].append(local_vars)

    def reset_locals(self, method_name=None, break_point=NO_BREAK_POINT,
                           all_=False):
        if method_name is None:
            method_name = inspect.currentframe(1).f_code.co_name
        if all_:
            del self.__locals[method_name]
        else:
            del self.__locals[method_name][point]

    def get_locals(self, method_name, break_point=NO_BREAK_POINT):
        return self.__locals[method_name][break_point]

You simply have inherit from it and call register_locals(locals()) when you want to save the state. It also allow to distinguish between "break points" and most importantly it does not pollute the instances.
Also it distinguish between different calls returning a list of states instead of the last state.
If you want to access the locals of some call via attributes you can simply do something like:
class SimpleNamespace(object):  # python3.3 already provides this
    def __init__(self, attrs):
        self.__dict__.update(attrs)

the_locals = x.get_locals('method_1')[-1]   # take only last call locals
x = SimpleNamespace(the_locals)
x.some_local_variable

Anyway, I believe there is no much use for this. You ought to use the python debugger.


text:
Q: Cannot import numpy I built numpy locally from source with python 2.7.2 because I dont have root access to the system. After installation, I appended the following path /path/to/install/lib/python2.7/site-packages to PYTHONPATH. When I tried to import from python, I get following error:
import numpy
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/path/to/numpy/numpy-1.8.0/lib/python2.7/site-packages/numpy/__init__.py", line 153, in <module>
    from . import add_newdocs
  File "/path/to/numpy/numpy-1.8.0/lib/python2.7/site-packages/numpy/add_newdocs.py", line 13, in <module>
    from numpy.lib import add_newdoc
  File "/path/to/numpy/numpy-1.8.0/lib/python2.7/site-packages/numpy/lib/__init__.py", line 18, in <module>
    from .polynomial import *
  File "/path/to/numpy/numpy-1.8.0/lib/python2.7/site-packages/numpy/lib/polynomial.py", line 19, in <module>
    from numpy.linalg import eigvals, lstsq, inv
  File "/path/to/numpy/numpy-1.8.0/lib/python2.7/site-packages/numpy/linalg/__init__.py", line 50, in <module>
    from .linalg import *
  File "/path/to/numpy/numpy-1.8.0/lib/python2.7/site-packages/numpy/linalg/linalg.py", line 29, in <module>
    from numpy.linalg import lapack_lite, _umath_linalg
ImportError: libgfortran.so.1: cannot open shared object file: No such file or directory

I also made GCC locally and have all the paths and library paths set correctly. While building numpy, I didn't build ATLAS because the machine I am running on has cpu throttling on and I cannot change it. Without turning throttling off, ATLAS cannot be installed.
What could be the possible reasons for this error ?

A: This looks like a dependancy issue with the fortran libraries on your machine.
In general, local installation of any package can be achieved in three (easy) ways that I know of, none of which require changing the python path.

*

*virtualenv

*conda

*pip
The easiest of these is using pip with the --user flag.
pip install numpy --user

Make sure ~/.local/bin is in the $PATH, then if your dependancies are correct, numpy should just work.


text:
Q: Cannot access 'filter': it is internal in 'kotlinx.coroutines.channels' Methods "map" and "filter" have been deprecated with the upgrade of Kotlin Coroutine Version. Code was working perfectly fine with earlier version of Kotlin Coroutine, due to some reason I need to upgrade coroutine version. But having much idea about it.
import kotlinx.coroutines.channels.BroadcastChannel
import kotlinx.coroutines.channels.ReceiveChannel
import kotlinx.coroutines.channels.filter
import kotlinx.coroutines.channels.map

object EventBus {
    @ObsoleteCoroutinesApi
    val bus: BroadcastChannel<Any> = BroadcastChannel(1)

    @ObsoleteCoroutinesApi
    fun send(o: Any) {
        CoroutineScope(Dispatchers.IO).launch {
            bus.send(o)
        }
    }

    @ObsoleteCoroutinesApi
    inline fun <reified T> asChannel(): ReceiveChannel<T> {
        return bus.openSubscription().filter { it is T }.map { it as T }
    }
}````

Can we replace the above usage of Map and Filter? Any help would be greatly appreciated.

A: You should take annotation @ObsoleteCoroutinesApi serious, because
class BroadcastChannel had been deprecated altogether ...instead use SharedFlow or MutableSharedFlow; also see this example.
This blog post should support the understanding & migration: Shared flows, broadcast channels.


text:
Q: Headphones plugged in causes audio stuttering? Linux noob here. Off a fresh install of 18.04 LTS, plugging in and using headphones causes the audio to stutter intermittently, whether streaming from a browser or playing a file in VLC, etc. I get this bug in both ubuntu and mint installs. Switching to an HDMI output alleviates this issue somewhat(the sound outputs through my monitor); audio plays absolutely fine if headphones aren't plugged in at all. In pavucontrol and the sound settings menu, I can see the headphone going from detected to undetected as stuttering occurs. See video.
I noticed that pavucontrol frequently attempts to connect to pulseaudio when sound is output through headphones. lspci audio output in terminal specifies:
00:1b.0 Audio device: Intel Corporation 9 Series Chipset Family HD Audio Controller
01:00.1 Audio device: NVIDIA Corporation GK104 HDMI Audio Controller (rev a1)

In alsamixer, the display reads:
Card: HDA Intel PCH
Chip: Realtek ALC887-VD

or
Card: HDA NVidia
Chip: NVidia GPU 40 HDMI/DP

I've tried removing pulse, switching alsa automute to disabled, using a different gfx driver, editing the pulse config files in several permutations based on related questions, but nothing I've found so far seems to describe my problem or present a solution.
SPECS:
CPU: Intel Core i5-4690k 3500 MHz
Motherboard: ASUS H97-PLUS
BIOS Ver. 0316
Graphics Card: MSI Gaming G Series NVIDIA Geforce GTX 770
Ideally I'd like to stop the stuttering, but if someone can point out which area I should focus my debugging I'd really appreciate it.


text:
Q: How can I update state after sorting I need update state after sort by salary
state = {
    workers: [
        {name: 'Bob', surname: 'Meljanski', salary: 5140},
        {name: 'Michel', surname: 'Hensson', salary: 5420},
        {name: 'Jane', surname: 'Mitchel', salary: 2054}
}

startSort = () => {
    const arr = this.state.workers.slice();

    arr[2].name = 'Mike';
    var kk = [...arr].sort((a,b) => (a.salary>b.salary)*2-1);

    this.setState(kk);
    console.log(kk);
}

by result. state renders without sorting. How can I do correctly? sorry for my english

A: setState accepts an object (the new state object)  or a function (an updater which will run when react actually updates the state, mostly used when the next state is depended on the previous state, like toggles etc), you passed to it an array.
You can try this:
 this.setState({workers: kk});


text:
Q: Modify Express sessions on set and get I'm wondering if there's a way to (globally via Express middleware) intercept the get and set of session objects.
So, for instance if somewhere in one of my controllers I set req.session.foo = 'bar' I can change bar to baz, then when req.session.foo is accessed I can send back bar.

A: I'm not sure what you are trying to accomplish but you should take a look at connect-flash middleware to store messages in requests.
From the docs:
app.get('/flash', function(req, res){
  // Set a flash message by passing the key, followed by the value, to req.flash().
  req.flash('info', 'Flash is back!')
  res.redirect('/');
});

app.get('/', function(req, res){
  // Get an array of flash messages by passing the key to req.flash()
  res.render('index', { messages: req.flash('info') });
});


text:
Q: Statistical significance of the difference between two Linear Regression slopes How to test the statistical significance of the difference between two Linear Regression slopes?
There are two time-series: T1 and T2. They come from different studies and mean different things. On T1 we do a Linear Regression and get the coefficient B1. On T2 we do a Linear Regression and get the coefficient B2.

*

*For comparison of the slopes, do I need the dependant variable to be the same?

*Can time be this dependant variable?

*What are the recommended statistical tests to apply in this case? T-test?

Thank you for your time!


text:
Q: How to access slim app requests on a shorten url I have a simple SLIM application that responds to all requests to sent it in an API-like way for example the following url:
http://example.com/pages/subdirectory/slimApp.php/products

As you can see, the url to the slim app is absolute and pretty long but I have tried using Apache2 mod_rewrite to shorten the url as shown below
RewriteEngine on
RewriteBase /pages/
RewriteRule ^slimApp/(.*) subdirectory/slimApp.php/$1 [L,NC]

The code above rewrites to the main route of the app which is basically a 404 error page and acts like no request has been specified. When I access the app with an absolute url, it works as normal but if I try to access /products from the shorten url version, it fails with a slim 404 page.
Basically what I need is to translate the following and still be able to handle requests like shortened_url/products, shortened_url/something_else, etc. For-example:
http://example.com/pages/subdirectory/slimApp.php/products

to
http://example.com/slimApp/products

Bear in mind that /products is dynamic, any help is greatly appreciated.


text:
Q: How to use Rest Framework's default token authentication view? I am trying to use DRF's builtin TokenAuthentication view, but I can't get it to work.
Here is the test:
import requests
import json
data = json.dumps({
  'username': 'test-sandbox-root',
  'password': 'password'
})
headers = {'Content-Type': 'application/json'}
r = requests.post('http://localhost:8000/api/auth', data=data, headers=headers)
>>> r.status_code
400
>>> r.text
'{"non_field_errors":["Unable to log in with provided credentials."]}'

But the user clearly exists:
>>> User.objects.get(username='test-sandbox-root', password='password')
<User: test-sandbox-root>

I've added the DEFAULT_AUTHENTICATION_CLASSES to my settings:
REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': [
        'rest_framework.authentication.BasicAuthentication',
        'rest_framework.authentication.SessionAuthentication',
        'rest_framework.authentication.TokenAuthentication',
    ]
}

And migrated the rest_framework.authtoken app:
INSTALLED_APPS = [
    ...

    'rest_framework',
    'rest_framework.authtoken',

    ...
]

And added optain_auth_token to my urls.py:
from rest_framework.authtoken import views

urlpatterns = [
    path('/api/auth', views.obtain_auth_token),
]

What am I missing?


text:
Q: AutoFill plugin/extension which works for all browsers? I am currently thinking of writing an AutoFill plugin/widget which will take my personal data such as First Name, Last Name etc from a file/javascript and will automatically fill it in web page form.
    I have read till now to build a plugin which works for all browsers, I have two options:-
    1) To make a Jquery UI widget
    2) To make a NPAPI plugin
Is there any other easier method to develop an autofilling plugin, and which option to take i.e. NPAPI plugin or Jquery widget ?
Thanks

A: Neither of the two options you mention will allow you to automatically fill in your personal data on all websites.
You'll want to write a browser extension (which are different from plugins). As you want to target multiple browsers, you may want to look into frameworks which make that easier, like crossrider.


text:
Q: Import error while launching PyTorch Lightning project on Colab TPU I followed this guide to launch my PyTorch Lightning project on Google Colab TPU. So I installed
!pip install cloud-tpu-client==0.10 https://storage.googleapis.com/tpu-pytorch/wheels/torch_xla-1.9-cp37-cp37m-linux_x86_64.whl

Then
 !pip install pytorch-lightning

Then I
!pip install torch torchvision torchaudio
!pip install -r requirements.txt

After installing the project requirements, I restarted the runtime as requested and re-ran the cloud-TPU-client install, the pytorch-lightning install, and both command from above. It ran smoothly.
But just after the TPU has started with version PyTorch version 1.9, I get the following import error :
WARNING:root:TPU has started up successfully with version pytorch-1.9
        Traceback (most recent call last):
          File "synthesizer_train.py", line 2, in <module>
            from synthesizer.train import train
          File "/content/Real-Time-Voice-Cloning/synthesizer/train.py", line 6, in <module>
            from synthesizer.models.tacotron import Tacotron
          File "/content/Real-Time-Voice-Cloning/synthesizer/models/tacotron.py", line 7, in <module>
            import pytorch_lightning as pl
          File "/usr/local/lib/python3.7/dist-packages/pytorch_lightning/__init__.py", line 20, in <module>
            from pytorch_lightning.callbacks import Callback  # noqa: E402
          File "/usr/local/lib/python3.7/dist-packages/pytorch_lightning/callbacks/__init__.py", line 14, in <module>
            from pytorch_lightning.callbacks.base import Callback
          File "/usr/local/lib/python3.7/dist-packages/pytorch_lightning/callbacks/base.py", line 26, in <module>
            from pytorch_lightning.utilities.types import STEP_OUTPUT
          File "/usr/local/lib/python3.7/dist-packages/pytorch_lightning/utilities/__init__.py", line 18, in <module>
            from pytorch_lightning.utilities.apply_func import move_data_to_device  # noqa: F401
          File "/usr/local/lib/python3.7/dist-packages/pytorch_lightning/utilities/apply_func.py", line 26, in <module>
            from pytorch_lightning.utilities.imports import _compare_version, _TORCHTEXT_AVAILABLE
          File "/usr/local/lib/python3.7/dist-packages/pytorch_lightning/utilities/imports.py", line 101, in <module>
            from pytorch_lightning.utilities.xla_device import XLADeviceUtils  # noqa: E402
          File "/usr/local/lib/python3.7/dist-packages/pytorch_lightning/utilities/xla_device.py", line 24, in <module>
            import torch_xla.core.xla_model as xm
          File "/usr/local/lib/python3.7/dist-packages/torch_xla/__init__.py", line 142, in <module>
            import _XLAC
        ImportError: /usr/local/lib/python3.7/dist-packages/_XLAC.cpython-37m-x86_64-linux-gnu.so: undefined symbol: _ZN2at13_foreach_erf_EN3c108ArrayRefINS_6TensorEEE

Trainer was launched with the flag TPU_cores=8.
The model had run on CPU and GPU beforehand (ie on another session).
I tried to downgrade PyTorch to 1.9 (the same as the one shown when TPU is starting) because Colab uses torch 1.10.0+cu111 and a different error appeared :
WARNING:root:TPU has started up successfully with version pytorch-1.9
Traceback (most recent call last):
  File "synthesizer_train.py", line 2, in <module>
    from synthesizer.train import train
  File "/content/Real-Time-Voice-Cloning/synthesizer/train.py", line 6, in <module>
    from synthesizer.models.tacotron import Tacotron
  File "/content/Real-Time-Voice-Cloning/synthesizer/models/tacotron.py", line 7, in <module>
    import pytorch_lightning as pl
  File "/usr/local/lib/python3.7/dist-packages/pytorch_lightning/__init__.py", line 20, in <module>
    from pytorch_lightning.callbacks import Callback  # noqa: E402
  File "/usr/local/lib/python3.7/dist-packages/pytorch_lightning/callbacks/__init__.py", line 14, in <module>
    from pytorch_lightning.callbacks.base import Callback
  File "/usr/local/lib/python3.7/dist-packages/pytorch_lightning/callbacks/base.py", line 26, in <module>
    from pytorch_lightning.utilities.types import STEP_OUTPUT
  File "/usr/local/lib/python3.7/dist-packages/pytorch_lightning/utilities/__init__.py", line 18, in <module>
    from pytorch_lightning.utilities.apply_func import move_data_to_device  # noqa: F401
  File "/usr/local/lib/python3.7/dist-packages/pytorch_lightning/utilities/apply_func.py", line 29, in <module>
    if _compare_version("torchtext", operator.ge, "0.9.0"):
  File "/usr/local/lib/python3.7/dist-packages/pytorch_lightning/utilities/imports.py", line 54, in _compare_version
    pkg = importlib.import_module(package)
  File "/usr/lib/python3.7/importlib/__init__.py", line 127, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "/usr/local/lib/python3.7/dist-packages/torchtext/__init__.py", line 5, in <module>
    from . import vocab
  File "/usr/local/lib/python3.7/dist-packages/torchtext/vocab/__init__.py", line 11, in <module>
    from .vocab_factory import (
  File "/usr/local/lib/python3.7/dist-packages/torchtext/vocab/vocab_factory.py", line 4, in <module>
    from torchtext._torchtext import (
ImportError: /usr/local/lib/python3.7/dist-packages/torchtext/_torchtext.so: undefined symbol: _ZTVN5torch3jit6MethodE

Is there anything I can do to train the model on TPU ?
Thank you very much

A: Actually the same problem has also been described and the suggested solution did work for me.
So in the details they suggest to downgrade PyTorch to 1.9.0+cu111 (mind the +cu111) after installing torch_xla.
Consequently here are the steps I followed to launch my Lightning project on Google Colab with TPU :
!pip install cloud-tpu-client==0.10 https://storage.googleapis.com/tpu-pytorch/wheels/torch_xla-1.9-cp37-cp37m-linux_x86_64.whl
!pip install torch==1.9.0+cu111 torchvision==0.10.0+cu111 torchtext==0.10.0 -f https://download.pytorch.org/whl/cu111/torch_stable.html

And then the project's pip :
!pip install torch torchvision torchaudio pytorch-lightning
!pip install -r requirements.txt

And it worked even though after this last step, I had to restart runtime.

A: Based on above solution, we could additionally fix the issue for sure by finding the version of cuda installed with
import torch
torch.version.cuda

10.2

Based on this cuda version perform this pip install command
!pip install cloud-tpu-client==0.10 torchvision==0.12.0+cu102 torch==1.11.0+cu102 https://storage.googleapis.com/tpu-pytorch/wheels/colab/torch_xla-1.11-cp37-cp37m-linux_x86_64.whl -f https://download.pytorch.org/whl/cu102/torch_stable.html

Pls notice the cu102 in three places in the above command


text:
Q: Configuring JVM properties for OLP pipelines I would like to provide custom JVM properties to pipelines deployed to OLP.
I know it is possible when deploying via REST API, but is there any other way to do that (using CLI or portal GUI)?
What are the general rules in that matter? Are different ways of deploying pipelines functionally equal?
Unfortunately, documentation isn't very specific about that. I know this is rather general question without details, but we are trying to figure out the best approach.

A: Currently, that is not supported.  What would be the use case where you would need to do that?  We can ask for a feature request given a use case.  The different ways of deploying pipelines (CLI, Portal UI) are functionally equivalent.

A: You can't pass JVM properties per se (assuming you mean -D arguments to a java command) but you can pass in custom properties for a pipeline version. They will placed in a file named application.properties which your code will then have to read in. Documentation


text:
Q: Client-side javascript: be notified of all accesses to any property of Object.prototype? In javascript, or using the browsers's Dev Tools, is there a way to be notified or log or intercept all accesses to any property of Object.prototype?
What I'm trying to do is figure out all the places where some client-side code tries to access a property of an object that isn't defined anywhere in the inheritance chain. For example, if the code tries to access someObject.xxx and xxx isn't defined in someObject, I would like to be notified of that.
It can easily be done for a specific property or any object, by defining a getter for this property with Object.defineProperty(Object.prototype, 'xxx', {get: _ => {...}}). It can also easily be done for all properties of a specific object, using a Proxy. The question is, can it be done for any property of any object?


text:
Q: How to connect AWS DynamoDb directly with dart I am working on a messaging app in flutter and all the messages are stored in AWS DynamoDB. I didn't find any docs on direct support of DynamoDB and Dart. So I first connected DB to NodeJS and used http req from flutter app to get the messages. But its not much reliable. Only if I could find a way to connect it directly I could make the app more speeder. If anyone out there know a way for this please help out.

A: There is not an AWS SDK for this programming language. The only thing I can think of is to write code in your programming language that can invoke DynamoDB using Rest. There is an AWS documentation including an example:
DynamoDB Low-Level API

A: You can maybe try non AWS provided SDKs like this one. It includes a DynamoDB client. I haven't used it before, so I can't vouch for it.

A: As Richard mentioned, https://pub.dev/packages/aws_dynamodb_api is a good solution.
I integrated DynamoDB in dart as other languages:
static var client = DynamoDB(region: 'eu-west-1',
endpointUrl: "http://localhost:8000",
credentials: AwsClientCredentials(accessKey: "dummy", secretKey: "dummy"));

static Future<bool> init() async {

var attributeDefinitions = <AttributeDefinition>[
AttributeDefinition(attributeName: "user_id", attributeType: ScalarAttributeType.n)
];

var keySchema = <KeySchemaElement>[
KeySchemaElement(attributeName: "user_id", keyType: KeyType.hash)
];

var throughput = ProvisionedThroughput(readCapacityUnits: 10, writeCapacityUnits: 10);
try
{
  var response = await client.createTable(attributeDefinitions: attributeDefinitions, keySchema: keySchema, provisionedThroughput: throughput, tableName: "Users");
  print("Created table ${response.tableDescription!.tableName}");
  return true;
} catch(e)
{
  print("Error: $e");
  return false;
}

I tested it downloading the docker image of DynamoDB: https://hub.docker.com/r/amazon/dynamodb-local/


text:
Q: Simple matrix problem basis vectors Why does the standard basis vector $e_2$ lie in the kernal of this matrix? Doesn't $e_1$ also lie in it too?  $$\pmatrix{0&0&1\\0&0&0\\0&0&0}$$

A: (Just to avoid leaving an unanswered question.)
A vector $\vec{v}$ is in the kernel of a matrix $A$ if and only if $A\vec{v}=\vec{0}$. Since
$\pmatrix{0&0&1\\0&0&0\\0&0&0} \pmatrix{1\\0\\0}=\pmatrix{0\\0\\0}=\pmatrix{0&0&1\\0&0&0\\0&0&0} \pmatrix{0\\1\\0}$,
$e_1$ and $e_2$ belong to the kernel; while $e_3$ does not because
$\pmatrix{0&0&1\\0&0&0\\0&0&0} \pmatrix{0\\0\\1}=\pmatrix{1\\0\\0}\neq \pmatrix{0\\0\\0}$.


text:
Q: Could we use static method outside class in java I define a static method f for class named a in java,
Could I also use it as a.f outside the class?
OR we could only use it as a help function within the class?

A: If that is a public static method, you can use it from anywhere outside the class.
If that is package-private (default), then you can use only it within that package.

A:
...could I also use it as a.f outside the class?

Yes. You can use the static method if it is declared as public:
public static void f() {
    // ...
}

or if it is package-private (no modifier):
static void f() {
    // ...
}

A: Marking the method Public will make it accessible wherever you want.
Marking the method Protected will make it accessible in same package and also in subclasses
Marking the method nothing that is keeping it default (no modifier)will make it visible inside same package
Wherever u try to access your method Just make sure that your class is also visible there!
Hope this helps!
All the best


text:
Q: Configuring Material UI with Next.js and react-apollo; correct usage of getDataFromTree I have an existing application in which I've encountered a problem.
The root of the problem, as far as I know, lies in a broken Apollo query (for example, when trying to spread data whilest it's still undefined). This leads to a wierd UI, in which there are humongous icons and to a warning of such kind:
Warning: Prop className did not match. Server: "MuiSvgIcon-root-69" Client: "MuiSvgIcon-root"
After some research, I found out that the reason of this may be the disableGeneration prop which should be set to true for performance reasons, but I also suspect that if it's turned on then MUI skips the className generation and yields correct classnames as the result.
The question is: what is the correct way to use it, or is there any other way to fix this issue? My stacks is as follows:

*

*next.js 9.1.1

*material UI 4.6.0

*react-apollo 3.1.2

I have tried several combinations of using StylesProvider and ServerStyleSheets, though I haven't managed to get the job done. Currently I'm using this in _document.js:
const sheets = new ServerStyleSheets({
  injectFirst: true
});

And this is the way I use getDataFromTree, though it looks quite odd to me:
const sheets = new ServerStyleSheets({
  disableGeneration: true
});

await getDataFromTree(sheets.collect(<AppTree {...appProps} />));

I had done a lot of googling but couldn't find a concise result of how to use SSR with Apollo & Material. Any help would be much appreciated :)


text:
Q: Api Platform pagination custom page_parameter_name I have very specific question on which I cannot find any answer and/or solution provided for Api Platform.
By default, the documentation states, that if you want to pass a page parameter for paging action, you must do the following:
pagination:
        page_parameter_name: _page

However, due to the nature of our frontend we're not able to pass this variable to the request. It is hardcoded to the frontend request and is something like page[number]=1.
Is it possible to configure page_parameter_name to receive this variable or we need to transform it somehow in the Api itself?
Thank you!

A: ApiPlatform\Core\EventListener\ReadListener::onKernelRequest gets $context['filters'] from the request through ApiPlatform\Core\Util\RequestParser::parseRequestParams which ultimately uses PHP's parse_str function so the value of 'page[number]' will be in $context$context['filters']['page']['number'].
ApiPlatform\Core\DataProvider\Pagination::getPage retrieves the page number from $context['filters'][$parameterName] so whatever the value of [$parameterName] it will at best retrieve the array ['number'=> 1].
Then ::getPage casts that to int, which happens to be 1. But will (at least with PHP7) be 1 for any value under 'number'.
Conclusion: You need to transform it somehow in the Api itself. For example by decoration of the ApiPlatform\Core\DataProvider\Pagination service (api_platform.pagination).

A: API_URL?page[number]=2
print_r($request->attributes->get('_api_pagination'));
Array(
    [number] => 2
)

The value of the "page_parameter_name" parameter should be "number" .
api_platform.yaml
collection:
    pagination:
       page_parameter_name: number

This may not work in version 3
vendor/api-platform/core/src/JsonApi/EventListener/TransformPaginationParametersListener.php
public function onKernelRequest(RequestEvent $event): void
{
  $request = $event->getRequest();
  $pageParameter = $request->query->all()['page'] ?? null;
  ...
  /* @TODO remove the `_api_pagination` attribute in 3.0 */
  $request->attributes->set('_api_pagination', $pageParameter);
}