text:
Q: Efficiently querying a region-partitioned PostGIS table I have two PostGIS tables: one of streets, and one of regions, which, apart from spanning the same spatial extent, are a priori unrelated. The streets queries I perform can be restricted to a given region, by supplying a known id. To exploit this, I added a region_id column to the streets table (using a st_intersects-based update query, which was quite expensive, but performed only once).
My question: once this is in place, will the use of an index on the streets.region_id column be enough to make queries of this type maximally efficient:
select * from streets where region_id = <id> and ...

Or is there an alternative mechanism that would perform better?

A: Indexing a column that is used in either joins or where clauses is the best (and simplest) way to make a query efficient, so the answer is yes.
Another trick you could pull is to CLUSTER the table against the index (remember to run VACUUM ANALYZE after that to update table statistics). CLUSTER makes a copy of the table (the table will not be usable during clustering) reordering the data so that identical values of the index are contiguously stored on disk (thus maximing disk read-ahead efficiency).
Make sure to read the documentation on the CLUSTER command to understand if you need it and how it works.
Please note though that Postgres will not use the index when the condition is IS NULL.


text:
Q: Is there a way to play multiple mp3 files at once in pygame? I'm trying to play 2 mp3 files, but every time the other one plays, the first one stops. Whenever I use channel, the game ends up crashing.
Here is my code:
pygame.mixer.music.load('music.mp3')
pygame.mixer.music.play(-1)
#insert generic if statement here
pygame.mixer.music.load("differentmusic.mp3')
pygame.mixer.music.play()

is there any way to allow 2 mp3 files to be playing at the same time, or do I have to convert them all to wav?

A: Just so there's a formal answer to this question...
It's not possible to play multiple MP3 sound files simultaneously using channels with PyGame.  They can be played singularly with the pygame.mixer.music set of functions.
However, it's absolutely possible to convert your sound-files to OGG sound format - which is compressed much the same as MP3, or the uncompressed WAV format.  Obviously this is not a solution if you want to write an MP3 music player, but for a game it's a minor a requirement.  Free software such as Audacity is easily able to convert sound formats.
I have adapted the example from the comment link to not use the var module.  Like the linked code it continuously plays a rain-sound , and pressing h adds a car horn meep-meep into the output.
import pygame

# Window size
WINDOW_WIDTH    = 400
WINDOW_HEIGHT   = 400
WINDOW_SURFACE  = pygame.HWSURFACE|pygame.DOUBLEBUF|pygame.RESIZABLE

DARK_BLUE = (   3,   5,  54)

### initialisation
pygame.init()
pygame.mixer.init()
window = pygame.display.set_mode( ( WINDOW_WIDTH, WINDOW_HEIGHT ), WINDOW_SURFACE )
pygame.display.set_caption("Multi Sound")

### sound
# create separate Channel objects for simultaneous playback
channel1 = pygame.mixer.Channel(0) # argument must be int
channel2 = pygame.mixer.Channel(1)

# Rain sound from: https://www.freesoundslibrary.com/sound-of-rain-falling-mp3/ (CC BY 4.0)
rain_sound = pygame.mixer.Sound( 'rain-falling.ogg' )
channel1.play( rain_sound, -1 )   # loop the rain sound forever

# Car Horn sound from: https://www.freesoundslibrary.com/car-horn-sound-effect/ (CC BY 4.0)
horn_sound = pygame.mixer.Sound( 'car-horn.ogg' )

### Main Loop
clock = pygame.time.Clock()
done = False
while not done:

    # Handle user-input
    for event in pygame.event.get():
        if ( event.type == pygame.QUIT ):
            done = True
        elif ( event.type == pygame.KEYUP ):
            if ( event.key == pygame.K_h ):
                if ( not channel2.get_busy() ):                          # play horn if not already playing
                    channel2.play( horn_sound )
                    print( 'meep-meep' )

    # Window just stays blue
    window.fill( DARK_BLUE )
    pygame.display.flip()

    # Clamp FPS
    clock.tick_busy_loop(60)

pygame.quit()

redpajama_set_name: RedPajamaStackExchange


text:
Q: Declare an array variable to the controller/component [Laravel, October CMS] I am using October CMS and have no idea how to add an array to the component which serves a similar purpose of the Laravel's controller. Basically it is for my site search functionality. The thing is, it always throws an Array to String conversion ERROR. If you look at the code, the problem lies at the last line $this->$results = $results; because $results is a multidimensional array.
/**
 * Component setup.
 *
 * @return void
 */
  public function onRun()
  {
      $this->search();
  }

  /**
  * Initiate the search
  *
  *@return void
  */
   public function search()
   {
     // Sets the parameters from the get request to the variables.
      $popularno = Request::get('q');

      // Perform the query using Query Builder
      $estates = DB::table('makler_realestate_objects')
          ->where('slug', 'like', "%${popularno}%")
          ->get();

      // Now build a results array
      $i = 0;
      foreach ($estates as $estate) {
         $i++;

         $results[$i] = [
             'title'     => $estate->prim_id,
             'text'      => $estate->sifra_id,
             'url'       => 'nepremicnina/' . $estate->slug,
         ];
       }

       print_r($results);
       $this->$results = $results; // This is the issue
  }

I want to declare it to the component so I can call it on the page with {% set results = Search.results %} and loop through each array item with a for loop.
{% for result in results %}
 <li>{{result.title}} {{result.text}}</li>
{% endfor %}

Thank you for your help.

A: You're trying to assign an array as a property name by using an extra $. Take it out and you should be fine.
$this->results = $results;


text:
Q: Unable to capture memory allocation failure When I try to allocate a large memory using the 'new' operator in C++, system calls are not working after this memory allocation operation. It seems like the problem is with the memory allocation. However, I am not able to capture the exception.
For better clarity, I have the following MWE.
My main.cpp contains the following lines:
#include <cstdio>
#include <iostream>
#include "memallocator.h"
#include <stdlib.h>

using namespace std;
const int MAX_ITER = 2000;

int main()
{
    printf("\n 1. output of ls: %d \n", system("ls"));

    for(int i=0;i<MAX_ITER;i++)
    {
        MemAllocator *pCMemAllocator;
        try
        {
            pCMemAllocator = new MemAllocator(); // alocates memory of size BUF_SIZE = 4000*1024;
        } catch(bad_alloc e)
        {
            printf("\nException at %d",i);
            break;
        }

    }
    printf("\nMemory Allocated");
    printf("\n 2. output of ls: %d \n", system("ls"));

    return 0;
}

The memallocator.h file is given as:
#ifndef MEMALLOCATOR_H
#define MEMALLOCATOR_H

const unsigned long BUF_SIZE = 4000*1024;

class MemAllocator
{
public:
    MemAllocator(){};
private:

    unsigned char ucBuffer [BUF_SIZE];

};

#endif // MEMALLOCATOR_H

I compiled it using g++ (version 4.8) on Ubuntu 14.04 64-bit and got the following output:
a.out  main.cpp  memallocator.h

 1. output of ls: 0

Memory Allocated
 2. output of ls: -1

That is, the system("ls") command fails after the memory allocation operation. However, the failure was not captured by the exception handler. I also tried the naive method: allocating zero first to the pointer and checking for zero after memory allocation operation. This method also did not capture the problem with the memory allocation.
If I set the variable MAX_ITER to some small value, say 20, everything works fine.
For higher values of MAX_ITER, the memory exception was supposedly handled by the exception handler. Why is it not happening?

A: The system(3) function is (on Linux and most Posix systems) using the fork(2) syscall, which can fail for several reasons

EAGAIN:
     fork() cannot allocate sufficient memory to copy the parent's
                page tables and allocate a task structure for the child.
ENOMEM: fork() failed to allocate the necessary kernel structures
because memory is tight.

So you won't be able to  fork if your current process uses a lot of memory (and e.g. if the system does not have enough swap space to hold a copy).
BTW system(3) man pages says explicitly that system can fail and return....

   *  If a child process could not be created, or its status could not
      be retrieved, the return value is -1.

Consider using strace(1)  - proably as strace -f to understand the syscalls done by your application.
Notice that system(3) is not a syscall (which are listed in syscalls(2)...) but a standard library function.
So your huge memory allocation works as you want, but the later call to system is failing (and you should test it against failure). There is no memory allocation failure in your case.


text:
Q: Predicate required in Core Data fetch request? I would like to omitt the predicate in an NSFetchRequest in order to delete all managed objects for an entity.
However, when there is no predicate (according to the SQL debugger), the fetch request is not executed. According to Apple the predicate should be optional.
How would I need to change my code to remove the predicate? Any ideas? Thank you!
- (void)deleteEntity:(NSString*)entityName inContext:(NSManagedObjectContext *)context
    {
        NSFetchRequest * request= [[NSFetchRequest alloc] init];
        [request setEntity:[NSEntityDescription entityForName:@"TableStructure" inManagedObjectContext:context]];
        //[entities setIncludesPropertyValues:NO]; //only fetch the managedObjectID
        NSPredicate * predicate = [NSPredicate predicateWithFormat:@"category = 'est'"];
        [request setPredicate:predicate];

    NSError *error = nil;
    NSArray *entitiesArray = [context executeFetchRequest:request error:&error];

    if (error) {
        NSLog(@"%@: Error fetching context: %@", [self class], [error localizedDescription]);
        NSLog(@"entitiesArray: %@",entitiesArray);
        return;
    }

    for(NSManagedObject *entity in entitiesArray) {
        [context deleteObject:entity];
    }

    NSError *saveError = nil;
    [context save:&saveError];
}

Update 2
It seems that I call my fetch request before the database is ready. How can I make sure that my request is not called before the core data database is ready?

A: You simply don't assign the predicate if you don't want it. Remove following lines:
NSPredicate * predicate = [NSPredicate predicateWithFormat:@"category = 'est'"];
[request setPredicate:predicate];

A: I issued my fetch request before the Core Data database was ready.
To solve this issue, I have now added the call ImportFormulasInRequest to the UIDocument openWithCompletion handler, which encapsulates my core data database:
- (void)useDocument
{
    if (![[NSFileManager defaultManager] fileExistsAtPath:[self.myDatabase.fileURL path]]) {
        // does not exist on disk, so create it
        [self.myDatabase saveToURL:self.myDatabase.fileURL forSaveOperation:UIDocumentSaveForCreating completionHandler:^(BOOL success) {
            [self setupFetchedResultsController];
        }];
    } else if (self.myDatabase.documentState == UIDocumentStateClosed) {
        // exists on disk, but we need to open it
        [self.myDatabase openWithCompletionHandler:^(BOOL success) {
            [self setupFetchedResultsController];
            [self ImportFormulasInContext:[self.myDatabase managedObjectContext]];
        }];
    } else if (self.myDatabase.documentState == UIDocumentStateNormal) {
        // already open and ready to use
        [self setupFetchedResultsController];
        [self ImportFormulasInContext:[self.myDatabase managedObjectContext]];
    }
}


text:
Q: rename controllers asp.net mvc I have a bigger project with about 9 controllers. Now at the end of the project the url requeirement change. How to deal best with this situation - renaming the controllers seems just too cumbersome ... I need to change all links in servercode and javascript

A: Your problem can be solved by changing your existing routes. In your global.asax you'll find a code fragment like this
routes.MapRoute(
            "Default", // Route name
            "{controller}/{action}/{id}", // URL with parameters
            new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
        );

That maps an URL '/Controller/Action/Id' to Controller, Action and Id. You can provide routes like this
    routes.MapRoute(
            "RefactoredRoute", // Route name
            "SomeChangedURLBase/{action}/{id}", // URL with parameters
            new { controller = "Controller", action = "Index", id = UrlParameter.Optional } // Parameter defaults
        );

to route requests to /SomeChangedURLBase... to be handled by Controller.
Be aware that these routes should be registered before the default route to avoid that links generated in views point to the default route and generate the old URL.

A: you could change the routings in global.asax
just change the method RegisterRoutes
here you can find some more informations.
http://www.asp.net/mvc/tutorials/older-versions/controllers-and-routing/asp-net-mvc-routing-overview-cs
http://weblogs.asp.net/scottgu/archive/2007/12/03/asp-net-mvc-framework-part-2-url-routing.aspx
cheers


text:
Q: House address is not listed on Google Maps When I search for my address on Google Maps it cannot be found which means I can't order takeaway etc.
Is there a way of adding my address to Google Maps or even add a street address?
I want the address to be publicly available so others can search it.

A: Someone in a similar situation to you posted here:
https://productforums.google.com/d/msg/maps/WJeY25YbFSo/n8hA_LZMEokJ

*

*Go to Google.com

*click on "About Google" at the bottom

*click on "Contact us" at the bottom

*At the first drop down box where it says Or, jump straight to specific product contact options - SELECT "Maps contact options"

*Click on "Fix an error on Google Maps"

*You can choose the option that best pertains to your situation, but if it's street name error click "Report incorrect map data"

*(Tela Atlas provides Google Maps with their data) It says:  •Tele Atlas: Report a map error using their Map Insight system. Click on
  "Map insight" link.

*Click "English"

*Click "Start"

*click your country "United States" from the drop down box.

*click your "state/province" from the drop down box.

*Type in the address that needs corrected.  Click "search"

*Click the green push pin marker to move it to the street you are describing.

*Click "Step 2 - Describe"

*Click "Address" icon

*click "change and address, street name, house number or city"

*Type the correct address

*Click "additional remarks" to explain any information to help them understand the correction.

*click "Step 3 - Submit"   - You will get an ID number with your request and an email stating that it has been completed.

A: From the Google Maps help on how to Fix an error on Google Maps:

Help us make Maps better
Community edits allow you to modify the information you see on Google Maps, making it more accurate for everyone.
To let us know about a point of interest other than a business, use the Report a Problem link and follow these instructions:

*

*Drag the marker to the position where the point of interest is located.

*Under "Which element is wrong?", select "A place or landmark."

*Under "Which place?", select "Place isn't listed."

*Fill out the details under "Problem Description" and click Report Problem

A: In the US you need a 911 address (Physical Address), this is usually calculated along a road segment. This is how car GPS units interpolate along the segment to find an address. Google also uses this method. Beyond Google, your local 911 center uses it to dispatch first responders to your location. So beyond pizza you should be more concerned if an ambulance or firetruck can find you. Just telling Google will only help if they are using Google. You may want to check with your county emergency services.
There is an association called National Emergency Numbering Assoc (NENA.org) that sets standards for addressing. So when you call 911 services can find you.


text:
Q: Как добавить свой код/проект на GitHub? Всем привет! Я уже два дня не могу добавить свой проект на GitHub.
Работаю я с Java в Inteliji IDEA, сначала пробывал добавить прямо с Inteliji с помощью кнопки "Share with GItHUb", добавил целый проект с кучей ненужной инфы. То есть мне нужно только добавить код и всё. Создать один репрозиторий для всех следующих лабораторных.

A: Андрiй, сперва настройте файл .gitignore, в нем укажите те файлы\папки которые не надо загружать на сервер GIT. Пример файла .gitignore:
.idea
*iml
conf
domain
target

Вам потребуется указать те папки которые вам не нужны на сервере git. Далее, создайте проект на GIT и после загрузите его.

*

*cd /path/to/project

*git init

*git remote add origin git@[your_git_host]:[your_login]/[your_project].git

*git add .

*git commit -m "Initial commit"

*git push -u origin master

A: *

*При создании нового репозитория на Github поставьте флажок Add .gitignore и в строке поиска наберите Java.

*Выберите появившейся пункт Java. Github сформирует необходимый шаблон, который позволит не добавлять в репозиторий "кучу ненужной инфы":

*Скопируйте файл .gitignore в локальный репозиторий.

*Удалите и заново создайте репозиторий на Github.


text:
Q: Is it "safe" to use OpenSolaris on EC2 for the foreseeable future? We have a project which needs to take advantage of some ZFS features (snapshots, streaming, etc) but we're a little concerned with the recent events with Oracle and OpenSolaris. Is it "safe" to use the current OpenSolaris images on EC2?
We're considering whether it would be "safe" to use OpenSolaris in production on EC2 until an alternative BSD or Linux distro with native ZFS support becomes available on EC2. I understand that there are a number of OSol clones in the works, and that FreeBSD may become available soon on EC2.
By "safe" I mean that the current OpenSolaris AMIs on Amazon are stable enough for production use and that there's little/no chance Amazon will pull those AMIs in the near future.

A: Due to the open-source license it was released under, the existing OpenSolaris remains safe to use. However, you should not expect any patches or bugfixes, so it is not recommended to use OpenSolaris for production systems. Have a look at the Indiana Project and Illumos kernel as a potential upgrade path. (See Wikipedia)
I'm not sure if Amazon have AMIs for Solaris Express yet, but that may be the direction you want to go for a commercial product. There might be licensing costs involved though.

A: If you are only requiring ZFS and not other Solaris features, you could also migrate to Linux as OS. IBM developerWorks has a pretty good article on using ZFS on Linux even though setup seems to be rather technically intense.
If you are depending on the features, you might give Linux with btrfs a try, it also supports snapshots, streaming and the likes.

A: OpenSolaris is dead, Oracle killed it :(
Although Solaris Express have not been discontinued, so you can use that if you want, although the license is pretty limiting.

A: Safe unless Amazon decides to cut you off like WikiLeaks without prenotice. This way you will lose all your data and possibly customers.
OpenSolaris should be as stable distro as any but alas no longer supported. For PC hardware there are so many choices, like Nexenta, or OpenFiler.


text:
Q: convertir JavaPairRDD a Json Tengo el siguiente ejemplo de WordCount y me gustaría sacar el resultado a JSONObject:
JavaPairRDD<String, Integer> counts = words.mapToPair(new PairFunction<String, String, Integer>() {
    public Tuple2<String, Integer> call(String x) {
        return new Tuple2<String, Integer>(x, 1);
    }
}).reduceByKey(new Function2<Integer, Integer, Integer>() {
    public Integer call(Integer x, Integer y) {
        return x + y;
    }
});

JSONObject json = new JSONObject();

counts.foreach(line -> {
    json.put(line._1(), line._2());
});

parece que json queda vacía después de recorrer counts, como si fuera una variable interna dentro del iterador. ¿Cómo puedo sacarla fuera?

A:     List<Tuple2<String, Integer>> finalCounts = counts.toArray();

    JSONObject json = new JSONObject();

    for (Tuple2<String, Integer> count : finalCounts)
        json.put(count._1(), count._2());


text:
Q: Git LFS migration and conf files I'm trying to migrate an existing project with multiple branches to use Git LFS.
The doc says "create and commit a file named .lfsconfig at the repository root. This file can specify LFS options the same way as allowed in .git/config"
But what happens to branches which know nothing about this .lfsconfig file or .gitattributes ? Do they use the conf files from master branch ? Do you need to set up some options globally (in your ~/.git) ?

A: This is not an answer, but too long for a comment. Hopefully, it helps to get things work:

But what happens to branches which know nothing about this .lfsconfig
file or .gitattributes?

You don't need to take care of these details. git lfs magically does what you need. See below for the process.

Do they use the conf files from master branch? Do you need to set up some options globally (in your ~/.git) ?

You don't need to change config files.
I just made a test and it works:
git init
#add test.txt
git add .
git commit -m "initial"
#change test.txt
git add .
git commit -m "l1"

git checkout -b mybranch
#change test.txt
git add .
git commit -m "mbl1"

git checkout master
#change test.txt
git add .
git commit -m "ml2"

# giving
# * 34fd7dd (HEAD -> master) ml2
# | * d58560f (mybranch) mbl1
# |/
# * de26a14 l1
# * 451129f initial

git lfs migrate import --everything --include="*.txt"
git status
# On branch master
# nothing to commit, working tree clean

git lfs ls-files
# b940d77f9e - test.txt

git checkout mybranch
# Switched to branch 'mybranch'
git branch -av
#  master   0c44e15 ml2
# * mybranch 14e031c mbl1

git lfs created a .gitattributes containing
*.txt filter=lfs diff=lfs merge=lfs -text


text:
Q: $select and $expand Odata V4 commands are generating an error I am using:

*

*.NET Framework 4.7.2

*Visual Studio 2017

*OData V4

*Web API V 5.2.4 with Entity Framework V6.2 code first with existing MS SQL DB

My $expand and $select commands are generating an error. For example, when I use the select command as follows:
http://localhost:62681/data/Advances?$select=Description

I get the following error:

The query specified in the URI is not valid. Could not find a
  property named 'Description' on type
  'Microsoft.AspNet.OData.Query.Expressions.SelectSome_1OfAdvance'

$filter and $orderby do work
The odd thing is that this used to work a couple of weeks ago, but when I came back from vacation I could not get it to work. Any help is appreciated.
I've scoured the internet for any clue to my problem, but no luck.
I've upgraded to  Microsoft.OData.Core version=7.5.0 and Microsoft.OData.Edm" version="7.5.0
My register method in WebApi.Config does have the line config.Select().Expand().Filter().OrderBy().Count().MaxTop(null);
public static void Register(HttpConfiguration config)
    {
        // Web API configuration and services

        // Web API routes
        config.MapHttpAttributeRoutes();

        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );

        ODataModelBuilder builder = new ODataConventionModelBuilder();

        config.Select().Expand().Filter().OrderBy().Count().MaxTop(null);

        builder.EntitySet<Advance>("Advances");
        builder.EntitySet<Advance_Payments>("Advance_Payments");

        config.MapODataServiceRoute(
            routeName: "ODataRoute",
            routePrefix: "data",
            model: builder.GetEdmModel());

        config.AddODataQueryFilter(new SecureAccess2Attribute());
    }

What am I doing wrong?

A: I found the solution in another stack overflow posting
EntitySetController $expand and $select not working
Go down about 2/3 of the page and look for a posting that starts with:
I came across a similar issue in OData V4. In this case it turned out if you used an attribute on the Get method and registered another attribute in your config, it errors because you are calling the EnableQuery code twice:

A: For OData V4, Remove the attribute [EnableQuery] on Controllers/Methods in the controller class IF you have enabled it globally. It accepts it only at one place.


text:
Q: What specifically makes $m_i = 0$ for all $i$ in part $(a)$? Here is the question I wanna solve:
Suppose $R$ is commutative and $N \cong R^n$ is a free $R-$module of rank $n$ with $R-$module basis $e_1, \dots , e_n.$
$(a)$ For any nonzero $R-$module $M$ show that every element of $M \otimes N$ can be written uniquely in the form $\sum_{i = 1}^{n} m_i \otimes e_i$ where $m_i \in M.$ Deduce that if $\sum_{i = 1}^{n} m_i \otimes e_i = 0 $ in $M \otimes N$ then $m_i = 0$ for $i = 1, \dots , n.$
$(b)$ Show that if $\sum m_i \otimes n_i = 0$ in $M \otimes N$ where the $n_i$ are merely assumed to be $R$-linearly independent then it is not necessarily true that all the $m_i$ are $0.$ [Consider $R = \mathbb Z, n = 1, M = \mathbb Z/ 2\mathbb Z,$ and the element $1 \otimes 2.$]
Here is by proof for part(a):
Let $N \cong R^n $ be a free $R$ module of rank $n$ with $R-$module basis $e_1, \dots , e_n,$ let $R$ be a commutative ring, we want to show that, for every non-zero $R$ module $M,$ $M \otimes N$ can be written uniquely by $\sum m_i \otimes e_i$ where $m_i \in M.$
Now, let $x\in M \otimes N.$ Then, $x=\sum_{j = 1}^p (m^{'}_j \otimes n_j)$ where $n_j= \sum_{i=1}^n r_{ji}e_i$ with $r_{ji} \in R$ (by the definition on pg.$354$ because $N \cong R^n $ is a free $R$ module of rank $n$ with $R-$module basis $e_1, \dots , e_n$). So,
\begin{align*}
x &= \sum_{j = 1}^p (m^{'}_j \otimes (\sum_{i=1}^{n} r_{ji} e_i))\\
&= \sum _{j=1}^p(\sum_{i=1}^{n} r_{ji}m^{'}_j) \otimes e_i \\
&= \sum _{i=1}^n ((\sum_{j=1}^{p} r_{ji}m^{'}_j) \otimes e_i) \\
&= \sum _{i=1}^n m_i \otimes e_i \text{ where $m_i \in M.$ }
\end{align*}
as required. Where the second equality is by the third property of tensor product given in eqn.$10.4$ on pg.$360.$ And the last equality is because $M$ is a nonzero $R-$module.
Note that this form is unique because the $r_{ji}'s$ in the definition of the free module $N$ are unique by the definition of a free module.
Now, assume that $\sum_{i = 1}^{n} m_i \otimes e_i = 0 $ in $M \otimes N$ then because $e_1, \dots , e_n,$ is a basis for $N$ then each of them is nonzero (more explicitly $e_i = (0,0, \dots , 0, 1, 0, \dots, 0)$ where the $1$ appears in the position $i.$) and so for $\sum_{i = 1}^{n} m_i \otimes e_i = 0 $ to be satisfied we must have that $m_i = 0$ for all $i = 1, \dots , n$ as $1 \otimes 0 =  0$ by Example $2$ on pg.$363$ and because tensor product is commutative on commutative rings by proposition $20$ on pg. $374$.
My questions are:
The pages in my proof are those of Dummit and Foote, Abstract Algebra, third edition.
1- Is my proof correct regarding to uniqueness part and the proof of the form or should I construct a map like here Dummit and Foote 10.4.10 like this "There is a bilinear map $b:M\times N\to M$ defined by
$$b\left(m,\sum_{i=1}^n r_ie_i\right)=r_1m.$$
This induces a linear map $\beta:M\otimes N\to M$ with
$$\beta\left(m\otimes\sum_{i=1}^n r_ie_i\right)=r_1m.$$
Then $\beta(m_1\otimes e_1)=m_1$ and $\beta(m_i\otimes e_i)=0$
for $i\ne 1$. Then
$$\beta\left(\sum_{i=1}^n m_i\otimes e_i\right)=m_1$$
so $\sum_{i=1}^n m_i\otimes e_i$ determines $m_1$ etc." ?
2- Is my justification for the last part of $(a)$ correct? or What specifically makes $m_i = 0$ for all $i$ in part $(a)$?why when the $n_i's$ are merely assumed to be $R$-linearly independent  it is not necessarily true that all the $m_i$ are $0?$ I feel like I am using only the idea of $e_i's$ being basis in my argument.
3- In part$(b),$ what is $N$?
Could anyone help me in answering these questions please?

A: *

*I don't think your proof is really complete. It is true that it follows from the uniqueness of the expansion, but there are steps in between, such as in your link. In that case the map $b$ is well defined because of the uniqueness of the representation.

*The second part of $a$ follows immediately from the first since
$$\sum_{i=1}^n m_i\otimes e_i = 0 = \sum_{i=1}^n 0\otimes e_i$$
and you just showed that such representations are unique, so $m_i=0$ for each $i$.

*In $b$ they say $n=1$ which means $N\cong R^1$, so just take $R$ for simplicity. Note that in the given example

$$1\otimes 2 = 1 \otimes (2\cdot1)=(2\cdot1)\otimes 1=0\otimes 1=0$$
so we have that $1\otimes 2=0$ but $m=1\neq0$.


text:
Q: How to use Jsonp and ajax in jsp page? I have one program that runs on a specific IP and put output in a file on same system.
I want to read that file from other system or domain(web) using ajax and jquery from jsp page.
I am getting error of cross browser origin not allowed.
To resolve this I am using jsonp as a datatype in ajax request.
But at server side do I need to handle callback parameter? how?


text:
Q: ' Windows Subsystem for Linux' option not showing up in Windows Server 2016 I am using Windows Edition 1607 on Windows Server 2016. I need to enable the ' Windows Subsystem for Linux'. I am unable to find this option in the Add Features option. You can view the screenshot for the same:

Please help me understand how to find that option. Do I need to download any additional software?

A: WSL is only available starting with Windows Server 2016 release 1803.

*

*https://virtualizationreview.com/articles/2018/06/13/installing-wsl-on-windows-server.aspx
Officially it seems it's only supported in Windows Server 2019:

*

*https://docs.microsoft.com/en-us/windows/wsl/install-on-server


text:
Q: Tableau table filter for one column only in table I have a really basic question that I can't figure out. I need to create a table that has multiple calculated fields, but I need only one of the calculated fields to be filtered for a specific dimension value. For example, I have the following data set (dummy data) and I want to create a table that will include total clicks for both companies, but [cost per click] from one company only, company B.
DATA SET
Company| Clicks| $ Cost
------------------------
Comp A | 100   | $20
Comp B | 200   | $40

WHAT I'M LOOKING FOR
       CLICKS | COST/CLICK
TOTAL   300   |  $0.13

$0.13 comes from 40/300; $40 from company B and 300 clicks from both company A and B.
How do you create a table that has multiple calculations but with one of those calculations filtered on one dimension value only?

A: One simple calculated field:
sum(if [Company] = 'B' then [Cost] end )/sum([Click])

A: This should get you in the right direction.
Based on your question and your comment, you want to divide the cost by the TOTAL number of clicks in your dataset.

*

*Create a calculated field called "TotalClicks" and enter this formula
window_sum(sum([Clicks])) // This formula will sum the clicks field for all rows

*Create a calculated field called Cost / Clicks and enter this formula
sum([Cost]) / [TotalClicks]
Add the Cost / Clicks field to the sheet and it should look like this

NOTE: If you need to partition / group your report, you may have to play around with this some. I don't use window functions within tableau very often since I usually handle the aggregation at the datasource level instead.

NOTE: Since you mentioned filtering, I will add this statement -- If you filter out any of your data, that data will not (cannot) be included in any calculated fields (To the best of my knowledge and experience, anyway). If you need to include that data (total clicks), I think the only option is to add that aggregated total to your dataset - otherwise, tableau can't calculate it if you are filtering it out.
Edit2: If you cannot change the underlying dataset, you could accomplish this by creating another datasource and joining it to your inital data source --

*

*Data > Add Datasource, add the datasource again and change the name so you can identify it

*Click Data > Edit Relationships. Click Custom and REMOVE any linked fields -- this will essentially produce a Cartesian join (every record in your first DataSource will have every reocrd from your second Datasource)

*Select the second datasource and create a calculated field (ClicksTotal_DS2) using the same window_sum function

*Select the first datasource and create a calculated field (named Cost / Clicks_DS2) using this formula
sum([Cost])/ [Sheet1 (test) (2)].[ClicksTotal_DS2]
Now you can apply a filter to your first data source, and your second data source will still calculate the total.


text:
Q: Geometric series: two ways to tackle same problem giving me issues I am trying to get a closed form expression for the following sum:
$$x + 2x^2 + 3x^3 + \cdots + nx^n$$
so by perturbation method:
$$S = x + 2x^2 + 3x^3 + \cdots + nx^n$$
$$xS=     x^2  + 2x^3 + \cdots + (n-1)x^n + nx^{n+1}$$
$$(1-x)S = x + x^2 + x^3 + \cdots + x^n - nx^{n+1}$$
Now here is where it gets weird. The professor writes that this can be simplified to this well-known sum: $1+ x+ x^2 + \cdots + x^n = \frac{1-x^{n+1}}{1-x}$
Giving us:
$$(1-x)S = \frac{1-x^{n+1}}{1-x} - nx^{n+1} - 1$$
I see the $-1$ is because there is no $1$ in our sum but can't I do the following:
$$(1-x)S = x(1 + x + x^2+\cdots+x^{n-1}) - nx^{n+1}$$
$$(1-x)S = x \left( \frac{1-x^n}{1-x} \right) - nx^{n+1}$$
So I went to wolfram to see if this was possible and got a peculiar result when I went to test:

Now I might be using wolfram wrong but is it fair to assume that these two statements:
1.) $(1-x)S = (1-x^(n+1))/(1-x) - nx^(n+1) - 1$
2.) $(1-x)S = x((1-x^n)/(1-x)) - nx^(n+1)$
are equal? And if not: where did I go wrong to get the second statement?

A: Both of your results are correct, You are just using Wolfram wrong.
Here's the actual output,

A: $$S = x + 2x^2 + \cdots + nx^n$$ implies $$(1-x)S = (x + x^2 + \cdots + x^n) - nx^{n+1}.$$  This much is clear for you.  If you do not already know the sum for a finite geometric series, this too can be obtained by the same perturbation method you just applied to $S$.  For instance, let $$G = 1 + x + x^2 + \cdots + x^n.$$  Then $$xG = x + x^2 + x^3 + \cdots + x^{n+1},$$ and $$(1-x)G = 1 - x^{n+1},$$ from which it follows that $$G = \frac{1 - x^{n+1}}{1-x}, \quad x \ne 1,$$ and in turn, $$S = \frac{(G-1) - nx^{n+1}}{1-x} = \frac{1 - x^{n+1} - 1 + x - n(1-x)x^{n+1}}{(1-x)^2} = \frac{x + (nx-n-1)x^{n+1}}{(1-x)^2}.$$
Second, judging from the output you obtained from Wolfram Alpha, your input was probably inappropriate.  The triple equals sign === is the infix notation for the expression SameQ[] in the Wolfram language, and it gives True only if the LHS and RHS are exactly the same expression.  So, if I were to guess, you might have used the word "same" in your input, rather than "equal to."  Instead of dealing with these subtleties, it is much more meaningful to simply test the formula for a few carefully chosen values of $x$ and $n$.  If you really want to, you could also input
Sum[x^k, {k,0,n}]

or you could even input
Sum[k x^k, {k,1,n}]

to get the answer to the original question.


text:
Q: R jsonlite does not parse JSON as per keys correctly When converting json to columns in R using jsonlite, I came across a bug where the column values were in the wrong columns. I tried replicating it -
R> dt <- data.table(id = 1:2,
json = c('{"user": "xyz2", "weightmap": "w1", "domains": "d1"}',
         '{"weightmap": "w2", "user": "abcd", "domains": "d2"}'))

R> dt[,fromJSON(json),.(id)]
   id user weightmap domains
1:  1 xyz2        w1      d1
2:  2   w2      abcd      d2

From what I understand, jsonlite picks the keys from the first row and expects the json in all rows to be in the same order.
I also tried this with different datatypes. Eg. If weightmap was a complex datastructure like a list or another nested json, it would fail saying the columns types are not consistent.
Is this expected behavior ? Should'nt it always read from the keys and split to cols ?
Is there a way to make jsonlite parse the json correctly ?

A: I wonder if this is a "bug" in data.table, where it is internally treating each as a list instead of a data.frame with names that need to be aligned. We can force it this way:
dt[, c(.SD, rbindlist(lapply(json, jsonlite::fromJSON), use.names=TRUE))][, json := NULL][]
#       id   user weightmap domains
#    <int> <char>    <char>  <char>
# 1:     1   xyz2        w1      d1
# 2:     2   abcd        w2      d2

If there is any complexity, what happens depends on the structure. For example, if a weightmap is a list, then
dt <- data.table(id = 1:2,
    json = c('{"user": "xyz2", "weightmap": ["w1","w2"], "domains": "d1"}',
             '{"weightmap": "w2", "user": "abcd", "domains": "d2"}'))
dt[, c(.SD, rbindlist(lapply(json, jsonlite::fromJSON), use.names=TRUE))][, json := NULL][]
# Warning in as.data.table.list(jval, .named = NULL) :
#   Item 1 has 2 rows but longest item has 3; recycled with remainder.
# Warning in as.data.table.list(jval, .named = NULL) :
#   Item 2 has 2 rows but longest item has 3; recycled with remainder.
#       id   user weightmap domains
#    <int> <char>    <char>  <char>
# 1:     1   xyz2        w1      d1
# 2:     2   xyz2        w2      d1
# 3:     1   abcd        w2      d2

which achieves an "unnesting" (noisily).

A: dt[,':='(jsonb=list(as.data.table(fromJSON(json)))),.(id)]
dt[,setcolorder(jsonb[[1]], sort(names(jsonb[[1]]))),.(id)]

The issue was that data table uses an implicit rbindlist over the lists generated for the groups. rbindlist always binds as per position unless use.names is given.
We resolved this issue by setting the colorder explicitly from the first json row so that the order of json fields are maintained.


text:
Q: Не доходит dropdown в письме обратного звонка Есть сайт, на котором я пытаюсь установить функцию обратного звонка через модальное окно. Имя и телефон доходят отлично, но никак не могу добиться значения из dropdown. В php и js не силён. Ниже приведу код, в котором какие я только манипуляции не совершал, всё ровно у меня не получилось. Может подскажете где ошибка? Файл HTML:

Оставить заявку

Заполните форму, и мы свяжемся
с вами в ближайшее время

    <form>
        Имя
        <input type="text" name="name" class="input_name" placeholder="Татьяна Иванова">

        Телефон

        <input type="text" name="phone2" class="input_ph2" placeholder="+375...">
<select name="dropdown" size="1">
<option value="option1">Сейчас</option>
<option value="option2">Через 15 минут</option>
<option value="option3">Через 30 минут</option>
</select>

<input id=u2 name="usluga" type="hidden" value="">
<input id=r2 name="referer" type="hidden" value="">
<input id=n2 name="phrase" type="hidden" value="">
<input  name="ccall" type="hidden" value="2">

        <input name="request" type="button" class="bttn bttn2 button noselect" value="Оставить заявку на консультацию">
    </form>

Файл под названием - scripts.js
    var $form = $(this).parent(),
        name = $('input[name="name"]', $form).val(),
        phone = $('input[name="phone2"]', $form).val(),
        email = $('input[name="email"]', $form).val(),
        option1 = $('input[name="option1"]', $form).val(),
        option2 = $('input[name="option2"]', $form).val(),
        option3 = $('input[name="option3"]', $form).val(),
        option4 = $('input[name="option4"]', $form).val(),

usluga = $('input[name="usluga"]', $form).val(),
referer = $('input[name="referer"]', $form).val(),
phrase = $('input[name="phrase"]', $form).val(),
ccall = $('input[name="ccall"]', $form).val(),
        ques = $('textarea[name="ques"]', $form).val(),
        sbt = $('input[type="button"]', $form).attr("name"),
        submit = $('input[name='+sbt+']', $form).val();
    var ref = $('input[name="referer"]').val();
    var ref = ref+'\nutm-метки:'+request_url;
    var formname = $('input[name="formname"]').val();
    $.ajax({
        type: "POST",
        url: url,
        dataType: "json",
        data: "name="+name+"&usluga="+usluga+"&referer="+referer+"&phrase="+phrase+"&ccall="+ccall+"&phone="+phone+"&"+sbt+"="+submit+"&email="+email+"&option1="+option1+"&formname="+formname+"&ref="+ref
    }).always(function() {
        //метрики
        //ga('send', 'event', ''+sbt, ''+sbt, ''+sbt);
        thx();
    });
}

});
И файл отвечающий за письмо, под названием - respod.php
$name ="";
$phone ="";
$dropdown ="";

        if (isset($_POST['name'])) {$name = $_POST['name']; }
        if (isset($_POST['dropdown'])) {$dropdown = $_POST['dropdown']; }
        if (isset($_POST['phone'])) {$phone = $_POST['phone'];}
        if (isset($_POST['phone2'])) {$phone.= $_POST['phone2'];}
        if (isset($_POST['phone3'])) {$phone.= $_POST['phone3'];}
echo  "name = ".$name."phone= ".$phone."dropdown= ".$dropdown;

/* Сюда впишите свою эл. почту */
 $address = "madest4815@gmail.com";

/* А здесь прописывается текст сообщения, \n - перенос строки */
 $mes = "Тема: Заказ обратного звонка!\nТелефон: $phone\nВопрос: $dropdown\nИмя: $name ";

Для Ивана:
var $form = $(this).parent(),
                name = $('input[name="name"]', $form).val(),
                phone = $('input[name="phone2"]', $form).val(),
                email = $('input[name="email"]', $form).val(),
                dropdown  = $('select[name="dropdown"]', $form).val(),
        usluga = $('input[name="usluga"]', $form).val(),
        referer = $('input[name="referer"]', $form).val(),
        phrase = $('input[name="phrase"]', $form).val(),
        ccall = $('input[name="ccall"]', $form).val(),
                ques = $('textarea[name="ques"]', $form).val(),
                sbt = $('input[type="button"]', $form).attr("name"),
                submit = $('input[name='+sbt+']', $form).val();
            var ref = $('input[name="referer"]').val();
            var ref = ref+'\nutm-метки:'+request_url;
            var formname = $('input[name="formname"]').val();
            $.ajax({
                type: "POST",
                url: url,
                dataType: "json",
                data: "dropdown="+dropdown+"name="+name+"&usluga="+usluga+"&referer="+referer+"&phrase="+phrase+"&ccall="+ccall+"&phone="+phone+"&"+sbt+"="+submit+"&email="+email+"&option1="+option1+"&formname="+formname+"&ref="+ref
            }).always(function() {
                //метрики
                //ga('send', 'event', ''+sbt, ''+sbt, ''+sbt);
                thx();
            });
        }
    });

A: В js вам нужно брать значение не из option[name=*], а из select[name=dropdown]. Примерно так
var $form = $(this).parent(),
    ...
    dropdown = $('select[name="dropdown"]').val(),
    ...;

...
    data: "dropdown="+dropdown+"&name="+name+"&usluga="+usluga+"&...
    ...

А на данный момент у вас в js не добавляется переменной по имени dropdown к отправке формы. Поэтому, хотя в php, вроде бы, все верно, в письме ничего не отправляется.


text:
Q: "Then obviously..." (a bound on strongly differential functions on an interval) On the fourth page of their 1967 paper Local Behavior of Solutions of Quasilinear Parabolic Equations, Aaronson and Serrin comment: "Consider a strongly differentiable function $w$ of the real variable $x$, $0 < x < d$. Then obviously
$$|w(x)|^{2} \leq \frac{2}{d}\int_{0}^{d}|w|^{2}\ dx + 2d\int_{0}^{d}|w_{x}|^{2}\ dx$$
and..."
And obviously I don't get it, and am wondering what background I need to fill in before I can read this paper.

A: This is I think just a very loose bound of the max norm by the norm of the function and the norm of the (strong) derivative. For any function $f$ defined over $(0,d)$  we have
$$|f(x)| \leq \text{min}|f(t)| + \int_0^d |f'(t)| dt \leq \frac{1}{d}\int_0^d|f(t)|dt + \int_0^d |f'(t)| dt $$
All you need now is to replace $f(x)$ by $w^2(x)$. Note by AM-GM inequality
$$\frac{1}{d}\int_0^d|w|^2dt + d\int_0^d|w_t|^2dt \geq 2\int_0^d|w\cdot w_t|dt=\int_0^d|(w^2(t)'|dt$$
and the inequality follows.
You probably don't need more back ground. You just need to treat each of the "obviously", "easy too see" etc statements as an exercise and try to solve it.

A: Alternatively
$$
w(x)^2-w(y)^2=\int_y^x (w(u)^2)^{\prime}du = 2 \int_y^x w(u) w^\prime(u) du
$$
Since $2ab \leq a^2/t +t b^2$ for any $t$, we have
\begin{eqnarray*}
w(x)^2&\leq& w(y)^2 + \frac{1}{t}\int_y^x w^2(u)du +t \int_{y}^{x} (w')^2(u)du \\
      &\leq& w(y)^2   + \frac{1}{t}\int_0^d w^2(u)du +t \int_{0}^{d} (w')^2(u) du
\end{eqnarray*}
Now integrate this inequality with respect to $y$ between $0$ and $d$
$$
d w(x)^2  \leq \int_0^d w(y)^2dy + \frac{d}{t}\int_0^d w^2(u)du +dt \int_{0}^{d} (w')^2(u)du
$$
divide both sided by $d$ and choose $t=d$ to obtain
$$
 w(x)^2  \leq \frac{2}{d}\int_0^d w(y)^2dy + d \int_{0}^{d} (w')^2(u)du.
$$


text:
Q: Excel - Extract text from multiple columns I am trying to fill in a column ("mode of communication") based if a value is present in other columns.
This is how the rows and columns appear now.
+------+----------------+----------------+------------+----------------+
| Mode | In Person      | Email          | IM         | Phone          |
+------+----------------+----------------+------------+----------------+
|      | In person < 5  |                |            |                |
+------+----------------+----------------+------------+----------------+
|      |                | Email 10 - 15  |            |                |
+------+----------------+----------------+------------+----------------+
|      |                |                | IM < 5 min |                |
+------+----------------+----------------+------------+----------------+
|      |                |                |            | Phone 10 - 15  |
+------+----------------+----------------+------------+----------------+
|      |                |                | IM < 5 min |                |
+------+----------------+----------------+------------+----------------+

What I want is to use a formula to get it to scan through the thousands of rows and insert text into the Mode of Communication column based on if there is an entry in "In Person", "Email", "IM", or "Phone", and then to ideally create a separate column with the duration.
+-----------------------+-------------+-----------+-------+----+-------+
| Mode of Communication | Time Spent  | In Person | Email | IM | Phone |
+-----------------------+-------------+-----------+-------+----+-------+
| In Person             | < 5 min     |           |       |    |       |
+-----------------------+-------------+-----------+-------+----+-------+
| Email                 | 10 - 15 min |           |       |    |       |
+-----------------------+-------------+-----------+-------+----+-------+
| IM                    | < 5 min     |           |       |    |       |
+-----------------------+-------------+-----------+-------+----+-------+
| Phone                 | < 5 min     |           |       |    |       |
+-----------------------+-------------+-----------+-------+----+-------+
| In Person             | 10 - 15 min |           |       |    |       |
+-----------------------+-------------+-----------+-------+----+-------+

I have been trying to use VLOOKUP. All the rows and columns are on the same sheet.

A: Put this in the 'Mode of Communication' column:
=IF(C2<>"","In Person",IF(D2<>"","Email",IF(E2<>"","IM",IF(F2<>"","Phone",""))))
Put this in the 'Time Spent' column:
=IF(C2<>"",SUBSTITUTE(C2,"In person ","")&" min",IF(D2<>"",SUBSTITUTE(D2,"Email ","")&" min",IF(E2<>"",SUBSTITUTE(E2,"IM ","")&" min",IF(F2<>"",SUBSTITUTE(F2,"Phone ","")&" min",""))))
These assume that column A is Mode of Communication and column B is Time Spent.

A: Insert a new blank column between column A and column B.
In A2,
=IFERROR(INDEX(C$1:F$1, MATCH("zzz", C2:F2)), TEXT(,))

In B2,
=IFERROR(TRIM(REPLACE(INDEX(C2:F2, MATCH("zzz", C2:F2)), 1, LEN(A2), TEXT(,))), TEXT(,))

Fill down.

A: One of the solutions I see is concatenating all column and parse.
For example in column " Mode of Communication" you can use concatenate(inperson,email,im,phone) and then parse the data.
Use this formula in Mode of communication column: Cell A2
=TRIM(SUBSTITUTE(CONCATENATE(C2,D2,E2,F2),B2,""))
Time Spent Column: Cell B2
=TRIM(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(CONCATENATE(C2,D2,E2,F2),"In person",""),"Email",""),"IM",""),"Phone",""))


text:
Q: Formatting an NSDate I am pulling data from an RSS Feed. One of the keys in the feed is is a string representing the date and time the item was created.
I am trying to convert this string value to an NSDate. The string value is returned from the RSS feed as: 2009-11-18T22:08:00+00:00
I tried the following code to no avail:
    NSDateFormatter *df = [[NSDateFormatter alloc] init];
[df setDateFormat:@"yyyyMMdd HH:mm"];
NSDate *myDate = [df dateFromString: [[storedDates objectAtIndex:indexPath.row] objectForKey: @"UsersDate"]];

Ideally; on top of converting the value to a NSDate value, I would also like to format it using the localised date format on the handset.
Any pointers would be a great help.
Kind Regards

A: To retrieve the dateFormat:
NSDateFormatter *df = [[NSDateFormatter alloc] init];
[df setDateFormat:@"yyyy-MM-dd'T'HH:mm:ssZ"];
NSDate *myDate = [df dateFromString: [[storedDates objectAtIndex:indexPath.row] objectForKey: @"UsersDate"]];

You can use the predefined formats if you would like to format time and date according to the user's locale:
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateStyle:NSDateFormatterShortStyle];
[dateFormatter setTimeStyle:NSDateFormatterLongStyle];
NSLog(@"%@",[dateFormatter stringFromDate:someDate]);
[dateFormatter release]; // don't forget to release the dateformatter

Check the documentation to see which formatter suits you best.

A: Actually date form in RSS feed may differ, so best way to parse it is following
[NSDate dateFromInternetDateTimeString:processedText formatHint:DateFormatHintRFC822];

This is not a standard function, library for it can be found here https://gist.github.com/953664


text:
Q: How do I fix "IntelliSense: PCH warning:" On the first line of each file .cpp in a C++-cli project:
#include "StdAfx.h"

..I have the following warning and intellisense refuses to work:
IntelliSense: PCH warning:

I've tried:

*

*Rebooting my machine.

*Deleting all the .sdf files.

*Doing a clean / rebuild all.

...what might cause this and how can I fix it?

A: I'm not sure why, but removing and re-adding the last pair of files I added to the project appears to have resolved the issue.
This is possibly because I renamed a class after adding it and the old versions got cached or something like that? Strange that clearing the .sdf file didn't fix it though.


text:
Q: TypeError: unsupported operand type(s) for *: 'builtin_function_or_method' and 'int' when multiplying using asterisk (*) In the HuBMAPDataset class, I set sz using self.sz = reduce*sz. My code raised unsupported operand type error.
reduce = 4
class HuBMAPDataset:
    def __init__(self, idx, fold, train=True, tfms=None):
        self.data = rasterio.open(os.path.join(DATA,idx+'.tiff'), transform = identity,num_threads='all_cpus')
        ids = pd.read_csv(LABELS).id.astype(str).values
        kf = KFold(n_splits=nfolds,random_state=SEED,shuffle=True)
        ids = set(ids[list(kf.split(ids))[fold][0 if train else 1]])
        self.fnames = [fname for fname in os.listdir(TRAIN) if fname.split('_')[0] in ids]
        self.train = train
        self.tfms = tfms
        if self.data.count != 3:
            subdatasets = self.data.subdatasets
            self.layers = []
            if len(subdatasets) > 0:
                for i, subdataset in enumerate(subdatasets, 0):
                    self.layers.append(rasterio.open(subdataset))
        self.shape = self.data.shape
        self.reduce = reduce
        self.sz = reduce*sz
        self.pad0 = (self.sz - self.shape[0]%self.sz)%self.sz
        self.pad1 = (self.sz - self.shape[1]%self.sz)%self.sz
        self.n0max = (self.shape[0] + self.pad0)//self.sz
        self.n1max = (self.shape[1] + self.pad1)//self.sz

    def __len__(self):
        return len(self.fnames), self.n0max*self.n1max

    def __getitem__(self, idx):
        fname = self.fnames[idx]
        img = cv2.cvtColor(cv2.imread(os.path.join(TRAIN,fname)), cv2.COLOR_BGR2RGB)
        mask = cv2.imread(os.path.join(MASKS,fname),cv2.IMREAD_GRAYSCALE)
        if self.tfms is not None:
            augmented = self.tfms(image=img,mask=mask)
            img,mask = augmented['image'],augmented['mask']
        n0,n1 = idx//self.n1max, idx%self.n1max
        x0,y0 = -self.pad0//2 + n0*self.sz, -self.pad1//2 + n1*self.sz
        p00,p01 = max(0,x0), min(x0+self.sz,self.shape[0])
        p10,p11 = max(0,y0), min(y0+self.sz,self.shape[1])
        img = np.zeros((self.sz,self.sz,3),np.uint8)
        if self.data.count == 3:
            img[(p00-x0):(p01-x0),(p10-y0):(p11-y0)] = np.moveaxis(self.data.read([1,2,3],
                window=Window.from_slices((p00,p01),(p10,p11))), 0, -1)
        else:
            for i,layer in enumerate(self.layers):
                img[(p00-x0):(p01-x0),(p10-y0):(p11-y0),i] =\
                  layer.read(1,window=Window.from_slices((p00,p01),(p10,p11)))
        if self.reduce != 1:
            img = cv2.resize(img,(self.sz//reduce,self.sz//reduce),
                             interpolation = cv2.INTER_AREA)
        #check for empty imges
        hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
        h,s,v = cv2.split(hsv)
        if (s>s_th).sum() <= p_th or img.sum() <= p_th:
            #images with -1 will be skipped
            return img2tensor((img/255.0 - mean)/std), -1, img2tensor(mask)
        else: return img2tensor((img/255.0 - mean)/std), idx, img2tensor(mask)

for fold in range(nfolds):
    for idx,row in tqdm(df_sample.iterrows(),total=len(df_sample)):
        idx = str(row['id'])
        ds_t = HuBMAPDataset(idx, fold=fold, train=True, tfms=get_aug())

Traceback:
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
/tmp/ipykernel_33/1067530021.py in <module>
      3     for idx,row in tqdm(df_sample.iterrows(),total=len(df_sample)):
      4         idx = str(row['id'])
----> 5         ds_t = HuBMAPDataset(idx, fold=fold, train=True, tfms=get_aug())
      6         ds_v = HuBMAPDataset(idx, fold=fold, train=False)
      7         data = ImageDataLoaders.from_dsets(ds_t,ds_v,bs=bs,num_workers=NUM_WORKERS,pin_memory=True).cuda()

/tmp/ipykernel_33/3421423662.py in __init__(self, idx, fold, train, tfms)
     25         self.shape = self.data.shape
     26         self.reduce = reduce
---> 27         self.sz = reduce*sz
     28         self.pad0 = (self.sz - self.shape[0]%self.sz)%self.sz
     29         self.pad1 = (self.sz - self.shape[1]%self.sz)%self.sz

TypeError: unsupported operand type(s) for *: 'builtin_function_or_method' and 'int'

df_sample (as dictionary)
df_sample.to_dict()
{'id': {0: 10078}, 'rle': {0: '12 34'}}

A: 'reduce' is a function from functools. You multiply a function with an int. That's why you got the error.
You can reproduce this error by the following simple code:
from functools import reduce
c = reduce * 3


text:
Q: Jquery UI Animate background using scroll_pos I am working on changing the background of a div on scroll.  It works, but not consistently.  It sometimes doesn't make the change back when you scroll to the top position.  Other times it does, but there is a delay in the animation.  Any idea where I am going wrong here?
    var scroll_pos = 0;
        $(document).scroll(function() {
            scroll_pos = $(this).scrollTop();
            if(scroll_pos > 1) {
            $('.head').animate({'background-color':'rgba(0,0,0,1)'}, 500);
            $('.header li a, .header li a:visited, .header li a:active').animate({'color':'rgba(255,255,255,1)'},500);
            }
            if(scroll_pos < 1){
                $(".head").animate({'background-color':'rgba(223,223,223,0.8)'}, 500);
                $(".header li a, .header li a:visited, .header li a:active").animate({'color':'rgba(60,60,60,0.7)'}, 500);
            }
        });

I am using Jquery Mobile also, so my document ready function is actually;
    $(document).on('pageinit', function

Is it possible that this is causing the issue?

A: take a look at this example of transitioning the color from black to white on scroll of the document, you could use a logic like this if you want the color to change dependent to the scroll position: DEMO
var length=255/($(document).height()-$(window).height());
$(document).scroll(function(){
    var amount=Math.ceil($(document).scrollTop()*length);
    $('body').css('background-color','rgb('+amount+','+amount+','+amount+')');
});


text:
Q: Saltstack or JInja2 - Merge yaml with dictionary I am trying to merge a dictionary with a yaml file content and pass them to some salt state.
metricbeat.yml content:
metricbeat:
  config:
    modules:
      path: /etc/metricbeat/modules.d/*.yml
      reload.enabled: true
      reload.period: 10s

output.logstash:
  hosts:
  worker: 1
  compression_level: 3
  loadbalance: true
  ssl:
    certificate: /usr/share/metricbeat/metricbeat.crt
    key: /usr/share/metricbeat/metricbeat.key
    verification_mode: none

logging:
  level: debug
  to_files: true
  files:
    path: /var/tellme/log/metricbeat
    name: metricbeat.log
    rotateeverybytes: 10485760
    keepfiles: 7

config.yml content:
metricbeat:
  config:
    modules:
      reload.period: 100s

Statefile:
{% import_yaml "config.yml" as config %}

manage_file:
  file.managed:
    - name: /etc/metricbeat/metricbeat.yml
    - source: salt://metricbeat.yml
    - template: jinja

conf_file:
  file.serialize:
    - name: /etc/metricbeat/metricbeat.yml
    - dataset:
        output.logstash:
          hosts: ['exacmple.domain.com:5158']
        {{ config | yaml }}
    - serializer: yaml
    - merge_if_exists: true

But I am getting the below error:
example-1.domain.com:
    Data failed to compile:
----------
    Rendering SLS 'base:test' failed: could not find expected ':'

What am I doing wrong ?

A: Fixed the issue as below
{% import_yaml "config.yml" as config %}

manage_file:
  file.managed:
    - name: /etc/metricbeat/metricbeat.yml
    - source: salt://metricbeat.yml
    - template: jinja

conf_file:
  file.serialize:
    - name: /etc/metricbeat/metricbeat.yml
    - dataset:
        output.logstash:
          hosts: ['exacmple.domain.com:5158:5158']
        {{ config | yaml(false) | indent(8) }}
    - serializer: yaml
    - merge_if_exists: true

"yaml(false)" is for multiline yaml and proper indentation with "indent".


text:
Q: Cloudfront cache-control headers missing I setup Cloudfront to serve static images, js, css files for www.lottoresults.ie. I used a custom origin server.
The cloudfront domain name I setup is icdn.lottoresults.ie. I set this up using Bind9 dns, with icdn.lottoresults.ie a CNAME for the cloudfront distro.
That's all fine.
However, for website performance optimization (Yslow, google pagespeed etc), I want to have Cache-control and Expires headers set, and I do not want Etags.
To do this, I have the following in my htaccess file for the doc_root of www.lottoresults.ie:
Header unset Pragma
FileETag none
Header unset ETag

<FilesMatch "(.*)\.(ico|jpg|jpeg|png|gif|js|css|swf)$">
ExpiresActive on
ExpiresDefault "access plus 1 year"
Header set Cache-Control "max-age=1864000, public"
Header unset Last-Modified
</FilesMatch>

The problem is that for assets coming from the cloudfront distro (icdn), I have no Cache-control or Expires headers, but I do have Etags - yet for www I do have Cache-control and Expires headers, and no Etags.
When I query an asset from my cloudfront domain, I have no Cache-control or Expires headers, but I do have Etags.
curl -I -L http://icdn.lottoresults.ie/images/green-header.jpg
HTTP/1.0 200 OK
Date: Sun, 01 Apr 2012 22:58:30 GMT
Server: Apache/2.2.9 (Debian) PHP/5.2.6-1+lenny13 with Suhosin-Patch
Last-Modified: Mon, 08 Aug 2011 20:23:00 GMT
**ETag**: "28a213-19b-4aa0436a1b100"
Accept-Ranges: bytes
Content-Length: 411
Content-Type: image/jpeg
Age: 22137
X-Cache: Hit from cloudfront
X-Amz-Cf-Id: AV55dR4_vWHtlTbU6E9M2tkh9reoAwZcHlD4y9csetK6B6Ey8gDPJA=
Via: 1.0 8adf6ec3585d73c680b4a6d5052988d8.cloudfront.net (CloudFront)
Connection: close

Yet when I query the same asset from my origin server, I get the following, which includes Cache-control, Expires, and no Etags.
curl -I -L http://www.lottoresults.ie/images/green-header.jpg
HTTP/1.1 200 OK
Date: Fri, 06 Apr 2012 20:50:08 GMT
Server: Apache/2.2.9 (Debian) PHP/5.2.6-1+lenny13 with Suhosin-Patch
Accept-Ranges: bytes
Content-Length: 411
**Cache-Control**: max-age=1864000, public
**Expires**: Sat, 06 Apr 2013 20:50:08 GMT
Content-Type: image/jpeg

Any help or advice greatly appreciated.
Thanks
Paul

A: I think I know what this was, for anyone else who might have same issue.
It is kind of PEBKAC - I have to invalidate the assets before they acquire new headers.
E.g. I added a new file, images/zoom2.gif, and it looks correct:
curl -I -L http://icdn.lottoresults.ie/images/zoom2.gif
HTTP/1.0 200 OK
Date: Fri, 06 Apr 2012 23:00:24 GMT
Server: Apache/2.2.9 (Debian) PHP/5.2.6-1+lenny13 with Suhosin-Patch
Accept-Ranges: bytes
Content-Length: 1849
Cache-Control: max-age=1864000, public
Expires: Sat, 06 Apr 2013 23:00:24 GMT
Content-Type: image/gif
Age: 29
X-Cache: Hit from cloudfront
X-Amz-Cf-Id:         vPPBdJpw0ZI_J2trHyECnE2UBeQO9NsQZD9GSvl3GIVAZuQN5lz1ZQ==,J4bBHfF5lKEpjRPLZVYpS9HUdAKEOLEe-Gy3-a_x4PsLPrdWuRg93Q==
Via: 1.0 00204466f749ba432b50dc49d604c534.cloudfront.net (CloudFront)
Connection: close


text:
Q: Playing a sound periodically in the background on iOS I'd like to play a sound periodically while the app is in the background but after doing some research it's not certain if this is possible. Before I give up or waste too much time trying I want to double check with the community if this is really possible or not.
I figured out how to enable playing sounds while the app is in the background but the app is still eventually killed and the timer stops firing (there's a 10 minute period it runs in suspended mode if I use beginBackgroundTask: but that's not enough). Other ideas I had:
1) There appears to be a "background fetch" mode which could maybe be used like a timer but this is a hack and may be rejected by Apple.
2) Loop blank audio in the background or some other looping part of audio API's to keep the app alive? Again Apple may reject that even it's possible.
3) Enable the location API to keep the app alive and play audio. Hack again, bad for battery and Apple 99% will reject this.
4) I read somewhere that push notifications could work for this but that requires a complicated server backend and if it's possible that last resort.
Are any of those methods viable or are there others?

A: You can use scheduled Local Notifications with sounds.


text:
Q: Probability of at least 3 sixes with 18 dice I am trying to logically think about this, not to just apply formulas that are readily available for similar problems.  Can anyone help explain the math behind finding the probability of getting at least 3 sixes when rolling 18 (six sided) dice?

A: The probability of not rolling any six is given by $\left(\frac{5}{6}\right)^{18}$, the probability of getting exactly one six is given by $18\cdot\frac{1}{6}\left(\frac{5}{6}\right)^{17}$ and the probability of getting exactly two sixes is given by $\binom{18}{2}\left(\frac{1}{6}\right)^2\left(\frac{5}{6}\right)^{16}$, so the probability of getting three or more sixes is given by:
$$ 1 - \left(\frac{5}{6}\right)^{18} - 18\cdot\frac{1}{6}\left(\frac{5}{6}\right)^{17} - \binom{18}{2}\left(\frac{1}{6}\right)^2\left(\frac{5}{6}\right)^{16} \approx \color{red}{59,73\%}.$$


text:
Q: Fit an SVG text inside an SVG background rectangle Here is a box containing two SVGs. one for the text and one for the background rectangle.
I want to fit the text inside the background rectangle. so that there is no text stretching out of the background rectangle. (Note that I don't want to line break the text I want to decrease the dimensions of the text or something to fit the text inside the rectangle in a single line);
I have tried a lot of solutions with no luck and I think maybe there are no pure CSS solutions, So even Javascript to fix this wired issue is accepted.
Note: I really need the text and the background rectangle to be SVGs.
Here is the CodePen.
And Here is the code:

@font-face {
  font-family: "Heebo-Light";
  src: url(Heebo-Light.ttf) format("truetype");
}

svg {
    position: relative;
    display: block;
    overflow: visible;
    pointer-events: none;
}

body {
  background-color: #FDFDFD;
  overflow: hidden;
}

.box svg:nth-of-type(1) {
  position: absolute;
  z-index: 3;
}

.box svg:nth-of-type(2) {
  position: absolute;
  z-index: 2;
}

.box, svg {
  max-width: 100%;
  max-height: 2.59vw;
}

.box {
  position: relative;
  height: 2.59vw;
}

   <svg height="100%" width="100%" viewBox="0 0 100 45">
      <text font-family="Heebo-Light" font-size="24px" fill="#595959" fill-opacity="1" x="50%" y="53%" dominant-baseline="middle" text-anchor="middle">
         <tspan id="span-15">This is a long text that should be fit This is a long text that should be fit This is a long text that should be fit</tspan>
      </text>
   </svg>
   <svg height="100%" width="100%" viewBox="0 0 272 45" preserveAspectRatio="none">
      <defs>
         <linearGradient gradientTransform="rotate(90, 0.5, 0.5)" id="uniqueDomIdA-4">
            <stop offset="0%" stop-color="#AFAFAF" stop-opacity="1"></stop>
            <stop offset="0%" stop-color="#F5F3F8" stop-opacity="1"></stop>
            <stop offset="69.804%" stop-color="#F9F9F9" stop-opacity="1"></stop>
            <stop offset="100%" stop-color="#FFFFFF" stop-opacity="1"></stop>
         </linearGradient>
         <filter id="uniqueDomIdB-4" filterUnits="userSpaceOnUse" x="-15.75" y="-15.75" width="303.5" height="76.5">
            <feFlood result="floodOut" flood-color="#CCC1DA" flood-opacity="0.29"></feFlood>
            <feGaussianBlur result="gaussOut" in="SourceAlpha" stdDeviation="2.450000047683716,2.450000047683716">
            </feGaussianBlur>
            <feComposite in="floodOut" in2="gaussOut" operator="in"></feComposite>
         </filter>
      </defs>
      <use transform="translate(-2.72, -0.45) scale(1.0199999809265137, 1.0199999809265137) translate(0, 0)" xlink:href="#uniqueDomIdC-4" filter="url(#uniqueDomIdB-4)" data-angle="0" data-distance="0" data-height="45" data-scale="1.02" data-adornment-type="drop-shadow" data-width="272" data-transform="[{"type":"translate","args":[-2.72,-0.45]},{"type":"scale","args":[1.0199999809265137,1.0199999809265137]}]"></use>
      <g id="uniqueDomIdC-4">
         <g>
            <path d="M0,0L272,0 272,45 0,45z" fill="url(#uniqueDomIdA-4)"></path>
         </g>
      </g>
   </svg>

Edit: Changing veiwBox seems promising But I have no idea how to calculate it! I can calculate box width but I don't know how to find viewBox...?

A: Since the box is very small and the text is very long the text will be bearly visible.
In javascript I'm getting the length of the text: span15.getComputedTextLength() and I'm using this value for the viewBox attribute

let text_length = span15.getComputedTextLength();

document.querySelector("#first").setAttribute("viewBox",`0 0 ${text_length} 45`)
@font-face {
  font-family: "Heebo-Light";
  src: url(Heebo-Light.ttf) format("truetype");
}

svg {
    position: relative;
    display: block;
    overflow: visible;
    pointer-events: none;
    outline:solid red;
}

body {
  background-color: #FDFDFD;
  overflow: hidden;
}
.box {
  position: relative;
  height: 2.59vw;
  outline:solid;
}

   <svg id="first" viewBox="0 0 100 45">
      <text font-family="Heebo-Light" font-size="24px" fill="#595959" fill-opacity="1" x="50%" y="53%" dominant-baseline="middle" text-anchor="middle">
         <tspan id="span15">This is a long text that should be fit This is a long text that should be fit This is a long text that should be fit</tspan>
      </text>
   </svg>

A:

  <svg height="100%" width="100%" viewBox="0 0 272 45" preserveAspectRatio="none">
      <defs>
         <linearGradient gradientTransform="rotate(90, 0.5, 0.5)" id="uniqueDomIdA-4">
            <stop offset="0%" stop-color="#AFAFAF" stop-opacity="1"></stop>
            <stop offset="0%" stop-color="#F5F3F8" stop-opacity="1"></stop>
            <stop offset="69.804%" stop-color="#F9F9F9" stop-opacity="1"></stop>
            <stop offset="100%" stop-color="#FFFFFF" stop-opacity="1"></stop>
         </linearGradient>
         <filter id="uniqueDomIdB-4" filterUnits="userSpaceOnUse" x="-15.75" y="-15.75" width="303.5" height="76.5">
            <feFlood result="floodOut" flood-color="#CCC1DA" flood-opacity="0.29"></feFlood>
            <feGaussianBlur result="gaussOut" in="SourceAlpha" stdDeviation="2.450000047683716,2.450000047683716">
            </feGaussianBlur>
            <feComposite in="floodOut" in2="gaussOut" operator="in"></feComposite>
         </filter>
      </defs>
      <use transform="translate(-2.72, -0.45) scale(1.0199999809265137, 1.0199999809265137) translate(0, 0)" xlink:href="#uniqueDomIdC-4" filter="url(#uniqueDomIdB-4)" data-angle="0" data-distance="0" data-height="45" data-scale="1.02" data-adornment-type="drop-shadow" data-width="272" data-transform="[{"type":"translate","args":[-2.72,-0.45]},{"type":"scale","args":[1.0199999809265137,1.0199999809265137]}]"></use>
      <g id="uniqueDomIdC-4">
         <g>
            <path d="M0,0L272,0 272,45 0,45z" fill="url(#uniqueDomIdA-4)"></path>
      <foreignObject
        x="0" y="0" width="100%" height="100%"
      >

This is a long text that should be fit This is a long text that should be fit This is a long text that should be fit

      </foreignObject>
         </g>
      </g>
   </svg>


text:
Q: How to add submenu items to NavigationView programmatically instead of menu xml I'm trying to add submenu items to NavigationView programmatically . I'm able to add items into menu but not into submenu
Adding items to menu works
Menu menu = mNavigationView.getMenu();
menu.add(Menu.NONE, Menu.NONE, index, "Menu Item1");

But adding items to sub menu doesn't work
Menu menu = mNavigationView.getMenu();
SubMenu subMenu = menu.addSubMenu("Sub menu title");
subMenu.add(Menu.NONE, Menu.NONE, index, "SubMenu Item1");

A: The trick to call BaseAdapter.notifyDataSetChanged on the underlying Adapter that contains the menu items. You could use reflection to grab the ListView or just loop over the NavigationView children until you reach it.
This isn't the most up-to-date code, as fas as I know Google hasn't pushed the most recent changes to the Support Library, but essentially NavigationMenuPresenter.prepareMenuItems is called when you call BaseAdpater.notifyDataSetChanged.
But if you want to see the most recent source, you can download it through the SDK Manager. Choose Sources for Android MNC. Then navigate to
yourAndroidSDK/sources/android-MNC/android/support/design/internal/NavigationMenuPresenter.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    ...
    final Menu menu = mNavigationView.getMenu();
    for (int i = 0; i < 4; i++) {
        menu.add("Menu Item " + (i + 1));
    }
    final SubMenu subMenu = menu.addSubMenu("SubMenu Title");
    for (int i = 0; i < 2; i++) {
        subMenu.add("SubMenu Item " + (i + 1));
    }
    for (int i = 0, count = mNavigationView.getChildCount(); i < count; i++) {
        final View child = mNavigationView.getChildAt(i);
        if (child != null && child instanceof ListView) {
            final ListView menuView = (ListView) child;
            final HeaderViewListAdapter adapter = (HeaderViewListAdapter) menuView.getAdapter();
            final BaseAdapter wrapped = (BaseAdapter) adapter.getWrappedAdapter();
            wrapped.notifyDataSetChanged();
        }
    }

}

Results

A: Somebody figured out a way to do it via reflection and accessing a private field. It's not pretty, but it'll work, for the moment.
https://stackoverflow.com/a/30604299/4232051


text:
Q: Date Formatting like Date Picker in SSRS I'm using reporting service.
How can I set date to be formatted like, we manually select date using date picker.
I want a textbox should be formatted like below image on tab click.

Please help me. Thanks in advance!


text:
Q: LINQ inheritance query I'm supporting a system that has a hierarchy of groups that fall under an top level entity. Conceptually it looks like this:
id | Group      | parent
-------------------------
10 | Enterprise | N/A
20 | Partner A  | 10
21 | Partner B  | 10
29 | Business Q | 21

The actual group table looks like this:
int | GroupID
int | BusinessID (nullable)
int | PartnerID (nullable)

So the data looks like this:
GrpID | PtnrID | BzID  | Name
------------------------------------
10    | null   | null  | Enterprise
20    | 10     | null  | Partner A
21    | 10     | null  | Partner B
29    | 10     | 21    | Business Q

Instead of a group referring to a parent group, groups store partnerid and businessid which are nullable and point to another groups's GroupID.
Group-specific settings can be stored at any level. Enterprise defines the default value, but partner and business entities can override. Ex:
10 | color | red
20 | color | blue
29 | color | green

this would result in the following settings
Enterprise | red
Partner A  | blue
Partner B  | red
Business   | green

I'm trying to write a linq query that gets the setting for a given group, but am having trouble
from set in GroupSettings
from grp in Groups
where set.setting=="color" && grp.GroupID==29 &&
(
set.GroupID==grp.BusinessID || set.GroupID==grp.PartnerID
)
select set

this returns both the definition for Enterprise and the overridden value for the business
10 | red
29 | green

Is there a syntax that I can use that will give me (for lack of a better term) exclusive or functionality in my where clause that only falls through to the next or statement if the current one isn't met? My goal is to only return the relevant row - 29 | green in this case.

A: This Linq query does produce the correct output for the situation in your question. I basically have three left outer joins between group and its own setting, its business setting and its partner setting. This gives a result with 3 values. The projection selects the first non-null value.
var r = from grp in Groups
        join da in GroupSettings on grp.GroupID equals da.GroupID into ga // direct
        join db in GroupSettings on grp.BzId equals db.GroupID into gb // Busisness
        join dc in GroupSettings on grp.PartnerId equals dc.GroupID into gc // Partner
        from gar in ga.DefaultIfEmpty()
        from gbr in gb.DefaultIfEmpty()
        from gcr in gc.DefaultIfEmpty()
        where grp.GroupID == 29
        select new { setting = gar ?? gbr ?? gcr };  // null coalesce


text:
Q: Get list of files from s3 bucket with a particular substring I have an s3 bucket that has various kinds of file.
Example - abc.csv, def.tsv, ghi_sub_jkl.avro, mno_sub_pqrs.avro and others.
I need a function that can give me a list of files that have a particular substring in its filename.
In the above example I need the files having "sub" as the substring.
Therefore, the output list must contain - ['ghi_sub_jkl.avro', 'mno_sub_pqrs.avro']
Is there a way to do it?

A: You may use the following code:
import boto3

s3 = boto3.resource('s3')
my_bucket = s3.Bucket('mybucket')

files_list = [file.key for file in my_bucket.objects.all() if 'sub' in file.key]


text:
Q: Compilation fail standalone & pst-solides3d I've got a PStricks schema made with both pst-solides3d and pst-3dplot, put (thanks to the standalone package) apart in a different file.
The schema, when compiled itself, doesn't make any problems, and the output is normal, as it should be.
This is the preamble of my main document :
\documentclass[a4paper,11pt]{report}
\usepackage{standalone}
\usepackage{a4wide}
\usepackage[french]{babel}
\NoAutoSpaceBeforeFDP % empêcher d'ajouter un espace après :
\usepackage[table, usenames,dvips, dvipsnames]{xcolor}
\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}
\usepackage{amsmath, here}
\usepackage[hyperindex, pdfborder={0 0 0}]{hyperref} % Table des matières & références interactive
\usepackage{url}
\usepackage{wrapfig}
\usepackage{fancyhdr}
\usepackage{fancyref}

\usepackage{pstricks,  pst-circ, pst-plot, pst-3dplot, pst-solides3d}
\usepackage[locale = FR]{siunitx}

If I load the pst-solides3d (required to draw the schema in the included file), it doesn't compile, and I got this as error :
Error: /typecheck in --length--
Operand stack:
71.7882   -207.763   71.7882   -193.537   71.7882   -179.31   71.7882   -179.31
[...]
809.324   -165.366   809.324   -165.366   1   1
Execution stack:
%interp_exit   .runexec2   --nostringval--   --nostringval--   --nostringval--   2
%stopped_push   --nostringval--   --nostringval--   --nostringval--   false   1
%stopped_push   1900   1   3   %oparray_pop   1899   1   3   %oparray_pop   18831   3   %oparray_pop   1771   1   3   %oparray_pop   --nostringval--   %errorexec_pop   .runexec2
--nostringval--   --nostringval--   --nostringval--   2   %stopped_push
--nostringval--
--nostringval--
Dictionary stack:
--dict:1163/1684(ro)(G)--   --dict:1/20(G)--   --dict:139/200(L)--
--dict:747/1012(L)--   --dict:227/300(L)--   --dict:62/200(L)--   --dict:57/75(L)--
--dict:211/313(L)--   --dict:72/140(L)--   --dict:0/10(G)--   --dict:18/20(L)--
--dict:4/50(ro)(G)--   --dict:56/71(L)--
Current allocation mode is local
Last OS error: No such file or directory
Current file position is 10226107
GPL Ghostscript 9.10: Unrecoverable error, exit code 1

Moreover, if I don't load the package pst-solides3d, LaTeX doesn't recognise the pst-solides3d macros, and I've got errors, and it doesn't compile either...
I don't know what to do, since the apart file compile, and when included in the main, it compile no more...
Is it an interaction with others packages ?
Here is the code PSTricks I use :
\documentclass[pstricks, float]{standalone}
\usepackage{pstricks, pst-circ, pst-plot, pst-3dplot, pst-solides3d}
\begin{document}

%\bgroup% holds everything local
\begin{pspicture}[showgrid=false](-1,-2)(9,6)
    \psset{unit=0.5, Alpha=45, Beta=15,
            viewpoint=60 45 15 rtp2xyz, Decran=120, lightsrc=viewpoint,
            linewidth=0.15pt,solidmemory}
    %%%%%%
    \defFunction{K}(t){t cos 2.5 mul}{t sin 2.5 mul}{}
    \psSolid[object=prisme,h=0.15,
        %fillcolor=yellow,
        RotX=-90,
        resolution=50,
        action=none,name=fond,
        base=90 270 {K} CourbeR2+](0,-0.15,2.5)
    \defFunction{F}(t){t cos 2.5 mul}{t sin 2.5 mul}{}
    \defFunction{G}(t){t cos 2.4 mul}{t sin 2.4 mul}{}
    \psSolid[object=prisme,
        h=8,%fillcolor=yellow,
        RotX=90,ngrid=1 0,
        resolution=50,
        base=90 270 {F} CourbeR2+
        270 90 {G} CourbeR2+,
        action=none,name=can](0,8,2.5)
    \psSolid[linewidth=0.15pt,
            object=cylindre,
            h=0.1,r=0.25,
            fillcolor=red!50,
            action=none,name=pas,
            mode=4,
            ngrid=1 20]
            (0, 2, -0.1)
    \psSolid[linewidth=0.15pt,
            object=cylindre,
            h=0.3,r=0.15,
            fillcolor=red!50,
            action=none,name=bout,
            mode=4,
            ngrid=1 20]
            (0, 2, -0.4)
    \psSolid[object=fusion,
            action=draw**, linewidth=0.2pt,
            base=can fond pas bout](0,0,0)
    %\composeSolid
        \psSolid[linewidth=0.15pt,
            object=cylindre,
            h=0.1,r=0.15,
            fillcolor=red!50,
            mode=4,
            action=none,name=filet,
            ngrid=1 20]
            (0, 2, 0)
    \psSolid[linewidth=0.15pt,
            object=cylindre,
            h=1.5625,r=0.05,
            fillcolor=green,
            mode=4,
            action=none,name=antenne,
            ngrid=1 10]
            (0, 2, 0.1)
    \psSolid[object=fusion,
            action=draw**, linewidth=0.2pt,
            base=filet antenne](0,0,0)
    \composeSolid

%   \axesIIID(4,9,6)
%   \pstThreeDCoor[xMin=0,xMax=4.5,yMin=0,yMax=9,zMin=0,zMax=6,IIIDticks]

    \psset{linewidth=0.05, linecolor=black,arrowsize=0.2}
    \pstThreeDLine{<->}(0, 0, 1.7)(0, 2, 1.7)
        \pstPlanePut[plane=yz,
            planecorr=normal](0, 2, 4.1){$\frac{L_g}{4}$}
    \pstThreeDLine{<->}(0, 2.7, 0.1)(0, 2.7, 1.6625)
        \pstPlanePut[plane=yz,
            planecorr=normal](0, 6, 1.6){\colorbox{white!10}{$\frac{L_o}{4}$}}
    \pstThreeDLine{<->}(0.5, 0, 0.1)(0.5, 0, 4.9)
        \pstPlanePut[plane=xz,
            planecorr=normal](2.2, 0, 4.4){$D$}
    \pstThreeDLine{<->}(0.5, 0, 0)(0.5, 8, 0)
        \pstPlanePut[plane=yz,
            planecorr=xyrot](0.5, 8, -1){$\frac{3}{4}L_g$}
    \end{pspicture}
%\egroup
\end{document}

And here's what I got when compiles separately :

A: Divide and Conquer (best practice)
Put each diagram in its separate compilable input file. For this, use standalone document class. Then compile the input file with latex->dvips->ps2pdf to get a PDF output.
% the filename of this code is diagram-1.tex

% compile this with the following 3 steps:
% latex diagram-1
% dvips diagram-1
% ps2pdf -dAutoRotatePages=/None diagram-1.ps
\documentclass[pstricks,border=12pt,12pt]{standalone}
\usepackage{pst-solides3d,pst-3dplot}
\begin{document}

%\bgroup% holds everything local
\begin{pspicture}[showgrid=false](-1,-2)(9,6)
    \psset{unit=0.5, Alpha=45, Beta=15,
            viewpoint=60 45 15 rtp2xyz, Decran=120, lightsrc=viewpoint,
            linewidth=0.15pt,solidmemory}
    %%%%%%
    \defFunction{K}(t){t cos 2.5 mul}{t sin 2.5 mul}{}
    \psSolid[object=prisme,h=0.15,
        %fillcolor=yellow,
        RotX=-90,
        resolution=50,
        action=none,name=fond,
        base=90 270 {K} CourbeR2+](0,-0.15,2.5)
    \defFunction{F}(t){t cos 2.5 mul}{t sin 2.5 mul}{}
    \defFunction{G}(t){t cos 2.4 mul}{t sin 2.4 mul}{}
    \psSolid[object=prisme,
        h=8,%fillcolor=yellow,
        RotX=90,ngrid=1 0,
        resolution=50,
        base=90 270 {F} CourbeR2+
        270 90 {G} CourbeR2+,
        action=none,name=can](0,8,2.5)
    \psSolid[linewidth=0.15pt,
            object=cylindre,
            h=0.1,r=0.25,
            fillcolor=red!50,
            action=none,name=pas,
            mode=4,
            ngrid=1 20]
            (0, 2, -0.1)
    \psSolid[linewidth=0.15pt,
            object=cylindre,
            h=0.3,r=0.15,
            fillcolor=red!50,
            action=none,name=bout,
            mode=4,
            ngrid=1 20]
            (0, 2, -0.4)
    \psSolid[object=fusion,
            action=draw**, linewidth=0.2pt,
            base=can fond pas bout](0,0,0)
    %\composeSolid
        \psSolid[linewidth=0.15pt,
            object=cylindre,
            h=0.1,r=0.15,
            fillcolor=red!50,
            mode=4,
            action=none,name=filet,
            ngrid=1 20]
            (0, 2, 0)
    \psSolid[linewidth=0.15pt,
            object=cylindre,
            h=1.5625,r=0.05,
            fillcolor=green,
            mode=4,
            action=none,name=antenne,
            ngrid=1 10]
            (0, 2, 0.1)
    \psSolid[object=fusion,
            action=draw**, linewidth=0.2pt,
            base=filet antenne](0,0,0)
    \composeSolid

%   \axesIIID(4,9,6)
%   \pstThreeDCoor[xMin=0,xMax=4.5,yMin=0,yMax=9,zMin=0,zMax=6,IIIDticks]

    \psset{linewidth=0.05, linecolor=black,arrowsize=0.2}
    \pstThreeDLine{<->}(0, 0, 1.7)(0, 2, 1.7)
        \pstPlanePut[plane=yz,
            planecorr=normal](0, 2, 4.1){$\frac{L_g}{4}$}
    \pstThreeDLine{<->}(0, 2.7, 0.1)(0, 2.7, 1.6625)
        \pstPlanePut[plane=yz,
            planecorr=normal](0, 6, 1.6){\colorbox{white!10}{$\frac{L_o}{4}$}}
    \pstThreeDLine{<->}(0.5, 0, 0.1)(0.5, 0, 4.9)
        \pstPlanePut[plane=xz,
            planecorr=normal](2.2, 0, 4.4){$D$}
    \pstThreeDLine{<->}(0.5, 0, 0)(0.5, 8, 0)
        \pstPlanePut[plane=yz,
            planecorr=xyrot](0.5, 8, -1){$\frac{3}{4}L_g$}
    \end{pspicture}
%\egroup
\end{document}

In case you have some setting that needs to be loaded in both diagram input files and the main input file, put those setting in a new package, namely mycommonsetting.sty, and save it in a folder that TeX system can find.
After all diagrams have been in PDF format, you now can import them from the main input file as follows
% the filename of this code is main.tex
% compile it with
% pdflatex main

\documentclass{article}
\usepackage{graphicx}
\graphicspath{{Images/}}
\begin{document}
\includegraphics{diagram-1}
\end{document}

I assume the folder Images contains all diagrams you want to import from within the main.tex which is saved in the same folder in which the folder Images exists. Confuse? Here is the tree structure of the files and folders.
\<any folder>\main.tex
\<any folder>\Images\diagram-1.tex

You will get a PDF output for your project after compiling the main with pdflatex main. Done.

A: When I use this document:

\documentclass[a4paper,11pt]{report}
\usepackage{ifxetex}
\usepackage{amsmath}
\ifxetex
  \usepackage{unicode-math}
  \setmathfont{XITS Math}
\else
  \usepackage[T1]{fontenc}
  \usepackage[utf8]{inputenc}
\fi
\usepackage{libertine}
\usepackage[french]{babel}

\usepackage{a4wide}
\usepackage[table,dvipsnames]{xcolor}
\NoAutoSpaceBeforeFDP % empêcher d'ajouter un espace après :
\usepackage{wrapfig}
\usepackage{caption}
\usepackage{fancyhdr}
\usepackage{fancyref}
\usepackage[locale = FR]{siunitx}
\usepackage[hyperindex, pdfborder={0 0 0}]{hyperref} % Table des matières & références interactive

\usepackage{pst-circ,pst-plot,pst-3dplot, pst-solides3d}
\begin{document}
...
... The PSTricks code
...
\end{document}

I have no problem to create the document with running xelatex <file> or with
latex->dvips->ps2pdf.

A: Solved, I was a GhostScript problem due to Adobe Illustrator...
I used it to transforms some pdf's into eps files, and it has brought some errors...
I converted them with pdf2ps (Terminal command), and it was solved...


text:
Q: Is input's parent node itself? I have a DOM object obj of the type <input>, and want to get is parent node, but obj.parentNode gives back the same obj.Is this a specification of <input> objects? If so, what other kinds of DOM objects behave irregularly (returns anything other than its parent in an intuitive sense) like this?
Edit I must have done something wrong. sorry.

A: input behaves no differently than any other element on a page, and returning its parentNode() should not return the input itself. Try it out:

<input type='text' id='my_id' onfocus="alert(this.parentNode.tagName)" />

This will alert "P".
I'm guessing that you're not correctly testing for the parentnode.


text:
Q: Prove that: $\int_a^bf(x)dx = 2\int_{a}^{a+b\over 2}f(x)dx$ for a symmetric continuous function.
Given a continuous function $f(x)$ defined on a range $x\in[a,b]$, such that the function has equal values in points symmetric to $x = {a+b\over 2}$, prove that:
  $$
\int_a^bf(x)dx = 2\int_{a}^{a+b\over 2}f(x)dx
$$

I've started by using the fundamental theorem of calculus, namely:
$$
\int_a^bf(x)dx = \int_a^{a+b\over 2}f(x)dx + \int_{a+b\over 2}^bf(x)dx = \\
F\left({a+b\over 2}\right) - F(a) +F(b) - F\left({a+b\over 2}\right)
$$
On the other hand:
$$
2\int_{a}^{a+b\over 2}f(x)dx = 2\left(F\left({a+b\over 2}\right)- F(a)\right) \\
= F\left({a+b\over 2}\right) - F(a) + F\left({a+b\over 2}\right) - F(a)
$$
Since the function is symmetric with respect to $x_0$ then:
$$
F(a) = F(b) \tag 1
$$
Thus:
$$
\begin{align}
I &= F\left({a+b\over 2}\right) - F(a) + F\left({a+b\over 2}\right) - F(b) \\
&= F\left({a+b\over 2}\right) - F(a) - \left(F(b) - F\left({a+b\over 2}\right)\right)\\
&=\int_a^{a+b\over 2}f(x)dx - \int_{a+b\over 2}^bf(x)dx \tag2
\end{align}
$$
Which is obviously nonsense. I believe the error is in $(1)$
So in case, the sign in $(2)$ is plus as opposed to minus then:
$$
\int_a^{a+b\over 2}f(x)dx + \int_{a+b\over 2}^bf(x)dx = \int_a^bf(x)dx
$$
Is the idea to prove the statement "correct in general"? Where did I make a mistake?

A: In the seconf integral, do the next C.V.
$t=a+b-x$: so that $dx=-dt$ and for $x=b$ $t=a$ and for $x=\frac{a+b}{2}$ $t=\frac{a+b}{2}$. So
$$\int_{\frac{a+b}{2}}^bf(x)dx = -\int_{\frac{a+b}{2}}^{a}f(a+b-t)dt = \int_a^{\frac{a+b}{2}}f\left(\frac{a+b}{2}+\underbrace{\left(\frac{a+b}{2}-t\right)}_{>0}\right)dt =
\int_a^{\frac{a+b}{2}}f\left(\frac{a+b}{2}-\left(\frac{a+b}{2}-t\right)\right)dt =\int_a^{\frac{a+b}{2}}f(t)dt
$$


text:
Q: Slider Bar/Pins algorithm I have a slider with x number of bars that each represent a range of values.  Each bar has an  upper and lower handle that is used to manipulate the range.  The bars can be interconnected, thus, some of the handles will affect two bars(i.e. the handle is in the middle of the two bars), of which, their movements can affect movements of other bars down the chain.  Bars can have a max width, and they can still be pushed/pulled while maintaining their max width.  My question is, is there a documented algorithm for validating a move where the user attempts to move a handle to value V, which will, in turn, either push or pull all of the connected bars down the chain?
This is a little hard to explain, so hopefully this made sense.  I'm not looking for an actual solution, just some algorithms that might help me come to a solution(i.e. the magic google search terms for this type of problem).  Thanks for your help.

A: Sounds like you're dealing with a special case of constraint programming. I think you could model your sliders as a series of constraints, i.e.:
slider1 range: (a,b) where a >= MIN, b <= MAX
slider2 range: (c,d) where c > a + x, d <= MAX
...
where x is changed when the user moves the bottom range of slider 2?
It would take time linear in the number of constraints to just evaluate all of the affected equations when the user moves a slider, which isn't too bad. I'm not sure you can do better than that.


text:
Q: Implementing Fuzzines in Autocomplete in ElasticSearch I have implemented elasticsearch autocomplete. This is the current query that I use (node.js - elasticsearcj.js):
body: {
            query: {
                match_phrase_prefix: {
                    schoolname: {
                        query: clientSearchterm,
                        slop: 10,
                        max_expansions: 50,
                         fuzzy : {
                            fuzziness : 2
                        }
                    }
                }
            }
        }

It works just fine. How do I implement Fuzziness parameter?

A: Simple. Just add this:
  "fuzzy" : {
            "fuzziness" : 2
          }


text:
Q: Cannot call JQuery functions Help!!! I can't get this Jquery code to run, the functions don't call, I've looked for numerous solutions and tried various different ways of solving this problem but yet I'm still stuck! Any suggestions would be much appreciated thanks! P.S Im certain indentation is correct, it appears weird in the snippet below and incorrect 0.o

$(document).ready(function(){
 $("#explore-drop-menu").mouseenter(function(){
  $(this).show_drop_menu("#explore-drop-menu");
 });

 $("#explore-drop-menu").mouseleave(function(){
  $(this).hide_drop_menu("#explore-drop-menu");
 });

 $.fn.show_drop_menu = function(drop_menu_id){
     $(drop_menu_id).css({
      "transition":"1s",`enter code here`
      "height":"300px",
      "opacity":"1"
     });

     $("#nav").css({
      "transition":"1s",
      "background-color":"#F0F0F0"
     });

     $("body").css({
      "transition":"1s",
      "background-color":"#404040"
     });
 });

 $.fn.hide_drop_menu = function(drop_menu_id){
     $(drop_menu_id).css({
      "transition":"1s",
      "height":"0px",
      "opacity":"0"
     });

     $("#nav").css({
      "transition":"1s",
      "background-color":"#212121"
     });

     $("body").css({
      "transition":"1s",
      "background-color":"white"
     });
 });
});


text:
Q: Mood - Modality-Modal Verbs These are excerpts from different grammar books.

*

*Modality is said to be implemented grammatically through these moods: indicative, imperative, subjunctive.

*Mood express modality by grammatical morphological means.

My question is: since modal verbs express modality, what type of mood do they belong to? Subjunctive? Why? why not?

A: Modern English, apart from a few vestiges, does not express mood by morphology: instead, it has a range of modals (such as will, can, must, should) each of which has its own range of meanings.
Some of them can be used to translate particular morphological constructions in other languages: but in my view nothing is gained by trying to put labels on the English constructions according to which modal (or none) is used.
"Subjunctive" is a case in point: in many European languages (including Old English) this refers to a particular morphological form of a verb - not to a construction. The old English subjunctive survives in a few places, notably in the irrealis conditional "If he were...".
Some people refer to some other constructions with modals such as would as "subjunctive", apparently because if they were translated into French or Latin they would be expressed by a subjunctive. I think this is obfuscatory and unhelpful.


text:
Q: Plotting contours of a function for different values of a parameter I want to draw a picture of $(x-t)^2 + (y-t^2)^2 - t^2$ in $xy$ plane, with different values of $t$. I did it in a very silly way , namely,
ContourPlot[{
  (x - 1)^2 + (y - 1)^2 == 1, (x - 2)^2 + (y - 4)^2 == 4,
  (x - 3)^2 + (y - 9)^2 == 9, (x - 4)^2 + (y - 16)^2 == 16,
  (x - 5)^2 + (y - 25)^2 == 25, (x - 6)^2 + (y - 36)^2 == 36,
  (x - 7)^2 + (y - 49)^2 == 49, (x - 8)^2 + (y - 64)^2 == 64,
  (x - 9)^2 + (y - 81)^2 == 81, (x - 10)^2 + (y - 100)^2 == 100,
  (x + 1)^2 + (y - 1)^2 == 1, (x + 2)^2 + (y - 4)^2 == 4,
  (x + 3)^2 + (y - 9)^2 == 9, (x + 4)^2 + (y - 16)^2 == 16,
  (x + 5)^2 + (y - 25)^2 == 25, (x + 6)^2 + (y - 36)^2 == 36,
  (x + 7)^2 + (y - 49)^2 == 49, (x + 8)^2 + (y - 64)^2 == 64,
  (x + 9)^2 + (y - 81)^2 == 81, (x + 10)^2 + (y - 100)^2 == 100
 },
 {x, -110, 110}, {y, -110, 110}
]

I am sure there must be a simpler way. Could you give me a hand?

A: Use Table to generate the values for different t:
ContourPlot[Evaluate@Table[(x - t)^2 + (y - t^2)^2 == t^2,
    {t, -20, 20, 1}], {x, -110, 110}, {y, -110, 110}]

A: You can generate all formulae:
f = Function[t, (x - t)^2 + (y - t^2)^2 == t^2];
ContourPlot[Evaluate[f /@ Range[10]], {x, -110, 110}, {y, -110, 110}]

or interactively stroll through them:
Manipulate[
 ContourPlot[(x - t)^2 + (y - t^2)^2 == t^2, {x, -110, 110}, {y, -110,
    110}], {t, 1, 10, 1}]


text:
Q: Spinner does not show b/c the bound variable is not updated I'm working on a Blazor server side app. The page has a table with a list of cars and some filter elements on top. When I select a filter, a spinner should be visible until the new data is fetched and rendered.
The spinner with its variable:

    Loading...

@code{
string spinner = "invisible";

    public string vehicleTypeFilter
    {
        set
        {
            _vehicleTypeFilter = value;
            ApplyFilters();
        }
        get { return _vehicleTypeFilter; }
    }
}

The select for the Baumuster (vehicleType) is bound to the vehicleTypeFilter variable:

        <select class="form-control" @bind="vehicleTypeFilter">
            <option value="" selected>Alle</option>
            @foreach (var vehicleType in vehicleTypes.OrderBy(x => x.Description))
            {
                <option value="@vehicleType.Description">@vehicleType.Description</option>
            }
        </select>
        Baumuster

Then a value is selected, the ApplyFilter method is triggered through the setter of the vehicleTypeFilter variable:
public void ApplyFilters()
{
        ToggleSpinner();
        // I also tried a StateHasChanged(); right here

        // 1. Get all cars
        cars = model.CreateIndexViewModel();

        // 2. Filter for Baumuster / vehicle type
        if (!string.IsNullOrEmpty(vehicleTypeFilter))
        {
            cars.viewModels = cars.viewModels.Where(x => x.VehicleDescription == vehicleTypeFilter).ToList();
        }

        ToggleSpinner();
}

The ToggleSpinner method:
public void ToggleSpinner()
    {
        if (spinner == "invisible" )
            spinner = "";
        else
            spinner = "invisible";
    }

Unfortunately, I don't see the spinner. When  I inspect the html page right after the breakpoint hits the Baumuster-filter, the value of spinner is still set to "invisible". I even tried to call StateHasChanged(); after the first ToggleSpinner() but that didn't help.

A: You've shown a lot of code, but I don't see ToggleSpinner
However, you call it twice in your ApplyFilters method, with no blocking calls, so I'd assume that it's turning the spinner on and off so fast that it doesn't render (or at least that you can't notice it).
If the methods you call in ApplyFilters actually take any time, then Henk's got the right idea-- except you should use async Task I think.

A: Your problem is that you want async behaviour from a synchronous property. The standard advice is against async void but if you want to stay with the property, the minimal change would be:
public async void ApplyFilters()
{
   ToggleSpinner();
   // I also tried a StateHasChanged(); right here
   StateHasChanged();   // this _requests_ an update
   await Task.Delay(1); // this is why you need async void

   ... as before

   ToggleSpinner();
   StateHasChanged();
}