text:
Q: Avoid CORS when using nginx to redirect to S3 I'm setting up a service worker for my site (site.foo.co) which is behind nginx.
All my assets live on my S3 server (files.foo.co).
To avoid caching opaque requests (in Chrome), the service worker needs the assets to be from the same origin.
To do that, I assume the easiest approach is to have all asset requests go to nginx, which then redirects to S3.
The problem is the browser still treats redirects as cors requests.
How can I configure nginx to proxy requests to S3 & have the browser treat it like a sameorigin request?
My attempt below successfully redirects the request, but it doesn't avoid cors.
location ^~ /static/ {
    proxy_pass https://files.foo.co;
    rewrite ([^/]*$) https://files.foo.co/$1;
}

How can I change my config to fix this? Is there another approach that might be better?


text:
Q: receive specific data from Firebase with if statement in React Native I am new with Firebase and React Native. I have created a database and now that when a certain number is equal to a number in 1 of the objects in firebase, it stores this data in an array.
I have the following code for that:
scanOutput = '0';

getUserData = () => {
    console.log(this.scanOutput);
    let ref = firebase.database().ref('Questions/1R1/NL');
    ref.on('value' , snapshot =>{
      var state = snapshot.val();

      console.log(state);

      if('1' === this.scanOutput){
        this.setState({questions: state});
      }
    })

  }

  componentDidMount(){
    this.scanOutput = this.props.navigation.getParam('output');
    this.getUserData();
  }

the database looks like this:

Currently the if statement contains a "1" hardcoded, what I want to achieve is that when this.scanOutput (in this case "1") equals "question_number" from the database, it places all data in the state.

A: Your code is reading all data under Questions/1R1/NL. Since there may be multiple questions under there, the snapshot may contain multiple child nodes. Your callback needs to handle those by looping over snapshot.forEach.
Something like this:
  let ref = firebase.database().ref('Questions/1R1/NL');
  ref.on('value' , snapshot =>{
    snapshot.forEach((question) => {
      var state = question.val();

      if(state.question_number === this.scanOutput){
        this.setState({questions: state});
      }
    })
  })

A: If snapshot returns you an object then you can destructure it:
const { question_number } = snapshot.val();
console.log(question_number);

then you can have a check like:
if(question_number === this.scanOutput){

redpajama_set_name: RedPajamaStackExchange


text:
Q: 3D volume rendering in MATLAB I started with the vol3d function from MATLAB file exchange for the 3D display part but its slowing down the entire application.
I am working on a MATLAB based GUI. Need to display a volume of size 512X512X512, single precision. The display has 4 different views of the volume. 3 standard orthogonal views and the 4th view is the 3D rendered isometric view.
With vol3D, The display is looking fine but its causing the GUI little lagging and slow. If I remove the vol3d function, the GUI works fine, faster.
I am new in the field of 3D volume rendering. What are the alternatives to this volume rendering in MATLAB. Is there any way to call some C-subroutine using mex, do the calculation in C and display in MATLAB. I have a good GPU(GeForce gtx titan x, 12 gb) but I am afraid I am not utilizing it well for the volume rendering thing.
Any suggestions are welcome.
thanx for reading :)


text:
Q: MNIST dataset with Sklearn I'm training linear model on MNIST dataset, but I wanted to train only on one digit that is 4. How do I choose my X_test,X_train, y_test, y_train?

A: Your classifier needs to learn to discriminate between sets of different classes.
If you only care about digit 4, you should split your training and testing set into:

*

*Class 4 instances

*Not class 4 instances: union of all other digits

Otherwise the train/test split is still the typical one, where you want to have no overlap.

A: If you only need to recognize 4s it's a binary classification problem, so you just need to create a new target variable: Y=1 if class is 4, Y=0 if class is not 4.

*Train_X will be unchanged

*Train_Y will be your new target variable related to Train_X

*Test_X will be unchanged

*Test_Y will be your new target variable related to Test_X.
<\ul>

Data will be a bit unbalanced but it should not be an issue!


text:
Q: How to copy text from webpage and compare it in different page in selenium java webdriver WebElementDetails webElementDetails = new WebElementDetails();
element = webElementDetails.getElement(webDriver, objectName, selector);
passValue = element.getText();
propertyFileReader.setValue("STORE_URL_SUFFIX", passValue);

I want to copy text from a reservation website and store it, then compare the same data in an email which is received as confirmation.
I tried to copy the text by using the .getText method, but with this I can store only one value, while I need to store multiple values.

A: Webdriver driver= new FirefoxDriver();
    driver.get("");//Enter the website url

WebElement str1= driver.findelement(by.xpath("xxxxxxxxxxxxxxxx").gettext();

System.setProperty("webdriver.chrome.driver", System.getProperty("user.dir")+"/Drivers/chromedriver.exe");
 driver = new ChromeDriver();
driver.get("");//Enter the 2nd Website you want to compare

    WebElement str2= driver.findelement(by.xpath("xxxxxxxxxxx").gettext();

    if (str1.equals.str2){
    System.out.Println("Text matched");
    }
    else{
    System.out.Println("Text not matched");
    }

Try the above code.


text:
Q: k8s coredns pods showing CrashLoopBackOff due to property max_concurrent I believe this issue raised after upgraded k8s to 1.19 from 1.18. I didn't checked after upgraded the cluster.
k8scka@master:~$ kubectl get pods -n kube-system
NAME                                       READY   STATUS             RESTARTS   AGE
calico-kube-controllers-7dbc97f587-dfbwl   1/1     Running            0          8d
calico-node-jkgwv                          1/1     Running            0          10d
calico-node-wkncc                          1/1     Running            0          10d
coredns-66bff467f8-frh49                   0/1     CrashLoopBackOff   2093       7d10h
coredns-66bff467f8-wlb22                   0/1     CrashLoopBackOff   2092       7d10h
etcd-master                                1/1     Running            0          8d
kube-apiserver-master                      1/1     Running            0          8d
kube-controller-manager-master             1/1     Running            0          8d
kube-proxy-ljz55                           1/1     Running            0          8d
kube-proxy-w8nvg                           1/1     Running            0          8d
kube-scheduler-master                      1/1     Running            0          8d
k8scka@master:~$

A: verified the coredns CM and removed the property max_concurrent.
automatically issue resolved.

A: else,
we can Upgrade the coredns to resolve the issue.


text:
Q: How do I find which column is being declared incorrectly? I am a junior dev working on a Sharepoint 2007 to 2010 migration and am hitting the following error when I attempt to import the template:
The formula refers to a column that does not exist. Check the formula for spelling mistakes or change the non-existing column to an existing column.
Now this template is rife with customizations and after 2 weeks of investigation by myself and the senior dev, we are yet to find the offending column/s. I wish to know if there is a definitive way to find out which column is causing us grief? The error log (which I have set to pipe everything from verbose upwards) does not seem to be providing me the required information only that "The formula refers to a column that does not exist"


text:
Q: ASP.NET MVC / C# : how to remove a record id from url? How can I remove the ID from the url in this situation below where I am loading records from my database in which each record has an ID and a SEO slug name of the record. I have searched for this dozens of times but never seem to quite get a working answer.
mypictures.com/animal/cat-pictures/1
mypictures.com/animal/dog-pictures/2
mypictures.com/animal/bird-pictures/3

In this example I have a website that has different categories of animals. Each one of these exists in the database. The Cat category has Animal_Id = 1, the dog category has Animal_Id = 2 , Bird Category Animal_Id = 3 and so on.
I want to only show the slug of that category BUT NEVER THE ID. I am using SEO friendly urls so the answer would have to take that into account. I know that one way to maybe do it is to have unique slugs for each record but still I don't even know where to begin.
Below is what my code looks like so far that makes this work with the horrible id in the url:
AnimalController:
public ActionResult Details(int? id)
{
        if (id == null)
        {
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        }

        tblAnimal tblAnimal = db.tblAnimals.Find(id);

        if (tblAnimal == null)
        {
            return HttpNotFound();
        }

        return PartialView("_animalProdListPageLoad", tblAnimal);
}

This is the cshtml view that calls the partial view _animalProdListPageLoad that loads a list of animal picture accessories once we have landed on the Animal category page. This uses the id that I am trying not to pass in the url. I added this part to the explanation to illustrate that I still need the id to load stuff that connects to the tblAnimalPictures via the Animal_Id. In this case AnimalAccessories is connected to the Animal_Id table, so I would still need the ID I just don't want it in the url if that makes sense.
@model mypictures.Models.tblAnimal

@{ Html.RenderAction("GetAnimalAccesories", "Animal", new { Animal_Id = Model.Animal_Id });

                                        @Html.HiddenFor(Model => Model.Animal_Id)

                                        ViewBag.Store_Id_Passed = Model.Animal_Id;
                                    }

Then in my RouteConfig I have the following to show the SEO friendly routes:
routes.Add("AnimalDetails",
               new SeoFriendlyRoute2("animal/{slug}/{id}",
               new RouteValueDictionary(new { controller = "Animal", action = "Details" }),
               new MvcRouteHandler()));

Then I have a class that handles that SeoFriendlyRoute2 that looks like this:
public class SeoFriendlyRoute2 : System.Web.Routing.Route
{
    public SeoFriendlyRoute2(string url, RouteValueDictionary defaults, IRouteHandler routeHandler) : base(url, defaults, routeHandler)
    {
    }

    public override RouteData GetRouteData(HttpContextBase httpContext)
    {
        var routeData = base.GetRouteData(httpContext);

        if (routeData != null)
        {
            if (routeData.Values.ContainsKey("id"))
                routeData.Values["id"] = GetIdValue(routeData.Values["id"]);
        }

        return routeData;
    }

    private object GetIdValue(object id)
    {
        if (id != null)
        {
            string idValue = id.ToString();

            var regex = new Regex(@"^(?<id>\d+).*$");
            var match = regex.Match(idValue);

            if (match.Success)
            {
                return match.Groups["id"].Value;
            }
        }

        return id;
    }

    private object GetslugValue(object slug)
    {
        if (slug != null)
        {
            string slugValue = slug.ToString();

            var regex = new Regex(@"^(?<id>\d+).*$");
            var match = regex.Match(slugValue);

            if (match.Success)
            {
                return match.Groups["id"].Value;
            }
        }

        return slug;
    }
}

Then in the tblAnimal model I have this, which is what generates the seo url slug:
public string GenerateSlug2()
    {

        string phrase2 = string.Format("{0}-{1}", Animal_Id, slug);

        string str2 = RemoveAccent2(phrase2).ToLower();
        // invalid chars
        str2 = Regex.Replace(str2, @"[^a-z0-9\s-]", "");
        // convert multiple spaces into one space
        str2 = Regex.Replace(str2, @"\s+", " ").Trim();
        // cut and trim
        str2 = str2.Substring(0, str2.Length <= 45 ? str2.Length : 45).Trim();
        str2 = Regex.Replace(str2, @"\s", "-"); // hyphens
        return str2;
    }

    private string RemoveAccent2(string text)
    {
        byte[] bytes = System.Text.Encoding.GetEncoding("Cyrillic").GetBytes(text);
        return System.Text.Encoding.ASCII.GetString(bytes);
    }

Then finally when run the application and navigate to the animal category for any of the records like Dog it looks like this:
mypictures.com/animal/dog-pictures/2

but I REALLY need this instead:
mypictures.com/animal/dog-pictures

Please Help Me, I have been stuck on this for months and really need a solution.
I have already tried this and just get a 404: I removed the id from the route config since I thought that was a possible solution but its not.
routes.Add("AnimalDetails", new SeoFriendlyRoute2("animal/{slug}",
   new RouteValueDictionary(new { controller = "Animal", action = "Details" }),
    new MvcRouteHandler()));

A: edit your route config like this
routes.Add("AnimalDetails", new SeoFriendlyRoute2("animal/{slug}",
       new RouteValueDictionary(new { controller = "Animal", action = "Details" }),
        new MvcRouteHandler()));


text:
Q: Is there a Redmine plugin for listing projects and their repositories? Is there a Redmine plugin for listing projects and their repositories?
I have a lot of small projects not regularly used and it can be useful see which repositories they use without having to open the Settings page.


text:
Q: No Compatible Devices Found using WebHID on Chrome I am trying to use the ACR122U NFC Reader with the WebHID API but I cannot seem to get it to be found by Chrome 91 Desktop on both Linux nor Windows.
I know the browser is seeing the reader from chrome://usb-internals showing me this screen:

The two pieces of code that I have tried so far is here seen through the Inspect Element tools in the script tag.
The VendorID and ProductID in the scripts match that which Chrome can recognise it through, so I'm not sure why it is not working for this.
The only popup dialog that I have gotten the reader to appear within is the Chrome NFC WebUSB but I cannot use that API as it implements a protected class, which is why I am using WebHID as the alternative in hopes it may work.
How do I correct my code to allow Chrome to recognise this device; what am I missing?

A: I was able to control the ACR122U NFC Reader through WebUSB. See the library I've updated at https://github.com/beaufortfrancois/chrome-nfc
What is not working for you?

A: I think this won't work because ARC122U NFC Reader doesn't implement the HID protocol. According to the product page, it uses the USB CCID protocol.


text:
Q: SAX XMLParser not working I have followed multiple online tutorials on how to set up a SAX XML parser for the Android platform but none of them seem to work! Whats the problem? Heres my code:
Imports:
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import android.app.Activity;
import android.util.Log;

This Code is in a method that I know gets called, but why doesent logcat show "TESTING"?
 try {
                URL XMLURL = new URL("https://gdata.youtube.com/feeds/api/videos?q=Crystallize+Lindsey+Stirling+Offical+Music+Video&orderby=relevance");
                SAXParserFactory SPF = SAXParserFactory.newInstance();
                SAXParser SP = SPF.newSAXParser();

                DefaultHandler mainHandler = new DefaultHandler(){

                    @Override
                    public void startElement(String uri, String localName,
                            String qName, Attributes attributes)
                            throws SAXException {

                        if(localName.equals("Link")){

                            String possibleURL = attributes.getValue("href");
                            Log.i("TEST","TESTING");
                        }

                    }
                };

                SP.parse(new InputSource(XMLURL.openStream()),mainHandler);
            } catch (Exception e) {
                e.printStackTrace();

            }

Thanks for any and all help!

A: This is a namespace issue.
SAXParserFactory SPF = SAXParserFactory.newInstance();
SAXParser SP = SPF.newSAXParser();

is giving you a parser that doesn't properly handle namespaces.
If you change the startElement to check qName for the value "link", your code will work, but that's sort of a band-aid fix.
There are namespaces in this document, though this element is in the default namespace http://www.w3.org/2005/Atom specified for the document.
You should tell the parser factory to give you a namespace-aware parser:
SAXParserFactory SPF = SAXParserFactory.newInstance();
SPF.setNamespaceAware(true);
SAXParser SP = SPF.newSAXParser();

And then you'll get the expected result without changing the startElement method, except you do have to look for the right value, i.e., check for "link" instead of "Link".

A: Check your logcat for a big chunk of yellow text. It may inform you about any errors that crashed the SAX parser.


text:
Q: Importing MSSQL database backup to MySQL workbench Due to a change in jobs, I've recently had to move over to mac, but before I left, I made a backup of all my local MSSQL databases containing a lot of important work.
Is there any way I can bring these into MySQL workbench, without the use of a windows PC to alter the backups?

A: You cannot. SQL Server backups can only be restored to an instance of SQL Server. On-disk structures, data types, stored procedures, functions, etc. all have differences.
The reverse is true as well - you can't "import" a MySQL backup into SQL Server.
You will need to restore your SQL Server backup into an instance of SQL Server, then export the data from SQL Server into MySQL. The Import/Export Wizard in SSMS may be able to help you if you have the appropriate drivers, otherwise you'll be writing your own ETL process in your language/environment of choice. You'll probably want to create your table schema in MySQL first, to ensure the appropriate data types are used. Programmable features (stored procs, UDFs, triggers, etc.) will need to be re-implemented using the proper dialect of SQL for MySQL as it doesn't speak T-SQL.


text:
Q: Tomcat with Postgres Certificate connectivity Issue [FATAL: connection requires a valid client certificate] We are facing issue with connecting to Postgres SQL database with certificate (pk8 and key file) in tomcat using Java web application, however when we try to connect with Java standalone we can able to connect.
Upon checking the Catalina logs we found the error –

org.postgresql.util.PSQLException: FATAL: connection requires a valid client certificate

Below is the connection params used in Java web application (as per documentation), the same works fine when tried with standalone application (Refer screen shot below)
jdbc:postgresql://:/<DB_NAME>?sslmode=require&sslcert=/app/localstorage/UAT_Certs/FA1234.crt&sslkey=/app/localstorage/UAT_Certs/FA1234.pk8&sslpassword=XXXX&user=XXXX

Standalone Successful connection:
java -cp postgresql-9.3-1102-jdbc41.jar:Query.jar com.company.test.Query

URL used to connect to Database is
jdbc:postgresql://example.com:5432/sample?sslmode=require&sslcert=/app/localstorage/FA1234.crt&sslkey=/app/localstorage/FA1234.pk8&sslpassword=test&user=test_name

Output:
Current Time in Database is 12:15:48.738587+01

Below is the code which we use in Tomcat to create Data source by passing the necessary DB information:
public  class SecureTomcatDataSourceImpl extends DataSourceFactory {

    private EncDecJDBCPass encryptor = null;
    public SecureTomcatDataSourceImpl() {
        try {
                encryptor = new EncDecJDBCPass();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public DataSource createDataSource(Properties properties, Context context, boolean XA) throws InvalidKeyException,
            IllegalBlockSizeException, BadPaddingException, SQLException, NoSuchAlgorithmException,
            NoSuchPaddingException, UnrecoverableKeyException, KeyManagementException, CertificateException, FileNotFoundException, KeyStoreException, IOException {

        System.out.println("Inside createDataSource() method. ");

        //fetching pfx file  encrypted password from context.xml
        PoolConfiguration poolProperties = SecureTomcatDataSourceImpl.parsePoolProperties(properties);

        //poolProperties.setPassword(pwd);

        poolProperties.setPassword(null);
        poolProperties.setUsername("XXXX");
        String urlVal = poolProperties.getUrl();
        System.out.println("Before Append"+urlVal);
        String appendUrlVal =   "jdbc:postgresql://:/<DB_NAME>?sslmode=require&sslcert=/app/localstorage/UAT_Certs/FA1234.crt&sslkey=/app/localstorage/UAT_Certs/FA1234.pk8&sslpassword=XXXX&user=XXXX"

        System.out.println("AppendUrlVal:::::::::::::::"+appendUrlVal);

        poolProperties.setUrl(appendUrlVal);

        // The rest of the code is copied from Tomcat's DataSourceFactory.
        if (poolProperties.getDataSourceJNDI() != null && poolProperties.getDataSource() == null) {
            performJNDILookup(context, poolProperties);
        }
        org.apache.tomcat.jdbc.pool.DataSource dataSource = XA ? new XADataSource(poolProperties)
                : new org.apache.tomcat.jdbc.pool.DataSource(poolProperties);

        String Name = SecureTomcatDataSourceImpl.getProperties("name").toString();
        String URL = poolProperties.getUrl();
        System.out.println("URL VALUE::::::::"+URL);
        String username = poolProperties.getUsername();
        Logger.getLogger(SecureTomcatDataSourceImpl.class.getName()).log(Level.INFO, "Creating a New Connection Pool for DataSource "+Name+" with URL "+URL+" and the  username "+username);

        dataSource.createPool();

        return dataSource;
    }

}

Code used in Standalone Program:
import java.sql.*;
import java.util.Properties;

public class Query {

    public static void main(String[] args) {

        try {

            String url = "jdbc:postgresql://:/<DB_NAME>?sslmode=require&sslcert=/app/localstorage/UAT_Certs/FA1234.crt&sslkey=/app/localstorage/UAT_Certs/FA1234.pk8&sslpassword=XXXX&user=XXXX"

            System.out.println("URL used to connect to Database is " + url);

            Connection conn = DriverManager.getConnection(url);

            Statement stmt = conn.createStatement();
            ResultSet rs = stmt.executeQuery("select current_time");
            while (rs.next()) {
                System.out.println("Current Time in Database is :::::::::::::::::::::::::" + rs.getString("current_time"));
            }
            conn.close();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}


text:
Q: How to Fix Javascript Search Function in Spring Boot Application This is my first post, so apologies if this is not done properly.
I'm currently working on a Javascript search function in my Spring Boot app and am unable to figure out why it's not producing search results.
I've searched the interwebs to find something that might help, but have not found anything useful.
I've tried looking at the controller as well as the Javascript, but I'm still pretty new, so I can't seem to put my finger on what the problem might be.
Gradle dependencies:
dependencies {
        compile('org.springframework.boot:spring-boot-starter-data-jpa')
        compile('org.springframework.boot:spring-boot-starter-thymeleaf')
        compile('org.springframework.boot:spring-boot-starter-web')
        runtime('org.springframework.boot:spring-boot-devtools')
        runtime('com.h2database:h2')
        testCompile('org.springframework.boot:spring-boot-starter-test')
    }

Controller
    @RequestMapping(path = "/searchBy/{barcode}", method = GET)
    public String searchAllByBarcode(@PathVariable String barcode, Model model) {
        model.addAttribute("foundItems", itemRepo.findAllByBarcode(barcode));
        return "find";
    }

Javascript:
searchItems
document.addEventListener("DOMContentLoaded", function() {
    const addItemButton = document.querySelector('#findItems');
    addItemButton.addEventListener('click',searchItems)
});

function searchItems(){
    const barcode = document.querySelector('#info_input').value
    const xhr = new XMLHttpRequest()
        xhr.onreadystatechange = function () {
            if (xhr.readyState === 4 && xhr.status === 200) {
                console.log(xhr);
                console.log(barcode);
            }
        }

    xhr.open('GET', '/searchBy/'+ barcode, true)
    xhr.send()
}

HTML:

Search an Item!

                <form method="GET">

                        <select>
                            <option value="0">Search Item By:</option>
                            <option value="1">Barcode:</option>
                            <option value="2">Quantity:</option>
                            <option value="3">Expiration Date:</option>
                            <option value="4">Name:</option>
                            <option value="5">Unit:</option>
                            <option value="6">Location:</option>
                            <option value="7">Description:</option>
                            <option value="8">Mercedes</option>
                        </select>

                    <input type="text" name="input" maxlength="200" id="info_input" autofocus="true" required="true" />
                    <input type="submit" id="findItems" name="myButton" value="Search" />
                </form>

                    <button type="submit" class="deleteItem" th:attr="data-id=${item.id}" for="id" name="id">Remove</button>

                <button class="add_item_button">Add</button>

                <button class="delete_button">Delete</button>

                <button class="home_button">Home</button>

This should be pulling the data from the database and displaying an inventory item, but instead, it shows no results. I'm not sure if it's the Javascrpt, controller, html or all the above.
Please let me know if there is anything more that's needed and I'll be happy to provide.
Thank you in advance for all the help.


text:
Q: SitePages uses System Master Page Bit of a strange issue today.
I wasn't involved in the initial branding/master pages etc of my companie's SP Environment. Anyways, I have a strange issue.
On my site, I have some pages storted under the Pages Library and some under SitePages. Now I know that that SitePages uses Wiki pages and Pages Library allows you to use custom Page Layouts.
My issue howver is, that when I change the the System Master page on a site to a Wide Layout (Predefined Master page), then all pages in SitePages also adopts this look and feel. Pages Library stays unaffected. Surely SitePages (Wiki pages) should only be affted when changing the "Site Master Page" and not when changing "System Master Page "
Any ideas on why this is happening?

A: This is expected behavior:
The Site Master Page, affects Publishing Pages (/Pages)
The System Master Page, affects Wiki Pages (/SitePages)
http://blogs.technet.com/b/stefan_gossner/archive/2011/04/13/site-master-page-vs-system-master-page.aspx


text:
Q: Changing badge count in Push Notifications with Expo in background and foreground I was looking into ways to send push notifications to a native app and reading the expo documentation, I got confused by two bits of information that seem to contradict each other.

Notifications will appear in the system notification tray as you've
  come to expect, and tapping them will open/foreground the app.

(source: https://docs.expo.io/versions/latest/guides/push-notifications)
But in the section 'why not expo'  it states :

Expo apps don't support background code execution (running code when
  the app is not foregrounded or the device is sleeping). This means you
  cannot use background geolocation, play audio in the background,
  handle push notifications in the background, and more.

(source: https://docs.expo.io/versions/latest/introduction/why-not-expo)
That seems contradictory since 'foregrounding' or 'opening' an app implies that it was running in the background how I see it.
In the end I would like to change the notification badge of an app icon with this, but given this info it's not clear to me if this is possible ?   In IOS and Android ?

A: Indeed foregrounding the app sounds as if the app was actively running in the background and could therefore run code, but as the documentation states, this is not currently feasible with Expo alone. This entails that changing the badge count while the app is in background cannot be done.
On the other hand, when the app is in foreground or the notification is being open, this becomes feasible according to this table in the documentation.
Setting an arbitrary badge count on iOS can be done with Notifications.setBadgeNumberAsync(number), whereas for Android the only option available is to make the sent push notifications count towards the badge count for a given channel.

A: remove notification badge count for android - Notifications.dismissAllNotificationsAsync()
expo dismissAllNotificationAsync


text:
Q: How to setup node and cli in tron? I need to develop a tron node and tron cli in local server. I have followed java tron documentation but in java tron there is no cli. Then I moved to tron cli GitHub and I install all packages. I ran tron cli. Then how to run node and deploy contract in tron cli?

A: Have a look at https://github.com/andelf/rust-tron, it is a powerful cli tool for tron.
Contract dev Doc.


text:
Q: change view from list to grid after click I've created list view using bootstrap 5:

    Click to switch to grid/list

and here I've content list:

list view
...
.....
.......

and here I've content grid:

grid view
...
.....
.......

List view is enabled by default.
Can anyone help me if I click Click to switch to grid/list then remove tag from grid d-none and add  d-none to tag list ?
and again when I click then rewrite changes ?
I try somelike this:
<button onclick="myFunction()">Click to switch to grid/list</button>

But this not work for me and I cannot get effect which I try and with this code not possible rewrite changes.  I read every questions/answears here   but none suit me and I can't implement it to my solution.

A: This should work, it toggles the visibility between the two using style.display
    <button id="toggleButton">Toggle View</button>

    list view
    ...
    .....
    .......

    grid view
    ...
    .....
    .......


text:
Q: Google Places API - adding new types, Flutter When I perform a general search of farmers markets on Google maps on my desktop, it shows all of the markets. But farmers markets is not listed as an available "type" in the Google Places API. Is there a way to add types that are not specifically listed in the API? If not available using the Places API, could I create a separate class that would be incorporated into Google Maps that captures all the specific locations I'm wanting to provide to the user of the app?

A: Thanks to the below thread, it appears that rather than using one of the specific "types" listed in Google Places, you can instead you "keyword" to limit your search to particular locations that are not included in the Google Places type categories. Thanks to this thread which helped me find this answer.


text:
Q: Using `pyhf` to float both signal and background strength Hi pyhf users and developers!
I have a question that follows from a previous question and so I'll start with the anwser.py code provided in one of the responses and thena minor modification.
So I run the fit with the parameters given in the response but I then want to see the results of the fit, so I add some code to weight the original templates by the fit results and replot it with the overlays. The full script is below.

import pyhf
import pyhf.contrib.viz.brazil

import numpy as np
import matplotlib.pylab as plt

#    - Get the uncertainties on the best fit signal strength
#    - Calculate an 95% CL upper limit on the signal strength

tag = "ORIGINAL"

def plot_hist(ax, bins, data, bottom=0, color=None, label=None):
    bin_width = bins[1] - bins[0]
    bin_leftedges = bins[:-1]
    bin_centers = [edge + bin_width / 2.0 for edge in bin_leftedges]
    ax.bar(
        bin_centers, data, bin_width, bottom=bottom, alpha=0.5, color=color, label=label
    )

def plot_data(ax, bins, data, label="Data"):
    bin_width = bins[1] - bins[0]
    bin_leftedges = bins[:-1]
    bin_centers = [edge + bin_width / 2.0 for edge in bin_leftedges]
    ax.scatter(bin_centers, data, color="black", label=label)

def invert_interval(test_mus, hypo_tests, test_size=0.05):
    # This will be taken care of in v0.5.3
    cls_obs = np.array([test[0] for test in hypo_tests]).flatten()
    cls_exp = [
        np.array([test[1][idx] for test in hypo_tests]).flatten() for idx in range(5)
    ]
    crossing_test_stats = {"exp": [], "obs": None}
    for cls_exp_sigma in cls_exp:
        crossing_test_stats["exp"].append(
            np.interp(
                test_size, list(reversed(cls_exp_sigma)), list(reversed(test_mus))
            )
        )
    crossing_test_stats["obs"] = np.interp(
        test_size, list(reversed(cls_obs)), list(reversed(test_mus))
    )
    return crossing_test_stats

def main():
    np.random.seed(0)
    pyhf.set_backend("numpy", "minuit")

    observable_range = [0.0, 10.0]
    bin_width = 0.5
    _bins = np.arange(observable_range[0], observable_range[1] + bin_width, bin_width)

    n_bkg = 2000
    n_signal = int(np.sqrt(n_bkg))

    # Generate simulation
    bkg_simulation = 10 * np.random.random(n_bkg)
    signal_simulation = np.random.normal(5, 1.0, n_signal)

    bkg_sample, _ = np.histogram(bkg_simulation, bins=_bins)
    signal_sample, _ = np.histogram(signal_simulation, bins=_bins)

    # Generate observations
    signal_events = np.random.normal(5, 1.0, int(n_signal * 0.8))
    bkg_events = 10 * np.random.random(int(n_bkg + np.sqrt(n_bkg)))

    observed_events = np.array(signal_events.tolist() + bkg_events.tolist())
    observed_sample, _ = np.histogram(observed_events, bins=_bins)

    # Visualize the simulation and observations
    fig, ax = plt.subplots()
    fig.set_size_inches(7, 5)

    plot_hist(ax, _bins, bkg_sample, label="Background")
    plot_hist(ax, _bins, signal_sample, bottom=bkg_sample, label="Signal")
    plot_data(ax, _bins, observed_sample)
    ax.legend(loc="best")
    ax.set_ylim(top=np.max(observed_sample) * 1.4)
    ax.set_xlabel("Observable")
    ax.set_ylabel("Count")
    fig.savefig("components_{0}.png".format(tag))

    # Build the model
    bkg_uncerts = np.sqrt(bkg_sample)
    model = pyhf.simplemodels.hepdata_like(
        signal_data=signal_sample.tolist(),
        bkg_data=bkg_sample.tolist(),
        bkg_uncerts=bkg_uncerts.tolist(),
    )
    data = pyhf.tensorlib.astensor(observed_sample.tolist() + model.config.auxdata)

    # Perform inference
    fit_result = pyhf.infer.mle.fit(data, model, return_uncertainties=True)
    bestfit_pars, par_uncerts = fit_result.T
    print(
        f"best fit parameters:\
        \n * signal strength: {bestfit_pars[0]} +/- {par_uncerts[0]}\
        \n * nuisance parameters: {bestfit_pars[1:]}\
        \n * nuisance parameter uncertainties: {par_uncerts[1:]}"
    )

    # Visualize the results
    fit_bkg_sample = []
    for w,b in zip(bestfit_pars[1:],bkg_sample):
        fit_bkg_sample.append(w*b)

    fit_signal_sample = bestfit_pars[0]*np.array(signal_sample)

    fig, ax = plt.subplots()
    fig.set_size_inches(7, 5)

    plot_hist(ax, _bins, fit_bkg_sample, label="Background")
    plot_hist(ax, _bins, fit_signal_sample, bottom=fit_bkg_sample, label="Signal")
    plot_data(ax, _bins, observed_sample)
    ax.legend(loc="best")
    ax.set_ylim(top=np.max(observed_sample) * 1.4)
    ax.set_xlabel("Observable")
    ax.set_ylabel("Count")
    fig.savefig("components_after_fit_{0}.png".format(tag))

    # Perform hypothesis test scan
    _start = 0.0
    _stop = 5
    _step = 0.1
    poi_tests = np.arange(_start, _stop + _step, _step)

    print("\nPerforming hypothesis tests\n")
    hypo_tests = [
        pyhf.infer.hypotest(
            mu_test,
            data,
            model,
            return_expected_set=True,
            return_test_statistics=True,
            qtilde=True,
        )
        for mu_test in poi_tests
    ]

    # Upper limits on signal strength
    results = invert_interval(poi_tests, hypo_tests)

    print(f"Observed Limit on µ: {results['obs']:.2f}")
    print("-----")
    for idx, n_sigma in enumerate(np.arange(-2, 3)):
        print(
            "Expected {}Limit on µ: {:.3f}".format(
                "       " if n_sigma == 0 else "({} σ) ".format(n_sigma),
                results["exp"][idx],
            )
        )

    # Visualize the "Brazil band"
    fig, ax = plt.subplots()
    fig.set_size_inches(7, 5)

    ax.set_title("Hypothesis Tests")
    ax.set_ylabel(r"$\mathrm{CL}_{s}$")
    ax.set_xlabel(r"$\mu$")

    pyhf.contrib.viz.brazil.plot_results(ax, poi_tests, hypo_tests)
    fig.savefig("brazil_band_{0}.png".format(tag))

if __name__ == "__main__":
    main()

When I run it, I get the following plots. The first is original observations/simulation and the second plot has the simulation scaled by the fit results.

So this all looks good and I think I understand what his happening.
But now I ask a question, which is better illustrated with a slight variation on your example.
I'm going to modify the generated simulations and observations such that there are a different number of background events in the simulations and samples. I'm also making the signal more significant. This would be an example where I've not been able to get a good estimation of the background contribution(s) prior to doing the fit. In the example you provide, the number of background events is the same for the simulated sample and data, which is not going to be the case in the real world.
So I go to the above code and I change these lines.
    n_bkg = 2000
    n_signal = 200

    # Generate simulation
    bkg_simulation = 10 * np.random.random(n_bkg)
    signal_simulation = np.random.normal(5, 1.0, n_signal)

    bkg_sample, _ = np.histogram(bkg_simulation, bins=_bins)
    signal_sample, _ = np.histogram(signal_simulation, bins=_bins)

    # Generate observations
    signal_events = np.random.normal(5, 1.0, int(n_signal * 0.8))
    bkg_events = 10 * np.random.random(n_bkg - 300)

The fit isn't great, and I wouldn't expect it to be since I locked down the number of background events, modulo the Poisson fluctuations in each bin. The relevant plots (before/after fit) are shown here.

I might have thought another way to approach this would be to add another non-nuisance, floating parameter that represents the background strength, while still letting the individual bins vary within Poisson fluctuations. For that matter, couldn't (shouldn't?) the signal bins fluctuate as well?
In that case, I would then start with my a vastly larger number of data points in my simulated samples to get the more "true" (I know that's not rigorous) distribution. Once the fit drives the number of signal/background events down, Poisson fluctuations would become more significant.
I'm sure the optimization/minimization of the likelihood function becomes much more difficult but it also feels like we're constraining the fit too early if we lock down the bulk background normalization. Or maybe I'm missing something?
Thanks as always for your help and response!

A: you should be able to add a new nuisance by adding a "normfactor" modifier to the background component
e.g.
spec = {'channels': [{'name': 'singlechannel',
   'samples': [{'name': 'signal',
     'data': [10.0],
     'modifiers': [{'name': 'mu', 'type': 'normfactor', 'data': None}]},
    {'name': 'background',
     'data': [50.0],
     'modifiers': [{'name': 'bkgnorm',
       'type': 'normfactor',
       'data': None}]}]}]}

see the symmetry between signal and background


text:
Q: Cocoa: Appending Audio to an existing file My application uses the AVFoundation framework to record audio. The first time the user records some audio it works like a charm. However, when the user records additional audio, I would like to append this audio to the end of the existing file. I can't figure out how to do this. I've tried simply appending the NSData itself to the existing NSData, but this doesn't work:
NSError *error;
//This is the newly recorded second bit of audio saved to a temp file.
NSData *data = [NSData dataWithContentsOfFile:tempInputFilePath options:0  error:&error];

//Here I get out the old audio data that I have saved.
NSMutableData *mData = [fileBrowserVC.currentlySelectedFile.audioContent mutableCopy];
 NSLog(@"%lu",(unsigned long)mData.length);
if (mData==nil) {
    mData = [[NSMutableData alloc] init];
}

[mData appendData:data];
 NSLog(@"%lu",(unsigned long)mData.length);

fileBrowserVC.currentlySelectedFile.audioContent = mData;
[[AppDelegate sharedDelegate] saveAction:nil];

When I try to play back the newly created audio content, only the first piece of audio is played. Is this something that's not going to work, or is there something wrong with this code?
Is there another way to append audio to an existing file?

A: I was able to achieve this using AVMutableComposition as shown in this Apple article.


text:
Q: Mongoid winningPlan does not use compound index I have a compound index as follows.
  index({ account_id: 1, is_private: 1, visible_in_list: 1, sent_at: -1, user_id: 1, status: 1, type: 1, 'tracking.last_opened_at' => -1 }, {name: 'email_page_index'})

Then I have a query with these exact fields,
selector:
{"account_id"=>BSON::ObjectId('id'), "is_private"=>false, "visible_in_list"=>{:$in=>[true, false]}, "status"=>{:$in=>["ok", "queued", "processing", "failed"]}, "sent_at"=>{"$lte"=>2021-03-22 15:29:18 UTC}, "tracking.last_opened_at"=>{"$gt"=>1921-03-22 15:29:18 UTC}, "user_id"=>BSON::ObjectId('id')}
options:  {:sort=>{"tracking.last_opened_at"=>-1}}

The winningPlan is the following
"inputStage": {
    "stage": "SORT_KEY_GENERATOR",
    "inputStage": {
      "stage": "FETCH",
      "filter": {
        "$and": [
          {
            "account_id": {
              "$eq": {
                "$oid": "objectid"
              }
            }
          },
          {
            "is_private": {
              "$eq": false
            }
          },
          {
            "sent_at": {
              "$lte": "2021-03-22T14:06:10.000Z"
            }
          },
          {
            "tracking.last_opened_at": {
              "$gt": "1921-03-22T14:06:10.716Z"
            }
          },
          {
            "status": {
              "$in": [
                "failed",
                "ok",
                "processing",
                "queued"
              ]
            }
          },
          {
            "visible_in_list": {
              "$in": [
                false,
                true
              ]
            }
          }
        ]
      },
      "inputStage": {
        "stage": "IXSCAN",
        "keyPattern": {
          "user_id": 1
        },
        "indexName": "user_id_1",
        "isMultiKey": false,
        "multiKeyPaths": {
          "user_id": []
        },.....

And the rejected plan has the compound index and forms as follows
"rejectedPlans": [
  {
    "stage": "FETCH",
    "inputStage": {
      "stage": "SORT",
      "sortPattern": {
        "tracking.last_opened_at": -1
      },
      "inputStage": {
        "stage": "SORT_KEY_GENERATOR",
        "inputStage": {
          "stage": "IXSCAN",
          "keyPattern": {
            "account_id": 1,
            "is_private": 1,
            "visible_in_list": 1,
            "sent_at": -1,
            "user_id": 1,
            "status": 1,
            "type": 1,
            "tracking.last_opened_at": -1
          },
          "indexName": "email_page_index",
          "isMultiKey": false,
          "multiKeyPaths": {
            "account_id": [],
            "is_private": [],
            "visible_in_list": [],
            "sent_at": [],
            "user_id": [],
            "status": [],
            "type": [],
            "tracking.last_opened_at": []
          },
          "isUnique": false,

The problem is that the winningPlan is slow, wouldn't be better if mongoid choose the compound index? Is there a way to force it?
Also, how can I see the execution time for each separate STAGE?

A: I am posting some information that can help resolve the issue of performance and use an appropriate index. Please note this may not be the solution (and the issue is open to discussion).

...Also, how can I see the execution time for each separate STAGE?

For this, generate the query plan using the explain with the executionStats verbosity mode.

The problem is that the winningPlan is slow, wouldn't be better if
mongoid choose the compound index? Is there a way to force it?

As posted the plans show a "stage": "SORT_KEY_GENERATOR", implying that the sort operation is being performed in the memory (that is not using an index for the sort). That would be one (or main) of the reasons for the slow performance. So, how to make the query and the sort use the index?
A single compound index can be used for a query with a filter+sort operations. That would be an efficient index and query. But, it requires that the compound index be defined in a certain way - some rules need to be followed. See this topic on Sort and Non-prefix Subset of an Index - as is the case in this post. I quote the example from the documentation for illustration:
Suppose there is a compound index: { a: 1, b: 1, c: 1, d: 1 }
And, all the fields are used in a query with filter+sort. The ideal query is, to have a filter+sort as follows:
db.test.find( { a: "val1", b: "val2", c: 1949 } ).sort( { d: 1 })

Note the query filter has three fields with equality condition (there are no $gt, $lt, etc.). Then the query's sort has the last field d of the index. This is the ideal situation where the index will be used for the query''s filter as well as sort operations.
In your case, this cannot be applied from the posted query. So, to work towards a solution you may have to define a new index so as to take advantage of the rule Sort and Non-prefix Subset of an Index.
Is it possible? It depends upon your application and the use case. I have an idea like this and it may help. Create a compound index like the follows and see how it works:
account_id: 1,
is_private: 1
visible_in_list: 1,
status: 1,
user_id: 1,
'tracking.last_opened_at': -1

I think having a condition "tracking.last_opened_at"=>{"$gt"=>1921-03-22 15:29:18 UTC}, in the query''s filter may not help for the usage of the index.
Also, include some details like the version of the MongoDB server, the size of collection and some platform details. In general, query performance depends upon many factors, including, indexes, RAM memory, size and type of data, and the kind of operations on the data.

The ESR Rule:
When using compound index for a query with multiple filter conditions and sort, sometimes the Equality Sort Range rule is useful for optimizing the query. See the following post with such a scenario: MongoDB - Index not being used when sorting and limiting on ranged query


text:
Q: The order of the group G where $x^{11}=e$
Let $(G,*)$ a finite group such that for any $x\in G$ $x^{11}=e$ where $e$ is the nuetral element of the group $G$. Than the order of the group $G$ can be:
a) $1331$
b) $131$
c) $3113$
d) $313$

I know that if $x^{11}=e$ than $11\mid {\rm ord}(G)$ ( the order of $G$) so the answers can be a) or c) but I do not know another criteria which can help me to solve the problem.

A: By Lagrange's Theorem, since $x^{11}=e$ (and $11$ is prime), $\lvert x\rvert=11$ divides the order of the group. Note that $3113/11=283$ is prime, so, by Cauchy's Theorem, the group would have to have an element of order $283$
So you're nearly right.
Another useful tip here is a criterion for showing a number $n$ is divisible by $11$. We have $11\mid n=\overline{n_1\dots n_m}$ if and only if the sum $$\sum_{i=1}^m(-1)^{i}n_i$$ is divisible by $11$, where $n=\overline{n_1\dots n_m}$ is the decimal expansion of $n$.

A:
If $G $ is finite and has exponent  $p $, $p$ prime,  then $|G|=p^m $ for some  $m $.

If not, then by Cauchy's theorem there is an element  $g $ of order $q\ne p$, for $q$ a prime.  And $g^p\ne e$, since that would imply  $q\mid p $.

A: Hint: If all non-neutral elements have order $11$, then the group has order $10m+1$.


text:
Q: Proper way of chaining RSVP promises So I have a function data.people() which sends and http request and receives data, therefore I am using promises and this function returns a promise. After that I use the folowing chaining
data.people()
.then(function() {

    ....
}, function(err) {
    console.error(err);
}).then(function() {
        ...
}, function(err) {
    console.error(err);
}).then ...

So am I writing this correct, cause I can't find any documentary on this and when I attach an eventListener to one element with a given id in the third promise, it executes before the second promise is executed (where this element is changed with another with the same id) and doesn't work in the third promise (where I need it to). Here is my full code in jsfiddle.

A: Yes, you are writing works but far from optimal.
There is no reason to chain .then calls unless you are returning a promise from one of them in which case it'll wait until the asynchronous operation will complete.
Your code can be simplified to:
data.people().then(function(people){
    //rest of code here
});

Since none of your thens return promises.
Promises that don't return a promise will continue to the next .then almost instantly.
Also, if you do chain handlers and want to access the return value in later .then calls you have to return the data from that .then handler.


text:
Q: Update Facebook Status message using an Atmega16 microcontroller How can I access Facebook and post a status message using an Atmega16 microcontroller ?
Or what all things I should know for doing this?

A: This is half software, half hardware question.
From the hardware side, you'll need a way to get the ATMega connected to some Ethernet so it can connect to the Internet. There is no native support for Ethernet on an ATmega16, so you'll need to use a supporting IC that will do the Ethernet for you. These supporting chips usually communicate to another processor (your ATMega, in this case), over a simple serial link, such as SPI or I2C. As Garrett Fogerlie mentioned, you can take a look at some of the Arduino shields. You don't have to use an Arduino - just look at how the circuit works.
The Arduino Ethernet shield uses a supporting IC that communicates over the SPI bus. So first, you should figure out how to get SPI working on you ATMega. After that, this question starts to tread into software territory quite quickly. As others have mentioned, the software side of this is likely less than trivial. I don't know anything about communicating with Facebook, so I'll stop here.

A: There are four ways to do it. First is tethered to a computer (essentially using the microcontroller as a glorified sensor) with the computer running software to actually do the status updating. The second is the same, but with a router or bluetooth+cellphone other embedded computer instead (DDWRT or Openwrt is always a good starting point).
The third is semi-standalone. You use your atmega16 with a network connection (an ethernet shield or wifi shield, w5100 or ENC28J60, or serial to ethernet or serial to wifi modules, gsm modems, etc) talking to a php web host you run, that actually talks to the facebook api.
The fourth is that you do all of this on your atmega16, talking to Facebook's api directly, without needing a computer or router or web host.
These are from easiest to hardest.
For the most part, haven't seen any arduino or similar project that succeeds in complete standalone. Facebook requires OAuth for posting status updates, and running that on a microcontroller isn't easy or feasible or frankly been done. Killed alot of twitter microcontroller projects until Supertweet came out (twitter oauth/microcontroller basic auth proxy)


text:
Q: What could be regex for below logs? I want to remove numbers from first bracket and keep all the rest of the bracket intact.
Mar 17 00:03:13   %ASA-5-106100: access-list   permitted tcp  10.252.0.165(50811) ->  172.19.26.33(4902)
Mar 17 00:03:16   %ASA-5-106100: access-list   permitted tcp  10.252.0.166(54563) ->  172.19.26.33(4902)
Mar 17 00:03:28   %ASA-5-106100: access-list   permitted tcp  10.252.0.222(38071) ->  172.19.26.33(4902)
Mar 17 00:03:41   %ASA-5-106100: access-list   permitted tcp  10.252.0.222(38074) ->  172.19.26.33(4902)
Mar 17 00:03:45   %ASA-5-106100: access-list   permitted tcp  10.252.0.221(17868) ->  172.19.26.33(4902)
Mar 17 00:03:58   %ASA-5-106100: access-list   permitted tcp  10.252.0.166(54572) ->  172.19.26.33(4902)
Mar 17 00:03:58   %ASA-5-106100: access-list   permitted tcp  10.252.0.166(54573) ->  172.19.26.33(4902)
Mar 17 00:03:58   %ASA-5-106100: access-list   permitted tcp  10.252.0.166(54574) ->  172.19.26.33(4902)
Mar 17 00:04:14   %ASA-5-106100: access-list   permitted tcp  10.252.0.165(50826) ->  172.19.26.33(4902)
Mar 17 00:04:16   %ASA-5-106100: access-list   permitted tcp  10.252.0.166(54580) ->  172.19.26.33(4902)
Mar 17 00:04:28   %ASA-5-106100: access-list   permitted tcp  10.252.0.222(38088) ->  172.19.26.33(4902)
Mar 17 00:04:45   %ASA-5-106100: access-list   permitted tcp  10.252.0.221(17881) ->  172.19.26.33(4902)

I want to keep (4902) intact but want to take out first bracket with their numbers as well.
Is this correct to use?
awk '{sub('()'..... dst'()'," dst")}1'

A: You could use sed:
sed 's/([0-9]*)//' logfile

A: To take out first bracket with their numbers as well in awk:
$ awk '{sub(/\([^)]*\)/,"")}1' foo
Mar 17 00:03:13   %ASA-5-106100: access-list   permitted tcp  10.252.0.165 ->  172.19.26.33(4902)
Mar 17 00:03:16   %ASA-5-106100: access-list   permitted tcp  10.252.0.166 ->  172.19.26.33(4902)

A: @Bhavik: try:
awk '{sub(/\([0-9]+\)/,"");print}'   Input_file

It removes the very first occurrence of (all digits and then ). Thenn it prints the line from Input_file.


text:
Q: How to send a PUT/DELETE request in jQuery? GET:$.get(..)
POST:$.post()..
What about PUT/DELETE?

A: Here's an updated ajax call for when you are using JSON with jQuery > 1.9:
$.ajax({
    url: '/v1/object/3.json',
    method: 'DELETE',
    contentType: 'application/json',
    success: function(result) {
        // handle success
    },
    error: function(request,msg,error) {
        // handle failure
    }
});

A: We can extend jQuery to make shortcuts for PUT and DELETE:
jQuery.each( [ "put", "delete" ], function( i, method ) {
  jQuery[ method ] = function( url, data, callback, type ) {
    if ( jQuery.isFunction( data ) ) {
      type = type || callback;
      callback = data;
      data = undefined;
    }

    return jQuery.ajax({
      url: url,
      type: method,
      dataType: type,
      data: data,
      success: callback
    });
  };
});

and now you can use:
$.put('http://stackoverflow.com/posts/22786755/edit', {text:'new text'}, function(result){
   console.log(result);
})

copy from here

A: You should be able to use jQuery.ajax :

Load a remote page using an HTTP
  request.

And you can specify which method should be used, with the type option :

The type of request to make ("POST" or
  "GET"), default is "GET". Note: Other
  HTTP request methods, such as PUT and
  DELETE, can also be used here, but
  they are not supported by all
  browsers.

A: ajax()
look for param type
Other HTTP request methods, such as PUT and DELETE, can also be used here, but they are not supported by all browsers.

A: Seems to be possible with JQuery's ajax function by specifying
type: "put" or
type: "delete"
and is not not supported by all browsers, but most of them.
Check out this question for more info on compatibility:
Are the PUT, DELETE, HEAD, etc methods available in most web browsers?

A: For brevity:
$.delete = function(url, data, callback, type){

  if ( $.isFunction(data) ){
    type = type || callback,
    callback = data,
    data = {}
  }

  return $.ajax({
    url: url,
    type: 'DELETE',
    success: callback,
    data: data,
    contentType: type
  });
}

A: You can do it with AJAX !
For PUT method :
$.ajax({
  url: 'path.php',
  type: 'PUT',
  success: function(data) {
    //play with data
  }
});

For DELETE method :
$.ajax({
  url: 'path.php',
  type: 'DELETE',
  success: function(data) {
    //play with data
  }
});

A: If you need to make a $.post work to a Laravel Route::delete or Route::put just add an argument "_method"="delete" or "_method"="put".
$.post("your/uri/here", {"arg1":"value1",...,"_method":"delete"}, function(data){}); ...

Must works for others Frameworks

Note: Tested with Laravel 5.6 and jQuery 3

A: $.ajax will work.
$.ajax({
   url: 'script.php',
   type: 'PUT',
   success: function(response) {
     //...
   }
});

A: From here, you can do this:
/* Extend jQuery with functions for PUT and DELETE requests. */

function _ajax_request(url, data, callback, type, method) {
    if (jQuery.isFunction(data)) {
        callback = data;
        data = {};
    }
    return jQuery.ajax({
        type: method,
        url: url,
        data: data,
        success: callback,
        dataType: type
        });
}

jQuery.extend({
    put: function(url, data, callback, type) {
        return _ajax_request(url, data, callback, type, 'PUT');
    },
    delete_: function(url, data, callback, type) {
        return _ajax_request(url, data, callback, type, 'DELETE');
    }
});

It's basically just a copy of $.post() with the method parameter adapted.

A: You could use the ajax method:
$.ajax({
    url: '/script.cgi',
    type: 'DELETE',
    success: function(result) {
        // Do something with the result
    }
});

A: I've written a jQuery plugin that incorporates the solutions discussed here with cross-browser support:
https://github.com/adjohnson916/jquery-methodOverride
Check it out!

A: CRUD
this may make more sense
CREATE (POST)Request
function creat() {
  $.ajax({
    type: "POST",
    url: URL,
    contentType: "application/json",
    data: JSON.stringify(DATA1),
    success: function () {
      var msg = "create successful";
      console.log(msg);
      htmlOutput(msg);
    },
  });
}

READ (GET)Request
// GET EACH ELEMENT (UNORDERED)
function read_all() {
  $.ajax({
    type: "GET",
    url: URL,
    success: function (res) {
      console.log("success!");
      console.log(res);
      htmlOutput(res);
    },
  });
}

// GET EACH ELEMENT BY JSON
function read_one() {
  $.ajax({
    type: "GET",
    url: URL,
    success: function (res) {
      $.each(res, function (index, element) {
        console.log("success");
        htmlOutput(element.name);
      });
    },
  });
}

UPDATE (PUT)Request
function updat() {
  $.ajax({
    type: "PUT",
    url: updateURL,
    contentType: "application/json",
    data: JSON.stringify(DATA2),
    success: function () {
      var msg = "update successful";
      console.log(msg);
      htmlOutput(msg);
    },
  });
}

DELETE (DELETE)Request
function delet() {
  $.ajax({
    type: "DELETE",
    url: deleteURL,
    success: function () {
      var msg = "delete successful";
      console.log(msg);
      htmlOutput(msg);
    },
  });
}

GitHub Reference

A: You could include in your data hash a key called: _method with value 'delete'.
For example:
data = { id: 1, _method: 'delete' };
url = '/products'
request = $.post(url, data);
request.done(function(res){
  alert('Yupi Yei. Your product has been deleted')
});

This will also apply for


text:
Q: Get the URL of a server I am using flask and flask email for sending an email. When I work on I used the localhost as a base url. I deployed it on the server and email sent is still showing with localhost address.
For example
base_url = "http://localhost:0.0.0.6465"
url=base_url+'/login'

I sent an email(i am using flask-mail) with the url and I can login with the url.
With the same script when I deployed on the server I am getting with same localhost address.I need the server URL should be the base url.
To debug this I tried
url=request.base_url+'/login'

I am getting 404 error in the browser if I use this. I dont want to change the initializtion of base_url because I have to use both in the local as well as in the server.
How can I do that?

A: You can get the URL to the currently running app through request.host_url. But what you really want to to do to get an external URL to a specific part of your application, is to use url_for as you'd do when referencing your regular endpoints, but with the parameter _external=True:
Given that you have:
@app.route('/login')
def login():
    ....

You can generate an external URL by using:
from flask import (
    url_for,
)

...

url = url_for('login', _external=True)

This will also take into account any proxies in front of your application if you need that, as long as you've used the ProxyFix middleware when setting up your app object.
Since this uses the same mechanism as Flask uses when generating URLs between different pages, it should behave just as you want - i.e. it'll work both on localhost and on the remote host.


text:
Q: Possible injection from date string Select query I have a problem wich is a little strange. My page contains a html link which refreshes the page and calls a PHP variable. This variable appends a date string to the url string which is fed into a MySQL query, which grabs records matching this date. I think this is causing an injection as it sometimes deletes the user from the database!
I know there may be security issues using the '#' in the hyperlink, but I'd like to know whats going on. Also would this have different effects on different browsers seeing as how it uses javascript. The users being deleted seems to happen only on some peoples computers.
The PHP code calculates a timestamp three days from now and then puts it into a SQL format:
$ts_threeDays   = mktime(1,0,0,date('m'), date('d')+3-date('w'), date('y'));
$threeDaysAhead = date('y-m-d', $ts_second_day);

The script then listens for the 'day' variable in the url string passed by the hyperlink on the page:
$date = mysql_real_escape_string($_GET['day']);

The JavaScript and hyperlink is:
<a href='#' onClick="document.location.href='planner.php?day=<?php echo $threeDaysAhead; ?>'"> 3 Days Later

The MySQL query is bigger but the only input it takes from user action is the above date string. Query basically looks like this (uses another select statement to access users table):
SELECT planner.details FROM planner
WHERE  planner.date = '$date' AND users.`user_id` = '$id' // Logged in Id superglobal

If anyone can help me out and explain my problem I will be most grateful.
Many thanks

A: As you're passing $date through mysql_real_escape_string, suspicion has to fall on either $id, or something we can't see.
A SELECT statement isn't going to delete stuff from your db.  What else do you have in your PHP file that's responsible for deleting users, and could you have some broken if/else logic that ends up passing through a function to delete users when they really shouldn't be?

A: Previous responses explain very well your problem.
And you can validate your 'day' get var like this way:
$day = '';
if (preg_match('/^\d{4}-\d{2}-\d{2}$/', $_GET['day'])
{
    $day = $_GET['day'];
} else {
    die("bye bye");
}


text:
Q: Merge rows in the same DataTable I'm trying to merge two rows into one row. They're both in the same database and table.
Example:
        column1    column2    column3    column4    column5    column6
row1    value      value      value      null       null       null
row2    null       null       null       value      value      value

I tried using table.Merge(table) but that didn't seem to do anything. How can I merge these two rows so that it's just
        column1    column2    column3    column4    column5    column6
row1    value      value      value      value      value      value

A: Assuming you have two DataRows dr1 and dr2 from same DataTable, it is straight-forward using Linq :
var merged = dr1.ItemArray.Zip(dr2.ItemArray, (e1, e2) =>e1 ?? e2).ToArray();
dr1.ItemArray = merged;

A: There is no built in function to do this for you.  As such you have to do this manually.  First determine the rows to be merged, and run over the columns to merge them.
DataRow target = table.Rows[0];
DataRow source = table.Rows[1];

for (int i = 0; i < table.Columns.Count; i++)
{
    target[i] = target[i] ?? source[i];
}

table.Remove(source);

The sample above iterates over all the columns of the two rows and assigns values from source where target is null.  After the merge it removes the source row.


text:
Q: HTML Form not submitting if there is a ' character within the data So basically I have a working HTML Form that when filled out and submitted goes tomy SQL database, I have check multiple times and it works as should unless there is a ' character in the data being submitted. If there is a ' it simply won't submit the form. I don't know why this is and was hoping someone would know and potentionally help my resolve the problem so that that character can be used. I am using PHP to connect my HTMLform to my SQL server.
All the columns in my SQL Table are VARCHAR(no.)
EDIT:
This is the code on my php file.
<?php
// database connection code
// $con = mysqli_connect('localhost', 'database_user', 'database_password','database');

$con = mysqli_connect('localhost', 'root', '7520NHOj','db_connect');

// get the post records
$txtName = $_POST['txtName'];
$txtEmail = $_POST['txtEmail'];
$txtPhone = $_POST['txtPhone'];
$txtMessage = $_POST['txtMessage'];

// database insert SQL code
$sql = "INSERT INTO `tbl_contact` (`fldName`, `fldEmail`, `fldPhone`, `fldMessage`) VALUES ('$txtName', '$txtEmail', '$txtPhone', '$txtMessage')";

// insert in database
$rs = mysqli_query($con, $sql);

if($rs)
{
    echo "Your Contact form has been submitted, we will get back to you as soon as possible!";
}

?>

A: Use mysqli_real_escape_string function for solving problem.
Use the following code.
<?php
// database connection code
// $con = mysqli_connect('localhost', 'database_user', 'database_password','database');

$con = mysqli_connect('localhost', 'root', '7520NHOj','db_connect');

// get the post records
$txtName = mysqli_real_escape_string($con,$_POST['txtName']);
$txtEmail = mysqli_real_escape_string($con,$_POST['txtEmail']);
$txtPhone = mysqli_real_escape_string($con,$_POST['txtPhone']);
$txtMessage = mysqli_real_escape_string($con,$_POST['txtMessage']);

// database insert SQL code
$sql = "INSERT INTO `tbl_contact` (`fldName`, `fldEmail`, `fldPhone`, `fldMessage`) VALUES ('$txtName', '$txtEmail', '$txtPhone', '$txtMessage')";

// insert in database
$rs = mysqli_query($con, $sql);

if($rs)
{
    echo "Your Contact form has been submitted, we will get back to you as soon as possible!";
}

?>


text:
Q: How to find word frequency per country list in pandas? Let's say I have a .CSV which has three columns: tidytext, location, vader_senti
I was already able to get the amount of *positive, neutral and negative text instead of word* pero country using the following code:
data_vis = pd.read_csv(r"csviamcrpreprocessed.csv", usecols=fields)

def print_sentiment_scores(text):
    vadersenti = analyser.polarity_scores(str(text))
    return pd.Series([vadersenti['pos'], vadersenti['neg'], vadersenti['neu'], vadersenti['compound']])

data_vis[['vadersenti_pos', 'vadersenti_neg', 'vadersenti_neu', 'vadersenti_compound']]  = data_vis['tidytext'].apply(print_sentiment_scores)

data_vis['vader_senti'] = 'neutral'
data_vis.loc[data_vis['vadersenti_compound'] > 0.3 , 'vader_senti'] = 'positive'
data_vis.loc[data_vis['vadersenti_compound'] < 0.23 , 'vader_senti'] = 'negative'

data_vis['vader_possentiment'] = 0
data_vis.loc[data_vis['vadersenti_compound'] > 0.3 , 'vader_possentiment'] = 1

data_vis['vader_negsentiment'] = 0
data_vis.loc[data_vis['vadersenti_compound'] <0.23 , 'vader_negsentiment'] = 1

data_vis['vader_neusentiment'] = 0
data_vis.loc[(data_vis['vadersenti_compound'] <=0.3) & (data_vis['vadersenti_compound'] >=0.23) , 'vader_neusentiment'] = 1

sentimentbylocation = data_vis.groupby(["Location"])['vader_senti'].value_counts()
sentimentbylocation

sentimentbylocation gives me the following results:
Location                      vader_senti
Afghanistan                   negative          151
                              positive           25
                              neutral             2
Albania                       negative            6
                              positive            1
Algeria                       negative          116
                              positive           13
                              neutral             4

TO GET THE MOST COMMON POSITIVE WORDS, I USED THIS CODE:
def process_text(text):
    tokens = []
    for line in text:
        toks = tokenizer.tokenize(line)
        toks = [t.lower() for t in toks if t.lower() not in stopwords_list]
        tokens.extend(toks)

    return tokens

tokenizer=TweetTokenizer()
punct = list(string.punctuation)
stopwords_list = stopwords.words('english') + punct + ['rt','via','...','…',''','—','—:',"'","â"]
pos_lines = list(data_vis[data_vis.vader_senti == 'positive'].tidytext)

pos_tokens = process_text(pos_lines)
pos_freq = nltk.FreqDist(pos_tokens)

pos_freq.most_common()

Running this will give me the most common words and the number of times they appeared, such as
[(good, 1212),
(amazing, 123)

However, what I want to see is how many of these positive words appeared in a country.
For example:

I have a sample CSV here: https://drive.google.com/file/d/112k-6VLB3UyljFFUbeo7KhulcrMedR-l/view?usp=sharing

A: Create a column for each most_common word, then do a groupby location and use agg to apply a sum for each count:
words = [i[0] for i in pos_freq.most_common()]

# lowering all cases in tidytext
data_vis.tidytext = data_vis.tidytext.str.lower()

for i in words:
    data_vis[i] = data_vis.tidytext.str.count(i)

funs = {i: 'sum' for i in words}
grouped = data_vis.groupby('Location').agg(funs)

Based on the example from the CSV and using most_common as ['good', 'amazing'] the result would be:
grouped

#               good amazing
# Location
# Australia     0    1
# Belgium       6    4
# Japan         2    1
# Thailand      2    0
# United States 1    0


text:
Q: activity finishes itself but onDestroy() call for this activity happen so late I found a bug in our code that we are launching the activity(let's call this as SCREEN_ACTIVITY) by
Intent intent = new Intent(SharedIntents.INTENT_SCREEN);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);

Android documentation : When using FLAG_ACTIVITY_NEW_TASK, if a task is already running for the activity you are now starting, then a new activity will not be started; instead, the current task will simply be brought to the front of the screen with the state it was last in.
So everything works fine in most of the case.
That screen activity will call finish() when user click something. Also this screen activity will get launch or create by incoming event from the service.
6053 I/ScreenActivity(15395): onCreate
6682 E/ScreenActivity(15395): finish() Activity
6832 I/ScreenActivity(15395): onDestroy

7284 I/ScreenActivity(15395): onCreate
7911 E/ScreenActivity(15395): finish() Activity
8063 I/ScreenActivity(15395): onDestroy

10555 I/ScreenActivity(15395): onCreate
13413 E/ScreenActivity(15395): finish() Activity
13701 I/ScreenActivity(15395): onCreate
13799 I/ScreenActivity(15395): onDestroy

The last one is the issue. ScreenActivity is created and then call finish() itself. But the problem is that onDestroy is being called very late. Before that there is incoming event from the server and calling startActivity() trigger a new ScreenAcitivty onCreate(). The problem is that ScreenManager class keeps flags for that activity created and destroyed.
The flag is set when onCreate() callback and onDestroy() callback.
So for line 10555 and 13701 the ScreenManager set createFlag = true. for line 13799 set createFlag = false.
The event comes after line 13799 will assume that the activity is not created and events are not notified to the activity.
Hope my description for the issue is clear to you.
Is this kind of scenario onStop() and onDestroy() call so late after calling finish() is expected to happen? If yes, i have to think about the solution.
If not, then is there any places to modify?
Thanks a lot.

A: onDestroy() may or may not be called. You cannot rely on it being called all the time. From the docs:

Note: do not count on this method being called as a place for saving
  data! For example, if an activity is editing data in a content
  provider, those edits should be committed in either onPause() or
  onSaveInstanceState(Bundle), not here. This method is usually
  implemented to free resources like threads that are associated with an
  activity, so that a destroyed activity does not leave such things
  around while the rest of its application is still running. There are
  situations where the system will simply kill the activity's hosting
  process without calling this method (or any others) in it, so it
  should not be used to do things that are intended to remain around
  after the process goes away.

If you need to know that your Activity is finishing, a reliable way to know if it is finishing is the isFinishing() method. You can call it in onPause() to find out if this pause will eventually lead to this Activity being destroyed:
@Override
protected void onPause() {
    super.onPause();
    if (isFinishing()) {
        // Here  you can be sure the Activity will be destroyed eventually
    }
}

A: use Handler,
 new Handler().postDelayed(new Runnable() {
            @Override
            public void run()
              //enter code here for open an Activity
            }
        },300);

after that, we are getting log should be:
onCreate
onStop
onDestroy
onCreate


text:
Q: How to create polygon that goes over +/-180 (dateline) in ArcMap? I want to create a polygon feature that will go through the dateline (180 long.) in ArcMap. I am using WGS_1984_Web_Mercator_Auxiliary_Sphere (WKID: 3857) for my data frame and my polygonal feature class is defined with the same projected coordinate system. My feature classes are stored within enterprise geodatabase 10.2.1 (SQL Server Geometry spatial type). However, the same behaviour can be reproduced with the file geodatabase feature class.
From Esri help:

Data in a geographic coordinate system is treated, in a sense, as
two-dimensional, at least to the point that there are edges, just as
in a projected coordinate system. Generally, the edges are at
-180/+180 for the east–west extents, and -/+90 for the north–south extents. These extents are called the "horizon" of the coordinate
system.
In a geodatabase, a feature that crosses an edge will be clipped to
the horizon. If you are editing features in ArcMap, the data frame's
coordinate system will affect what happens to a feature that crosses
the +/-180° line. If the data frame is using a geographic coordinate
system, that is, the +180 and -180 lines are separated, a feature that
crosses outside the horizon will be clipped to the horizon. If the
data frame is using a projected coordinate system, with the +/-180°
line inside, a feature that crosses it will be split into multiple
parts.

I am able to create a polyline feature that crosses the 180° line. A multipart feature is created just as outlined in the Help. When I run the Multipart To Singlepart GP tool, I can verify that my line was originally multipart and is represented in the output feature class as two singlepart features.
However, this doesn't happen when I am trying to create a polygon feature crossing the 180° line. I am getting the error message:

Create
The Create Feature task could not be completed. The coordinates or measures are out of bounds.

Why don't polygons get splitted just lines did? Is there any workaround that would help me to achieve my goal?

A: I have figured out that in order to split polygons at the 180 line, the data frame coordinate system should be a geographic one (for instance, WGS84). The feature classes themselves can be defined with a projected coordinate system, but the data frame should be in geogprahic coordinate system.
So, it seems as the information in the Help is incorrect because if a data frame is defined in the projected coordinate system, the polygon doesn't get splitted.


text:
Q: Remove duplicates in SQL Server Group By I have 2 tables, Product and Type, the tables looks something like this:
Product
-Id
-Name
-TypeId

Type
-Id
-Name

I want to be able to write a SQL Server query which outputs the products grouped by Type:
+------------+------------+
| Bikes      | Product 1  |
|            | Product 2  |
|            | Product 3  |
| Clothes    | Tshirt 1   |
|            | Trousers 2 |
|            | Hat 3      |
|            | Shoes 4    |
| Electrical | Tv         |
|            | Radio      |
|            | Laptop     |
+------------+------------+

If i write:
SELECT Type.Name,Product.Name
FROM Product INNER JOIN Type ON Type.Id = Product.TypeId
ORDER By Type.Name

I get similar results however the type value is included in every column.
+------------+------------+
| Bikes      | Product 1  |
| Bikes      | Product 2  |
| Bikes      | Product 3  |
| Clothes    | Tshirt 1   |
| Clothes    | Trousers 2 |
| Clothes    | Hat 3      |
| Clothes    | Shoes 4    |
| Electrical | Tv         |
| Electrical | Radio      |
| Electrical | Laptop     |
+------------+------------+

Using SQL Server is there any way i can only show the first type value?

A: Windowing functions can help here.
SELECT CASE WHEN RowNum = 1 THEN TypeName ELSE NULL END AS TypeName, ProductName
FROM (
SELECT Type.Name AS TypeName,Product.Name AS ProductName, ROW_NUMBER() OVER(PARTITION BY Type.Name ORDER BY Product.Name) AS Rownum, COUNT([whatever you want to count]) AS ItemCount
FROM Product INNER JOIN Type ON Type.Id = Product.TypeId
GROUP BY Type.Name, Product.Name
) X

The MSDN reference for the OVER clause is here, by the way:
https://msdn.microsoft.com/en-us/library/ms189461.aspx

A: SELECT CASE WHEN rn = 1 THEN TypeName ELSE NULL END AS TypeName
     , ProductName, rn
FROM ( SELECT Type.Name AS [TypeName], Product.Name AS [ProductName]
            , ROW_NUMBER() OVER(PARTITION BY Type.Name ORDER BY Product.Name) AS rn
         FROM Product
         JOIN Type
               ON Type.Id = Product.TypeId
     ) tt
order by ProductName, rn

ROW_NUMBER (Transact-SQL)

A: Use this ones :
  Create Table [Type]
  (
    Id Int ,Name varchar(10)
  )
  Create Table [Product]
  (
    Id Int ,
    Name varchar(10),
    TypeID Int,
  )

  INSERT INTO [Type](ID,Name)
    VALUES
      (1,'Bikes'),
      (2,'Clothes'),
      (3,'Electrical')

  INSERT INTO [Product](ID,Name,TypeID)
    VALUES
      (1,'Product 1',1),
      (2,'Product 2',1),
      (3,'Product 3',1),
      (4,'Tshirt 1',2),
      (5,'Trousers 2',2),
      (6,'Hat 3',2),
      (7,'Shoes 4',2),
      (8,'Tv',3),
      (9,'Radio',3),
      (10,'Laptop',3)

  SELECT
    CASE ProductWithRank.[Rank]
      WHEN 1
        THEN [Type].Name
      ELSE NULL
    END AS TypeName
    , ProductWithRank.Name,
    ProductWithRank.[Rank]
  FROM ( SELECT
            Product.TypeId,
            Product.Name ,
            Product.ID
            , Rank() OVER(PARTITION BY Product.TypeId ORDER BY Product.ID) AS [Rank]
         FROM Product
       ) ProductWithRank
  INNER JOIN [Type] ON [Type].Id = ProductWithRank.TypeId
  ORDER BY ProductWithRank.ID, [Rank]


text:
Q: should I use an object to handle user search criteria? I have a search form that allows users to search real estate listings.
I currently have it set up as a basic html form that posts to a search results page.
On the search results page, I then use raw SQL and query the database and then use a repeater to display the results. I also create session variables on the query so if the user does another search they dont have to fill out the whole search, just edit it.
I was wondering if I should rather create a search class with a search object that gets created and edited with each search. Is this the best practice? or is my method above sufficient?
Thanks!

A: If there are lots of search parameters then I'd create a class to encapsulate them all and store that in session state, rather than maintaining lots of separate session variables. You might need to decorate this class with the SerializableAttribute depending on how you've got your session state configured, e.g.
[Serializable]
public class SearchOptions
{
    public string Foo { get; set; }
    public string Bar { get; set; }
}


text:
Q: Create covariance matrix using ratio and rotation degree I am a beginner in Linear Algerbra. I want to create a covariance matrix using given ratio and degree of rotation
For example:
If the ratio is 2 and degree of rotation is 45 the covariance matrix should be:
[[2.5, 1.5], [1.5, 2.5]]

I tried this:
R = np.mat([[np.cos(0.785398), -np.sin(0.785398)], [np.sin(0.785398), np.cos(0.785398)]])
S = np.mat([[2, 0], [0, 2]])
np.cov(S@R.T)

I could not get the desired result.

A: If you want to rotate and scale the data as Burrito said, then this blog will help. It explains everything you want to do along with the code.
covariance-matrix

A: Came across this question when looking for the answer to it myself. Thought I'd come back and post what I found.
It's essentially an eigenvalue problem, so the covariance matrix can be represented by:

Where Q represents the eigenvectors and L is the diagonalised eigenvalues. Because we want to generate the covariance from the rotation and scale, this information must come from there.
To scale a vector/matrix we can use the identity matrix multiplied by a constant, but here we want to use a ratio, so I'm assuming you want the first dimension to be scaled differently to the last one, so we end up with something like:
S = np.diag([ratio, 1])

One thing to note here is that S is actually the square root of L:
L = S**2

Coming back to our eigenvectors, we know in linear algebra we use the eigenvectors as a transformation to get the original matrix in a diagonal form, then the inverse of that transformation to return back to the original space. The rotation matrix makes a good eigenvector matrix, with the added benefit that the inverse is just the transpose.
So, putting that all together we end up with:
rotation = 45
ratio = 2

theta = np.radians(rotation)
c, s = np.cos(theta), np.sin(theta)
R = np.array([[c, -s], [s, c]])

S = np.diag([ratio, 1])
L = S**2

R@L@R.T

Hope that helps


text:
Q: How to automatically route to a child route in Angular I have an albums module that's loaded by the main app-router module. When clicking the albums link in the navigation, it directs to the albums module which loads an empty path and some child routes. The reason for this is the component assigned to the empty path has it's own navigation and router outlet. This component is the AlbumContainer.
The module has some child routes too. However, when I click on albums in the main navigation, I want it to automatically route to one of the children components / routes (dates). I know it's possible to just add the child route url to the main album navigation anchor, but then that prevents the main navigations routerLinkActive from functioning.
Is it possible that when I land on this module / component, that it automatically routes to the dates path?
In all other instances (in the albums sub menu), I'll be linking directly to the child route via the sub menu.
const routes: Routes = [
  {
    path: '',
    component: AlbumContainer,
    children: [
      {
        path: 'dates',
        loadChildren: () => import('./dates/dates.module').then((mod) => DatesModule)
      },
      {
        path: 'artists',
        loadChildren: () => import('./art/profile.module').then((mod) => mod.ArtistsModule)
      },
    ]
  },
];

HTML for reference

     <albums-menu></albums-menu>

    <router-outlet></router-outlet>

A: Redirect route to child routes
The angular router will try to match the route as a Tree, this means you can use redirectTo relative to the current position in the UrlTree by implementing it as a member of a set of child routes.
Setup
child route container
@Component({
  selector: 'app-outlet',
  template: `<router-outlet></router-outlet>`,
})
export class OutletComponent {}

app.component.html
<router-outlet></router-outlet>

child.component
Simple dummy component that just joins the URL of the current path and shows it in its template:
import { Component } from '@angular/core';
import { ActivatedRoute } from '@angular/router';

@Component({
  selector: 'app-child',
  template: `{{routeInfo}}`,
})
export class ChildComponent {
  routeInfo: string = '';
  constructor(private r: ActivatedRoute) {
    r.url.subscribe((url) => {
      this.routeInfo = url.join(" ");
    });
  }
}

Routes
const routes: Routes = [
  {
    path: '',
    component: OutletComponent,
    children: [{
      path: '',
      redirectTo: 'childB',
      pathMatch: 'full'
    },
    {
      path: 'childB',
      component: ChildComponent
    },
    {
      path: 'childA',
      component: ChildComponent
    }]
  }
];

Angular will begin matching from the root of the UrlTree. In this instance, if we're at the root, it will check the children.
The trick here, is that inside the child routes, we've also defined an empty route with a redirect, but because it is a child route, it will check if the route is empty, relative to its parent route, if pathMatch is set to full
So, in this example, we will automatically be redirected to /childB if we do not currently have any route selected.
Stackblitz: https://stackblitz.com/edit/angular-ivy-ygiwtn?file=src/app/app.module.ts


text:
Q: How to view PHP code that is Base64 encoded and GZInflated?
Possible Duplicate:
Is there a way to decode this PHP code?
What does this encoded string say, and how did you find out?

So my client bought a Wordpress template and requires changes in what comes with the template. I figured out in which file the modifications need to be done, however the code in that file looks as follows:
<?php eval(gzinflate(base64_decode('[a bunch of alphanumerical values here'))); ?>

As I understand, this code is rendered on the spot, its encoded and compressed. However, I need to do modifications in there, so how would I go about obtaining an editable file out of that code?
If you care to know how I know it's the file that I need to edit, the translation file points to that file at a specific line to affect the copy.

A: Simply replace eval() with echo (mind the brackets), or by file_put_contents('somefile.php', .... to save raw script to somefile.php file.


text:
Q: Which random variable sequences can naturally generate gamma distributions? Let $ {\textstyle \{X_{1},\ldots ,X_{n},\ldots \}}$ be a sequence random variables
For the summation of those random variable:
$ {\displaystyle {\bar {X}}_{n}\equiv {\frac {X_{1}+\cdots +X_{n}}{n}}}$
We know if each $X_i$ is a random variable for a independent simple binominal random walk, then ${\bar {X}}_{n}$ follow a normal distribution.
Question: What kind of simple sequences of random variables can naturally lead to a Gamma distribution (like binormal random walks do for normal distribution) ?

A: Let $(X_k)_{k\leq n}$ be IID s.t. $X_1 \sim \textrm{Exp}(\lambda)$. Then $\overline{X}_{n}\sim \textrm{Gamma}(n,\lambda n)$; with shape-rate parametrization. To see this:
$$\begin{aligned}E[e^{i\xi(X_1+....+X_n)/n}]&=(E[e^{i\xi X_1/n}])^n=\\
&=\bigg(\frac{\lambda}{\lambda-i\xi/n}\bigg)^n=\\
&=(1-i\xi/(\lambda n))^{-n}\end{aligned}$$
The last line is the characteristic function of the $\textrm{Gamma}(n,\lambda n)$ law. The assertion follows from $\{x\mapsto e^{i\xi x}:\xi \in \mathbb{R}\}$ being a determining class on $(\mathbb{R},\mathscr{B}(\mathbb{R}))$.

A: We can generalize the previous answer.
Let $X_i \sim \Gamma(k_i, \theta)$ be independent (notice that the shape parameter can be different while the scale one is assumed to be the same). Then
$$
X := \sum_{i=1}^{n}X_i \sim \Gamma\bigg(\sum_{i=1}^{n}k_i, \theta \bigg)
$$
Hence, multiplying by $1/n$ and remembering the scaling property of a gamma distribution, we have that $X \sim \Gamma\bigg(\sum_{i=1}^{n}k_i, \frac{\theta}{n} \bigg)$.
This means that the sum of independent gamma distribution generates a gamma distribution. So, as special cases, we have that the sum of exponential distribution and the sum of independent chi-square distribution are gamma distributed.


text:
Q: Schema selection in Apartment gem not working as expected In a demo application we want to handle tenants in different schemas (default apartment configuration for Postgres). These are to be selected from the subdomain of the application url.
I got it working, but then broke it again (it started using public instead of the selected schema).
I could narrow the problem down to this: If I use the following piece of code everything works as expected:
require 'apartment/elevators/first_subdomain'
Rails.application.config.middleware.use Apartment::Elevators::FirstSubdomain
Apartment::Elevators::FirstSubdomain.excluded_subdomains = ['demo', 'localhost']

If I do this myself (extending the missing Tenant behavior to return a 404), it doesn't work anymore:
class DemoUserSelectionMiddleware < Apartment::Elevators::Generic
  def parse_tenant_name(request)
    subdomain = request.host.split('.')[0]
    unless Rails.application.config.is_demo && subdomain.start_with?('demo_')
      'public'
    else
      subdomain
    end
  end

  def call(*args)
    begin
      super
    rescue Apartment::TenantNotFound
      Rails.logger.error "ERROR: Apartment Tenant not found: #{Apartment::Tenant.current.inspect}"
      return [404, {"Content-Type" => "application/json"}, ["Error" => "Tenant not found"]]
    end
  end
end

No error, no log entries, nothing. It just decides to use 'public'.
Using byebug I see that the subdomain is properly found.
Am I missing something obvious here?

A: In the first snippet, you added demo subdomain to excluded_subdomains. In other words, public tenant should be active with demo subdomain. In other subdomains, the corresponding tenants will be active.
In the piece of code you wrote, public tenant doesn't active with demo subdomain. On the contrary, public tenant is active in all subdomains.
.
.
unless Rails.application.config.is_demo && subdomain.start_with?('demo_')
.
.

Looks like there's a logical error here. I think you should use if instead of unless.


text:
Q: Does ImageMagick have a native format? I am creating images with the PHP Imagick extension in several steps.
I would like to cache intermediate results to disk.
Is there a format that I can use that preserves all channels and preferably also settings?
$i = new Imagick();
$i->setImagecolorspace();
$i->compositeImage(...);
$i->setImageBackgroundColor(...);

$i->setImageFormat(???);
$i->writeImage('cache.im');

$i2 = new Imagick();
$i2->readImage('cache.im');

Now $i2 should be the exact same image as $i.

A: As Paul says, it is MPC which is basically a memory dump of the file in two parts - one, the header including all metadata and two, the pixels - unencoded and uncompressed so that it can be read directly into memory without any CPU effort.
So, for example:
convert -size 4x4 xc:white a.mpc

yields
-rw-------  1 mark  staff  128 23 Sep 09:29 a.cache     <--- the pixel array
-rw-r--r--  1 mark  staff  357 23 Sep 09:35 a.mpc       <--- the header and metadata

where a.mpc contains
id=MagickCache
magick-signature=4026865107
class=DirectClass  colors=0  matte=False
columns=4  rows=4 depth=16
colorspace=sRGB
page=4x4+0+0
rendering-intent=Perceptual
gamma=0.454545
red-primary=0.64,0.33  green-primary=0.3,0.6  blue-primary=0.15,0.06
white-point=0.3127,0.329
date:create=2015-09-23T09:35:05+01:00
date:modify=2015-09-23T09:35:05+01:00

and a.cache contains
xxd -g4 a.cache
0000000: ffffffff ffff0000 ffffffff ffff0000  ................
0000010: ffffffff ffff0000 ffffffff ffff0000  ................
0000020: ffffffff ffff0000 ffffffff ffff0000  ................
0000030: ffffffff ffff0000 ffffffff ffff0000  ................
0000040: ffffffff ffff0000 ffffffff ffff0000  ................
0000050: ffffffff ffff0000 ffffffff ffff0000  ................
0000060: ffffffff ffff0000 ffffffff ffff0000  ................
0000070: ffffffff ffff0000 ffffffff ffff0000  ................

Another format that preserves all metadata is the MIFF format. You would use that like this:
convert -size 4x4 xc:white MIFF:a

which yields this:
-rw-r--r--   1 mark  staff     439 23 Sep 09:37 a

and looks like this:
more a
id=ImageMagick  version=1.0
class=DirectClass  colors=0  matte=False
columns=4  rows=4  depth=16
colorspace=sRGB
page=4x4+0+0
rendering-intent=Perceptual
gamma=0.454545
red-primary=0.64,0.33  green-primary=0.3,0.6  blue-primary=0.15,0.06
white-point=0.3127,0.329
date:create=2015-09-23T09:37:04+01:00
date:modify=2015-09-23T09:37:04+01:00
^L
:^Z<FF><FF><FF><FF><FF><FF><FF><FF><FF><FF><FF><FF><FF><FF><FF><FF><FF><FF><FF><FF><FF><FF><FF><FF><FF>
<FF><FF><FF><FF><FF><FF><FF><FF><FF><FF><FF><FF><FF><FF><FF><FF><FF><FF><FF><FF><FF><FF><FF><FF><FF><FF>
<FF><FF><FF><FF><FF><FF><FF><FF><FF><FF><FF><FF><FF><FF><FF><FF><FF><FF><FF><FF><FF><FF><FF><FF><FF><FF>
<FF><FF><FF><FF><FF><FF><FF><FF><FF><FF><FF><FF><FF><FF><FF><FF><FF><FF><FF>

A nice feature of the MIFF format is that it is "streaming" which means you can append/concatenate arbitrary numbers of images together in a single file.
One factor to be aware of... it is not advisable to use these formats for long-term storage as they are not guaranteed to be compatible across ImageMagick releases or platforms.


text:
Q: "stress" vs. "distress" From Cambridge dictionary,

*

*stress - great worry caused by a difficult situation.

*distress - extreme worry, sadness, pain.

I'm not sure if the words 'distress' and 'stress' have the same meaning but I have seen people use them interchangeably in some situations. I have also looked into Oxford Thesaurus dictionary there appears to be no relation between them. So, I'm just confused if both mean the same thing and can be used in place of another word?

A: Stress is often used to describe a mental state caused by excessive pressure of work. Distress is found in contexts in which people have been subject to traumatic experiences.

A: Stress is a state of imbalanced physiological or psychological conditions caused by stressors (internal or external). To maintain the balance or to reduce such conditions, physiological changes occur, collectively called the stress response. With the stress response, people can change or adapt to a stressful condition. But when the stressful condition is not adapted for a long time or if the stress is intense, it may bring distress.
Distress can be said as the inability to cope with stressful conditions, or a condition that is painful physically or mentally, that is observable in behavior. An acute or chronic stress condition can also be regarded as distress, because it also brings pain and a sense of not being able to control the stressor.

A: They can't be interchanged. Apart from the other answers, I'll mention that psychologists describe healthy stress (challenges) and ways to manage stress, but a 'distress call' given by the captain of a vessel is made because of an extreme situation.

A: When talking about life and people,  feeling stress is not necessarily a negative input. However,  if a person feels distressed, the word connotes an accompaniment of pain, a much heavier burden.
Stress MAY be caused by a challenging or difficult situation. The impetus to act on feeling stressed out may yield a positive outcome because of the pressure.
Distress, however, IS a state of extremes: worries, pain, sadness. There is no indication of a positive outcome forthcoming.


text:
Q: Update ActiveRecord object including association and get error message I'm trying to update a record which includes a has_many association and wish to process any errors. Using update_attributes works great if there are no associations but if an association is not valid (violates a unique constraint, for example) then all I get is a ActiveRecord::RecordNotSaved error, but nothing in the @object.errors.
Controller Code
respond_to do |format|
  begin
    if @calmapp_version.update_attributes(params[:calmapp_version])
      tflash('update', :success, {:model=>@@model, :count=>1})
      format.html { redirect_to( :action => "index")}
      format.xml  { head :ok }
    else
      format.html { render :action => "edit" }
    end
  rescue ActiveRecord::RecordNotSaved => e
     flash[:error] = @calmapp_version.errors.full_messages
     format.html { render :action => "edit" }
  end
end

Models
    class CalmappVersion < ActiveRecord::Base
      has_many :calmapp_versions_translation_languages, :dependent => :destroy
      ....
    end

    class CalmappVersionsTranslationLanguage < ActiveRecord::Base
      belongs_to :calmapp_version
      belongs_to :translation_language

      validates :translation_language_id, :uniqueness => {:scope=> :calmapp_version_id}
    end

Where is the violation of uniqueness message and how do I access it?

A: I would try using update_attributes!.  Notice the !.  This will produce an exception if a record isn't valid and give you more insight into what's going wrong.

A: In regards to the other question  Where is the violation of uniqueness message and how do I access it?
you can look here (http://guides.rubyonrails.org/active_record_validations.html#uniqueness)  and include the message in the uniqueness hash  such as
validates :translation_language_id, :uniqueness => {:scope=> :calmapp_version_id, message => 'There Can Be Only 1'}