text:
Q: How can I stop django REST framework to show all records if query parameter is wrong I am using Django REST Framework and i am using filters to filter the query set.
http://www.django-rest-framework.org/api-guide/filtering/#filtering-against-query-parameters
like this
http://example.com/api/products/4675/?category=clothing&max_price=10.00
But i have seen that if there is error in filters or the query parameters does not exist then it displays all results which is very bad.
I rather want no results if there is issue with query parameters because sometimes i don't know if that is working or not
EDIT
This is my code
class userFilter(django_filters.FilterSet):
    strict = True

    class Meta:
        model = User
        fields = ('is_active', 'is_archived', 'age')

REST
class UserListCreateView(generics.ListCreateAPIView):
    queryset = User.objects.filter(is_archived=False)
    ordering_fields = ('is_active')
    filter_class = userFilter

This is REST settings
REST_FRAMEWORK = {
    'DEFAULT_MODEL_SERIALIZER_CLASS':
        'rest_framework.serializers.HyperlinkedModelSerializer',
    'DEFAULT_PERMISSION_CLASSES': [
        'rest_framework.permissions.IsAuthenticated',
    ],
    'DEFAULT_FILTER_BACKENDS': (
        'rest_framework.filters.DjangoFilterBackend',
        'rest_framework.filters.SearchFilter',
        'rest_framework.filters.OrderingFilter',
    ),
    # 'PAGINATE_BY': 1,
    'PAGINATE_BY_PARAM': 'page_size',
    'MAX_PAGINATE_BY': 100,
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework.authentication.BasicAuthentication',
        'rest_framework.authentication.SessionAuthentication',
        'rest_framework.authentication.TokenAuthentication',
    )
}

A: If you are using the DjangoFilterBackend, take a look at the strict Non-Meta option.

The strict option controls whether results are returned when an
  invalid value is specified by the user for any filter field. By
  default, strict is set to True meaning that an empty queryset is
  returned if any field contains an invalid value. You can loosen this
  behavior by setting strict to False which will effectively ignore a
  filter field if its value is invalid.

The filter:
from django_filters.filterset import FilterSet

class UserFilter(FilterSet):
    strict = True

    class Meta:
        model = User
        fields = ['username']

The settings: (assumes you have installed django-filter)
REST_FRAMEWORK = {
    'DEFAULT_FILTER_BACKENDS': ('rest_framework.filters.DjangoFilterBackend',)
}

Now, if someone does:
http://api.example.com/users/?username=myuser&badfilter=1

...it will return an empty list, as badfilter does not exist.
As the FilterSet automatically defaults to strict=True, I have a feeling that you are not taking advantage of the DjangoFilterBackend.

A: The marked answer didn't work for me. I solved it by overriding the "get" method:
class UserListCreateView(generics.ListCreateAPIView):
    queryset = User.objects.filter(is_archived=False)
    ordering_fields = ('is_active')
    filter_class = userFilter

    @staticmethod
    def is_valid_query_params(query_params):
        # do validations here
        ...

    def get(self, request, *args, **kwargs):
        if not self.is_valid_query_params(request.query_params):
            return Response([])  # send empty response
        return super(UserListCreateView, self).get(request, *args, **kwargs)

A: Your specific issue arises from the fact that the parameters you invoke in your GET query are not defined in your UserFilter. Thus only the following parameters will be taken into account from DRF:
fields = ('is_active', 'is_archived', 'age')

Moreover strict only controls the value of a query parameter, not if the parameter itself exists. For example
GET mydomain.com/resource_path?whatever=blabla

returns the whole queryset which is something wrong in my opinion, at least not REST-compliant.
I ended up writing a small method to manually check if the query parameters passed in the request actually exist.

A: I did this by overloading the function get_queryset() in class which inherit generics.ListAPIView. You can check params with self.request.query_params , and write custom handler for any cases.

A: According to the author, strict only filters the values assigned to the query parameters, not the existence of the query parameters.
Otherwise things such as paging, which add its own query parameters, would break the API.
You can override get_queryset() to validate the query keys:
class List(generics.ListAPIView):

    queryset = MyModel.objects.all()
    serializer_class = MyModelSerializer
    filter_fields = ('q1', 'q2',)
    # or filter_class

    def get_queryset(self):
        paging = set(['limit', 'offset'])
        qs = super(RestrictedQueryMixin, self).get_queryset()
        # Optional mutual exclusion check below...
        if hasattr(self, 'filter_fields') and hasattr(self, 'filter_class'):
            raise RuntimeError("%s has both filter_fields and filter_class" % self)
        if hasattr(self, 'filter_class'):
            filter_class = getattr(self, 'filter_class', None)
            filters = set(filter_class.get_filters().keys())
        elif hasattr(self, 'filter_fields'):
            filters = set(getattr(self, 'filter_fields', []))
        else:
            filters = set()
        for key in self.request.GET.keys():
            if key in paging:
                continue
            if key not in filters:
                return qs.none()
        return qs

I made this into a mixin.
Alternatively, you could raise rest_framework.exceptions.APIException.  You can also alternatively get the  paginator fields dynamically from self.paginator.get_schema_fields(self)


text:
Q: KnockoutJS and multiple nested models I'm trying to find some tutorials on how to create a nested viewmodel with more than two levels, for example:

*

*Store

*
*

*Order

*
*

*
*

*Order row

*
*

*Order

*
*

*
*

*Order row

*
*

*
*

*Order row

*Store

*
*

*Order

*
*

*
*

*Order row

All the orders are listed for the stores and when I click on an order I should see the order rows with the ability to edit and delete order rows. I've got this working somehow by following a few tutorials but it got messed up and I'm looking to start over (in the end I start using jQuery to get what I want but it feels like cheating and doing something half-done). Are there any tutorials out there for this or any pointers on where I should start (KnockoutJS or other framework? Yes I've followed the tutorials on knockoutjs.com but get stuck on the functionality for the third level.
Thanks in advance.
Edit: by following this one  http://jsfiddle.net/peterf/8FMPc/light/
JS (simplified)
// required by sharepoint
ExecuteOrDelayUntilScriptLoaded(loadTeams, "sp.js");

ko.observable.fn.beginEdit = function (transaction) {
    var self = this;
    var commitSubscription, rollbackSubscription;

    if (self.slice) {
        self.editValue = ko.observableArray(self.slice());
    }
    else {
        self.editValue = ko.observable(self());
    }

    self.dispose = function () {
        commitSubscription.dispose();
        rollbackSubscription.dispose();
    };

    self.commit = function () {
        self(self.editValue());
        self.dispose();
    };

    self.rollback = function () {
        self.editValue(self());
        self.dispose();
    };

    commitSubscription = transaction.subscribe(self.commit, self, "commit");
    rollbackSubscription = transaction.subscribe(self.rollback, self, "rollback");

    return self;
}

 function TeamModel (){
    var self = this;
    self.Team = function(title, members) {
        this.title = title;
        this.members = members;
    }
    self.editingItem = ko.observable();
    self.editTransaction = new ko.subscribable();
    self.isItemEditing = function(task) {
        return task == self.editingItem();
    };

    self.editTask = function (task) {
        if (self.editingItem() == null) {
            task.beginEdit(self.editTransaction);
            self.editingItem(task);
        }
    };

    self.removeTask = function (task) {
        if (self.editingItem() == null) {
            var answer = confirm('Are you sure you want to delete this task? ' + task.title());
            if (answer) {
                // SharePoint client object model to delete task
            }
        }
    };

    self.applyTask = function (task) {
        self.editTransaction.notifySubscribers(null, "commit");
        // SharePoint client object model to update task
        //  hides the edit fields
        self.editingItem(null);
    };

    self.cancelEdit = function (task) {
        self.editTransaction.notifySubscribers(null, "rollback");
        self.editingItem(null);
    };

    self.Member = function(name, id) {
        this.name = name;
        this.Tasks = ko.observableArray([]);
        this.Task = function(id, title, priority, userComment, managerComment) {
            this.id = ko.observable(id);
            this.title = ko.observable(title);
            this.priority = ko.observable(priority);
            this.userComment = ko.observable(userComment);
            this.managerComment = ko.observable(managerComment);
            this.beginEdit = function(transaction) {
                //this.title.beginEdit(transaction);
                //this.userComment.beginEdit(transaction);
            }
        }
        this.id = id;
        this.retrieveTasks = function() {
            if(this.Tasks().length === 0) {
                // First click, expand
                // SharePoint client object model to get tasks
            } else {
                // Collapse
                //this.Tasks.removeAll();
            }
        }
    }
    self.Teams = ko.observableArray([]);
    self.retrieveTeams = function() {
            // SharePoint client object model to get a list of teams and their members
            self.Teams.push(new self.Team(oListItem.get_item('Title'), members));
    }
}

function loadTeams() {
    var VM = new TeamModel();
    VM.retrieveTeams();
    VM.availableRankings = ["1","2","3","4","5","6","7","8","9","10"]
    ko.applyBindings(VM);
}

HTML

0">

0">

                                Title
                                Priority
                                User Comment
                                Manager Comment

                                        <input type="text" class="edit" data-bind="value: title, visible: $root.isItemEditing($data)"/>

                                        <select class="edit priority" data-bind="options: $root.availableRankings, value: priority, visible: $root.isItemEditing($data)"></select>

                                        <textarea rows="3" cols="25" class="edit userComment" data-bind="value: userComment, visible: $root.isItemEditing($data)"></textarea>

                                        <textarea rows="3" cols="25" class="edit managerComment" data-bind="value: managerComment, visible: $root.isItemEditing($data)"></textarea>

                                        Edit
                                        <Sharepoint:SPSecurityTrimmedControl runat="server" Permissions="DeleteListItems">

                                        Remove
                                        </SharePoint:SPSecurityTrimmedControl>

                                        Apply

                                        Cancel

A: Databinding nested view models with multiple levels is just the same as databinding nested view models with a single level.
In the below examples, I'll use your example with Store -> Order -> OrderRow, assuming that each Store has a storeName property, each Order has an orderNumber and each OrderRow has a runningNumber. I've also rendered the items inside an ul on each level.
Without using templates
To databind nested view models a single level, the stores list in this example, could be done similar to:

        Store Name:

To databind nested view models a single level, from Store -> Order could be done similar to:
Store Name:

To databind nested view models a single level, from Order -> OrderRow could be done like:
Order number:

        A row with running number:

To do this nested in multiple levels, it's as simple as combining the above, moving the third code in to replace the contents of the li in the second and then the new second code to replace the li contents in the first.

        Store Name:

                Order number:

                    A row with running number:

I have basically the above code running (though buttons are added for adding new Store, Order and OrderRow objects) at http://jsfiddle.net/8yF6c/.
With templates
To make the code easier to maintain you could do it with templates instead. Of course, as always, the benefit might not be as clear with such a small example as this.
In the case with templates, the code will basically look pretty much like the first three cases in the above sample; before merging the html. First, the template for the store:

Then the template for the orders:

And finally the template for the order row.

Observe that the above three code parts are just the same as the first examples single level bindings, only wrapped in a script element with type text/html (to ensure that the browser doesn't try to execute it as script). Then we just need something at the root level to start using the storeTemplate.

And that's pretty much it. Just as before, I have the above code running (though buttons are added for adding new Store, Order and OrderRow objects) at http://jsfiddle.net/Ag8U3/.
Adding edit and delete functionality
Adding editing functionality to the above templates (or bindings without templates) is as simple as changing the span elements to input boxes (if you want other bindings to be aware of the change you will of course need to change some properties to be observables). If you want different 'modes', an edit mode and a view mode, you could look into dynamically choosing your template, which you can find examples of in the knockout documentation.
To add deletion functionality, just add a function which removes the items from the list when clicking the delete button (e.g. adding a deleteOrder function on the Store object could be self.removeOrder = function(order){ self.orders.remove(order); }; and then add a button to the order, like <button data-bind="click: $parent.removeOrder">Remove Order</button>. I've added delete functionality to the template sample at http://jsfiddle.net/Ag8U3/1/.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Infinitesimal generator : what is it exactly? Let $(X_t)$ an diffusion Itô process, i.e. a solution of $$dX_t=b(X_t)dt+\sigma (X_t)dB_t.$$ The infinitesimal generator of $(X_t)$ is $$Af(x)=\lim_{t\to 0^+}\frac{\mathbb E^x[f(X_t)]-f(x)}{t},$$
where $\mathbb E^x$ is the expectation wrt $\mathbb P^x$.
Q1) What represent exactly $Af(x)$ for $X_t$ ? For example, for a Brownian motion, if $f$ is $C^2$ then $$A f(x)=\frac{1}{2}\Delta f(x).$$
But I don't really understand which information does $A$ give is. Is it a sort of derivative of $X_t$ ?
Q2) What is exactely the measure $\mathbb P^x$ ? I know it is $\mathbb P^x\{X_t\in A\}=\mathbb P(\{X_t\in A\}\mid \{X_0=x\}),$ But does it mean that on $(\Omega ,\mathcal F,\mathbb P^x)$ we have that $\mathbb P\{X_0=x\}=1$ ? (i.e. is deterministic).

A: Q1) It seems that this link could help.
Q2) Also see this link for a formal definition of conditional probability. Even, the existence of regular conditional probabilities is a non-trivial fact even for simple cases like $\mathbb{R}^2$ equipped with Borel sigma algebra.


text:
Q: Cordova/Phonegap camera plugin - on Samsung devices still saving in photo roll / gallery even with the feature set to false I am using the camera plugin (currently using version 4.0.3) - and calling it as below:
navigator.camera.getPicture(appHandler.listPhoto, appHandler.photoFail, {
    quality: 80,
    saveToPhotoAlbum: false,
    PictureSourceType: Camera.PictureSourceType.CAMERA,
    destinationType: Camera.DestinationType.DATA_URL,
    encodingType: Camera.EncodingType.JPEG
});

With saveToPhotoAlbum to false. This all works fine on Android and iOS - apart from I am finding the image can sometimes still appear in the photo gallery for samsung devices (tested on several Samsung G8 handhelds). This hasn't been an issue for other android handsets or iOS versions of the mobile app.
I think I know what might be causing the problem though - The devices have Samsung Cloud setup and I believe it is backing up the image when the above call is made and duplicates it in the background for Cloud backup. Something I am guessing is beyond the control of Cordova plugin.
I think the original image data is still deleted as per the checkForDuplicateImage function within the plugin-camera code (I had a look around the plugin code to understand how it works) but the plugin creates the image file first regardless (so it can return the base64 data of the image as per the DATA_URL option above).
My theory is that the gallery app on the device is picking up the Samsung cloud version that it duplicated during this process  (e.g. the location details for the image still showing in the photo gallery was :/samsung cloud/DCIM/Camera/2018-0815_160311.jpg).
Question - has anyone else had this problem and can recommend a solution so the images do not save into the photo roll, gallery app on Samsung devices and Samsung cloud isn't effecting it. I have reported this also as a potential bug to https://issues.apache.org/jira/browse/CB-14269?filter=-2
Thank you!


text:
Q: How to get friend's mobile number using Facebook? How do I get the mobile number of a friend using the REST Api?
I have HTC Sense on my HTC Legend phone, and somehow they can grab the phone numbers from FB, as I got a list of contacts with mobile and birthday taken from FB. I am wondering how they did it?

A: The API won't give out mobile numbers - it's too much of a privacy/spam risk.


text:
Q: Linux: create list of text with multiple operators I want to make a list like this:
7785237_770x770_de3b540dc13ed50023d17854513b40aa07e50a6a
732308_770x770_ec5c344c0114011a5306b31142ff9b001813f6d6
7430796_800x800_ec0f2e614e2dc460fca7e626d83073c827dc9130
7431018_800x800_7caa40b85c21485c64f2ad509a0d9cc1ed3ba526

So to explain:
First block before the first "_" is just a number between 0 and 9500000 - second block varies between two variables: "770x770" and "800x800"
Last block is a 40 character long HEX block.
So what I want to do, is to generate all possible combinations of these, and combine it into one line.
How do I do this? Don't know if it can be done in BASH, or it should be done in perl/something similar.

A: I guess bash cannot handle those amounts and in case it could you'd get old before it sorts it out.
Python itertools can help you creating and assembling all combinations.
I suggest Python and not perl as this is more a math task rather than a text manipulation one.
#!/usr/bin/env python

from itertools import combinations_with_replacement

for x in combinations_with_replacement('0123456789abcdef', 40):
    h = ''.join(x)
    for y in xrange(9500001):
        for r in ("770x770", "800x800"):
            print "{0}_{1}_{2}".format(y, r, h)

Of course Python is way slower than C so don't expect best performances. On the other side don't expect to get the same result in C with only 5 lines of code.


text:
Q: pthread_join hangs indefinitely __lll_lock_wait_private() I have multithreaded application where I spawn a few threads and do a pthread_join upon completion.
The main thread spawns threads and waits on pthread_join() for the worker threads to join. I am facing a issue where the main thread is waiting indefinitely in pthread_join() and all the worker threads have exited, leading the program to hang.
I identified that all worker threads have exited by checking info thread on gdb since it lists only the main thread.
 Its is known that calling pthread_join() on a exited thread will return immediately. But this seems different. This is the gdb stack trace.
#0  0x00007f45fefebeec in __lll_lock_wait_private () from /lib64/libc.so.6
#1  0x00007f45fef68a6f in _L_lock_5333 () from /lib64/libc.so.6
#2  0x00007f45fef62408 in _int_free () from /lib64/libc.so.6
#3  0x00007f45ffbe5088 in _dl_deallocate_tls () from /lib64/ld-linux-x86-64.so.2
#4  0x00007f45ff9bde67 in __free_stacks () from /lib64/libpthread.so.0
#5  0x00007f45ff9bdf7f in __deallocate_stack () from /lib64/libpthread.so.0
#6  0x00007f45ff9bff93 in pthread_join () from /lib64/libpthread.so.0
#7  0x00007f45f87a6fe1 in waitForWorkerThreadsToExit () at src/server.c:133
#8  ServerLoop (arg=<optimized out>) at src/server.c:662
#9  0x00007f45ff9bee25 in start_thread () from /lib64/libpthread.so.0
#10 0x00007f45fefde34d in clone () from /lib64/libc.so.6

I am on CentOS7 and Linux kernel 3.10
Can someone help? TIA

A: One of the other threads is leaving without relinquishing the lock. As suggested here you can check the thread id for owner of this mutex to know which thread is the culprit.


text:
Q: How to create nested JSON response with Entity Framework Query I want to get a nested JSON reply with my EF query and not sure how to do this.
I have declared my Models as follows:
  [Serializable]
    public class StockReturnMethod
    {
        public int WarehouseID { get; set; }
        public int ProductSKUID { get; set; }
        public int LotID { get; set; }
        public string LotName { get; set; }
        public int AreaID { get; set; }
        public string AreaName { get; set; }
        public int BinID { get; set; }
        public string BinName { get; set; }
        public List<AvailibleStock> Stock { get; set; }
    }

  [Serializable]
    public class AvailibleStock
    {
        public int WarehouseID { get; set; }
        public int ProductSKUID { get; set; }
        public string ProductSKUName { get; set; }
        public string WarehouseName { get; set; }
        public string Status { get; set; }
        public int QtyUnassigned { get; set; }
    }

Here is my EF query that I have so far.
    {
       return (from WH in SCMENT.Warehouses
               join WL in SCMENT.WarehouseLots on WH.WarehouseID equals WL.WarehouseID
               join WA in SCMENT.WarehouseAreas on WL.WarehouseLotID equals WA.WarehouseLotID
               join WB in SCMENT.WarehouseBins on WA.WarehouseAreaID equals WB.WarehouseAreaID
               join SLI in SCMENT.StockLineItems on WH.WarehouseID equals SLI.WarehouseID
               join PSKU in SCMENT.ProductSKUs on SLI.ProductSKUID equals PSKU.ProductSKUID
               where SLI.SystemAreaID == 1

               select new StockReturnMethod()
               {
                WarehouseID = WH.WarehouseID,
                LotID = WL.WarehouseLotID,
                LotName = WL.WarehouseLotName,
                AreaID = WA.WarehouseAreaID,
                AreaName = WA.WarehouseAreaName,
                BinID = WB.WarehouseBinID,
                BinName = WB.WarehouseBinName,
                ProductSKUID = PSKU.ProductSKUID,
                Stock = (Will I create a sub query here?)

               }

    )

A: public List<AvailibleStock> Stock { get; set; }

Change this to:
public IList<AvailibleStock> Stock { get; set; }

Edit: Here's working sample from one of my projects that you can use as reference:
public class StatisticsModel
{
    public int Id { get; set; }
    public int ClientId { get; set; }
    public int Opened { get; set; }
    public IEnumerable<LocationsModel> Locations { get; set; }
}

public class LocationModel
{
    public int Id { get; set; }
    public string Name { get; set; }
    public int OpenCount { get; set; }
}

return dbSet.Select(x => new StatisticsModel
{
    Id = x.Id,
    ClientId = x.ClientId,
    Opened = x.OpenCount,
    Locations = x.Locations.Select(z => new LocationsModel{
        Id = z.Id,
        Name = z.Store.Name,
        OpenCount = z.OpenCount
    })
})


text:
Q: minsize() and maxsize() methods doesn't work in tkinter python(Toplevel) I was recently trying to make a pdf viewer in python, so I set the minsize() and maxsize() of the window but it doesn't seem to work. Here is my code.
from pdf2image import convert_from_path
import tkinter as tk
from tkinter import filedialog
from PIL import Image, ImageTk

root4=tk.Toplevel()
root4.geometry("800x900")
root4.title("PDF Viewer")
root4.configure(bg="#202020")
root4.minsize(300, 200)
root4.maxsize(900, 800)

pdf_frame = tk.Frame(root4)
pdf_frame.pack(fill=tk.BOTH,expand=1)

scrol_y = tk.Scrollbar(pdf_frame,orient=tk.VERTICAL)
pdf = tk.Text(pdf_frame,yscrollcommand=scrol_y.set,bg="grey")

scrol_y.pack(side=tk.RIGHT,fill=tk.Y)
scrol_y.config(command=pdf.yview)
pdf.pack(fill=tk.BOTH,expand=1)

pages = convert_from_path(filedialog.askopenfilename(initialdir = "/",title = "Select file",filetypes = (("pdf files","*.pdf"),("all files","*.*"))),size=(800,900))

photos = []

for i in range(len(pages)):
  photos.append(ImageTk.PhotoImage(pages[i]))

for photo in photos:
  pdf.image_create(tk.END,image=photo)
  pdf.insert(tk.END,'\n\n')

root4.update()
root4.mainloop()

A: When your creating a parent window use Tk(), else using Toplevel() will create a Tk()(for which the minsize and maxsize doesnt apply) window without you asking for it and you mightve misunderstood that for your root4 window, so just say:
tk.Tk().withdraw()
root4 = tk.Tk()

This fixed the issue of two windows popping up, for me. Keep in mind the minsize() and maxsize() works, its just that you were trying it on the wrong window.


text:
Q: Site appears very small (almost like a thumbnail) in iPhone Here is the site.
On iPhones, the site comes up very tiny.

The code I'm using in the header is <meta name="viewport" content="width=device-width, initial-scale=1">
What am I missing?


text:
Q: A step in proof of Burnside's Theorem I am reading the proof of Burnside's Theorem and it uses the following lemma in the online notes. page $70$ of - https://www.college-de-france.fr/media/jean-pierre-serre/UPL2937151343298039815_1___Groupes_finis.pdf.

Let $s \in G-\{1\}$ and $p$ be a prime. Let the cardinality of conjugacy class of $s$ be $c(s)=p^\alpha$, for some $\alpha$.
Then $\exists$ $N\lhd G $ and  $N\neq G$, such that,
If $ \phi : G\rightarrow G/N$ be the natural homomorphism, then $\phi (s) \in Z(G/N)$, where $Z(G/N)$ is the center of $G/N$.

Proof: Let $r_{G}$ be the character of regular representation of G.
Therefore $$r_{G}(s)=\sum \chi(1)\chi(s)=0$$ where the sum is over all the irreducible characters of G.
Now, $$1+\sum_{\chi \neq 1} \chi(1)\chi(s)=0$$
$\implies$
$$1/p+\sum_{\chi \neq 1} (\chi(1)\chi(s))/p=0$$
$\implies$
$$-1/p=\sum_{\chi \neq 1} (\chi(1)\chi(s))/p$$

$\implies$ $-1/p$ isn't algebraic integer .

How is the last step justified? How do we know that $-1/p$ isn't an algebraic integer?

A: As per the comment by @anon
If $f(−1/p)=0$, $f(−1/p)=0$ for some monic integer-coefficient polynomial $f$ of degree $n$ then multiplying by $p^n$ and reducing mod $p$ yields $(−1)^n≡0$ then,  $(−1)≡0$ or $1≡0$, a contradiction.


text:
Q: Django Admin Interface overlapping I have a standard Django admin site. The description overlap the input widget. How can i fix that? Is this a bug in Django or my fault?

A: Try to edit and increase the white spaces. You can the relevant CSS files in
"site-packages\django\contrib\admin\static\admin\css"

[UPDATE]:
You can just enhance it for this page only using  custom templates.
{% extends "admin/change_form.html" %}
{% block extrastyle %}
  {{ block.super }}
  <style type="text/css">

    .aligned label {
        display: block;
        padding: 3px 10px 0 0;
        float: left;
        width: 20em; /* updated */
    }
      </style>
{% endblock %}


text:
Q: Homomorphism between polynomial algebras $K$ is a field and $K[X_1,\dots, X_n]$ and $K[X_1,\dots, X_m]$ are polynomial algebras in $n$ and $m$ indeterminates respectively.

Suppose there is a $K$-algebra homomorphism $\phi:K[X_1,\dots, X_n] \to K[X_1,\dots, X_m]$. Prove that:
If $\phi$ is injective, $n\leq m$.
If $\phi$ is surjective, $n\geq m$.

My idea so far has been to try and exploit the vector space structure of polynomials but I haven't gotten anything concrete yet.
An idea for injectiveness: If $\phi$ is injective, then there exists a sub-algebra $A$ of $K[X_1, X_2,\dots, X_m]$ that is isomorphic to $K[X_1, X_2,\dots, X_n]$. $A$ can be in at most $m$ indeterminates because it is a subalgebra of an algebra generated by $m$ elements. This forces $n\leq m$. Does this work?

A: Let $\phi$ be a surjection from $K[X_1,\dots,X_n]$ to $K[X_1,\dots,X_m]$. Let $n<m$. Then there is a natural surjection $\psi$ with non-zero kernerl from $K[X_1,\dots,X_m]$ to $K[X_1,\dots,X_n]$. Composing the two, we get a surjective endomorphism of $K[X_1,\dots,X_m]$ that is not an injection. We know that $K[X_1,\dots,X_m]$ is Noetherian. Hence, surjective endomorphisms of $K[X_1,\dots,X_m]$ are automorphisms. Contradiction. Hence, $n\geq m$.
Let $\phi$ be an injection. We know that the polynomials of degree less than are equal to $r$ in $m$ variables form a vector space of dimension ${m+r}\choose{m}$. Let $d$ be the maximum degree of $\phi(X_i)$ for all $i$. Then the polynomials with degree less than or equal to $r$ map to a vector space of dimension ${n+rd}\choose{n}$. Because $\phi$ is injective, ${{m+r}\choose{m}}\leq {{n+rd}\choose{n}}$. Looking at this as an inequality of an $m$ dimensional and $n$ dimensional polynomials in $r$ and $rd$ respectively, we can conclude that $n\leq m$.


text:
Q: C# and Skype speech recognition I developed an application in C# that tries to recognize phrases in a pc-to-land phone call, using the Skype ActiveX and Microsoft's speech recognition engines, redirecting the call through a tcp/ip port.
In the phone, a machine plays a recording, so the voice is very clear. But neither System.Speech nor Microsoft.Speech can recognize anything usefull.
It has loaded the grammar with the expected choices, but nothing. If I speak, I have to say a word, wait until it recognizes the word, and then speak the next word, that way it works.
The question is, how can I improve this? or do you know an ASR that can do better on live conversations?

A: The most straightforward way is to use tools specifically designed for the task instead of hand-made solution of skype/activex.
There are special software to connect telephone calls to something actionable. Some of them:
Asterisk
Freeswitch
All such system provide speech recognition and interactive voice response functionality through the MRCP protocol. The easiest way to setup the recognition is to use CMUSphinx toolkit
You can read more about CMUSphinx integration into IVR systems here or here
If you prefer to start very quickly, there are cool SAAS solutions which let you build a telephony applications with a few clicks. For example Voxeo


text:
Q: Active Admin use current user attribute in scope I wanna define a scope that shows me my own mission (Doesn't matter what is a mission in this context)
What i tried is:
scope :my_mission do |missions|
  missions.where("mission.id = #{user.mission_id}")
end

Where mission_id is an User model attribute. user is the active logged in. This code has to live into the ActiveAdmin.register Mission file. Any idea on how to retrieve the user to perform the Query?

A: ActiveAdmin uses AdminUser model thus:
current_admin_user or current_active_admin_user == current_user

Your scope definition can be this way:
scope :my_mission do |missions|
  missions.where(admin_user_id == current_admin_user.id)
end

or in your case search for a single mission
scope :my_mission do |missions|
  Mission.find(current_admin_user.mission)
end

A: The active admin user is called
AdminUser

by default. The corresponding devise helper method is therefore
current_admin_user.

reference: How to get the current user that is logged in via active admin?


text:
Q: How to Format Output for Powershell Script I am new to Powershell and I have been trying to format this script to format output to be neat and left aligned. I have reviewed different websites and tutorials but I'm not sure I understand how to use the different switches and commands to make this happen.
    Hostname | Out-File -Filepath "\\some_path...\java_used.txt" -Append

    Test-Path C:\Users\%username%\AppData\LocalLow\Sun\Java\Deployment\deployment.properties | Out-File -Filepath "\\some_path...\java_used.txt" -Append

    Get-Item C:\Users\%username%\AppData\LocalLow\Sun\Java\Deployment\deployment.properties | Out-File -Filepath "\\some_path...\java_used.txt" -Append

    #powershell -noexit c:\Temp\JavaDateTimeUsers.ps1
    .\JavaDateTimeUsers.ps1 2>&1 | tee -filepath c:\Temp\results.txt

Below is an image of the output I currently have. I blanked out hostname and username. I don't want spaces, I want it to be left aligned, and I want the last line to have a line underneath to separate each entry, as this apends.

A: Just format the output as HTML. There u have any option to format your log with your needs.
Example:
echo <center> this is aligned to mid</center>|Out-File -Filepath "\\some_path...\java_used.html" -Append


text:
Q: Basic question on continuous time Markov chain For some reason I cannot find a worked example for reference, so any help in that direction (even just suggestions for a resource) is appreciated. Here is the question:
Let $X_t$ be a continuous time Markov chain and suppose $\{1,\dots,n\}$ is the finite state space of the process. Suppose that $X_0=1$ and let $Q$ be the rate matrix and $P$ the transition probability matrix. Is there an obvious way to compute $\mathcal{L}(X_t)$, the distribution law of $X_t$, in terms of $P$ and/or $Q$ as with discrete time Markov chains? Note that I am not interested in the limiting case of the stationary distribution here.
In the discrete time case, we have something like $P^k\mu_0 = \mu_k$ where $\mu_0$ is the distribution of $X_0$ and similarly $\mu_k$ for $X_k$.
Edit: I originally wrote $\mathbb{E}(X_t)$ instead of $\mathcal{L}(X_t)$, but answers in either direction are appreciated.

A: The continuous case is quite analogous; it is simply $\pi_0 e^{tQ}$ (I think it is customary to put the law on the left and the functions on the right by adjointness). That is because the diffusion has to solve Kolmogorov's forward-backward equations. ($P(t) = e^{tQ}$ is your transition matrix for time $t$, and it satisfies $\frac{\partial P(t)}{\partial t} = QP(t) = P(t)Q$). Durrett's Essentials of Stochastic Processes has a discussion of this in chapter 4 (and is available for free online).


text:
Q: xamarin.forms application not running on ios simulator I am working on Xamarin.Forms app and it's working perfectly fine on Android device. Anyway, when I am trying to run it on iPhone simulator it's just showing the main screen of the app, but none of the features are working.
The main screen consists of two parts of which one is to browse and open files and the other is to open a menu. The layout consists of Browse, process and exit buttons and when I click on the browse button to open file explorer an alert is displayed, that something went wrong.
I enabled breakpoints and tried debugging it, but the control is going to catch exception part directly.
Here is the code for it can anyone please help me with this part? I am using Xamarin.Plugin.Filepicker NuGet package. When I place the cursor on the Exception I can see that

System.NotImplemented Exception:This functionality is not implemented in the portable version of this assembly,you should reference the NuGet Package from your main application project in order to reference the platform specific

and the code is
   private Plugin.FilePicker.Abstractions.FileData file =
  default(Plugin.FilePicker.Abstractions.FileData);

    public async void OnBrowse(object o, EventArgs args)
    {
        try
        {
            //  var file_path =
            this.file = await CrossFilePicker.Current.PickFile();
            if (this.file == null)
            {
                return;
            }

            string extensionType = this.file.FileName.Substring(
                this.file.FileName.LastIndexOf(".",
     StringComparison.Ordinal) + 1,
                this.file.FileName.Length -
      this.file.FileName.LastIndexOf(".", StringComparison.Ordinal) -
      1).ToLower();

            fileName = this.file.FileName;

            if (extensionType.Equals("csv"))
            {
                csv_file.Text = (fileName);
            }
            else
            {
                await this.DisplayAlert("Name of the file:" + file.FileName, "File info", "OK");
            }

            if (SettingsPage.loggingEnabled)
            {
                LogUtilPage.Initialize("/storage/emulated/0");
            }
        }
        catch (Exception e)
        {
            await DisplayAlert("Alert", "Something went wrong", "OK");
            if (SettingsPage.loggingEnabled)
            {
                LogUtilPage.Log(e.Message);
            }
        }

    }


text:
Q: ¿Cómo unir 2 rows en un while?  while ($row2 =mysqli_fetch_array($results2)   )
    {

    echo "['".$row2["id_usuario"]."', ".$row2["number2"]."],    ";

    }

Quiero unir este row con un row3 que me traera otros datos de otra tabla ...
lo que quiero hacer es algo como
 while ($row2 =mysqli_fetch_array($results2) and ($row3 =mysqli_fetch_array($results3)   )
    {

    echo "['".$row2["id_usuario"]."', ".$row2["number2"]."],  ".$row3["color3"]."],   ";

    }

pero tengo errores

A: los puedes ir almacenando en un arreglo dentro de tu while
ejemplo:
 $rowunion=array();
        while (($row2 =mysqli_fetch_array($results2)) and ($row3 =mysqli_fetch_array($results3)   )
            {
             $rowunion[]=array("id_usuario"=>$row2["id_usuario"],"number2"=>$row2["number2"],"color3"=>$row3["color3"]);
            }
    print_r($rowunion);


text:
Q: What does babelRelayPlugin, transform-runtime, passPerPreset do? (babel+webpack configuration) I am new in Relay and I am looking at its' babel+webpack configuration and somehow I need help in understanding its' .babelrc - this is the code:
{
  "passPerPreset": true,
  "plugins": [
    "transform-runtime"
  ],
  "presets": [
    {
      "plugins": [
        "./build/babelRelayPlugin"
      ]
    },
    "react",
    "es2015",
    "stage-0"
  ]
}

This is the code on babelRelayplugin.js, this is short but I need help understanding this:
const getBabelRelayPlugin = require('babel-relay-plugin');
const schema = require('../data/schema.json');

module.exports = getBabelRelayPlugin(schema.data);

I understand   "react", "es2015", "stage-0" on presets, babel transform the code to js that browser understand.I have done my search and this is the information I have, which I don't understand and have confusion:

*

*babelRelayPlugin - Relay uses a babel plugin to convert from Relay.QL
string templates to JavaScript code that describes each query and
includes data from the GraphQL schema.

*passPerPreset:true -  will modify how babel traverses through
plugins. Instead of a single traversal in which all plugins/presets
are merged together, each preset will get their own traversal.(what does it mean?)

*"plugins": ["transform-runtime"] - all of the helpers will reference
the module babel-runtime to avoid duplication across your compiled
output. The runtime will be compiled into your build

Would really appreciate if someone help me understand what these are and what they do.

A: I recommend that you read this issue of Relay repository, and the links contained in it.


text:
Q: Display or set Text Diagonal way to textview will it be possible to display text in diagonal way if yes then how can we implement, please help me out for this thanks.
i have added image i have to replace WORLD text with other text.

A: Look here: How to Rotate TextView 90 Degrees and display.
The easiest way to do this is to:

*

*Create TextView with your background image.

*Rotate TextView as it is done in link above.

A: If you are using API 11 or later, you may try:
TextView tv = (TextView) findViewById(R.id.txtview);
String txt = "Stackoverflow";
tv.setText(txt);
tv.setRotation(45); // 45 degree rotation

Try this..

A: Use android:rotation in XML
or
textView.setRotation(angle)
http://developer.android.com/reference/android/view/View.html#attr_android:rotation

A: Guys i have implemented with custom textview thanks for your valuable response.working well on 4.0 device need to test it on 2.2 device.
    public class DiagonalTextView extends TextView{
   final boolean topDown;

   public DiagonalTextView(Context context, AttributeSet attrs){
      super(context, attrs);
      final int gravity = getGravity();
      if(Gravity.isVertical(gravity) && (gravity&Gravity.VERTICAL_GRAVITY_MASK) == Gravity.BOTTOM) {
         setGravity((gravity&Gravity.HORIZONTAL_GRAVITY_MASK) | Gravity.TOP);
         topDown = false;
      }else
         topDown = true;
   }

   @Override
   protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec){
      super.onMeasure(heightMeasureSpec, widthMeasureSpec);
      setMeasuredDimension(getMeasuredHeight(), getMeasuredWidth());
   }

   @Override
   protected boolean setFrame(int l, int t, int r, int b){
      return super.setFrame(l, t, l+(b-t), t+(r-l));
   }

   @Override
   public void draw(Canvas canvas){
      if(topDown){
         canvas.translate(getHeight(), 0);
         canvas.rotate(45);
      }else {
         canvas.translate(0, getWidth());
         canvas.rotate(-45);
      }
      canvas.clipRect(0, 0, getWidth(), getHeight(), android.graphics.Region.Op.REPLACE);
      super.draw(canvas);
   }
}


text:
Q: Not sure which property should I use for animation I am creating a kiosk app in Windows 8 but it will be used as assigned access app in 8.1. I want to create an animation for ads. The idea of animation is attached as image with this thread. Basically there will be 6-10 images in a L shape (Right side a column & bottom side a row). Now one ad in extreme bottom right corner will be stationary. The ads in column will travers like HTML's marquee and reaches to row at that time the ads in row will travers and reaches to column. In this way the ads will keep of moving in a clock wise pattern. How can I achieve this in my C#/XAML app?
Please not the ads will be never be displayed on top or left. The ad is <Image /> & source is Internet URLs. All ads are in ItemsControl.

A: Yuck, let's start with how much I hate this app already.
Now to the answer.
I don't think you really need an animation. You will likely change the ads only every so often. And a simple change in their position and NOT a transition in their position seems adequate.
Try this:
<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
    <Grid.ColumnDefinitions>
        <ColumnDefinition />
        <ColumnDefinition />
        <ColumnDefinition />
        <ColumnDefinition />
    </Grid.ColumnDefinitions>
    <Grid.RowDefinitions>
        <RowDefinition />
        <RowDefinition />
        <RowDefinition />
        <RowDefinition />
    </Grid.RowDefinitions>
    <Rectangle Fill="White" Grid.Column="0" Grid.ColumnSpan="3" Grid.Row="0" Grid.RowSpan="3" />
    <Rectangle x:Name="Ad1" Fill="Green" Grid.Column="3" Grid.Row="3" />
    <Rectangle x:Name="Ad2" Fill="IndianRed" Grid.Column="0" Grid.Row="3" />
    <Rectangle x:Name="Ad3" Fill="Red" Grid.Column="1" Grid.Row="3" />
    <Rectangle x:Name="Ad4" Fill="DarkRed" Grid.Column="2" Grid.Row="3" />
    <Rectangle x:Name="Ad5" Fill="Pink" Grid.Column="3" Grid.Row="0" />
    <Rectangle x:Name="Ad6" Fill="HotPink" Grid.Column="3" Grid.Row="1" />
    <Rectangle x:Name="Ad7" Fill="Purple" Grid.Column="3" Grid.Row="2" />
</Grid>

With this:
public MainPage()
{
    this.InitializeComponent();
    var timer = new DispatcherTimer { Interval = TimeSpan.FromSeconds(1) };
    timer.Tick += (s, e) => Move();
    timer.Start();
}

void Move()
{
    var ads = new Rectangle[] { Ad1, Ad2, Ad3, Ad4, Ad5, Ad6, Ad7 };
    foreach (var item in ads)
    {
        var row = (int)item.GetValue(Grid.RowProperty);
        var col = (int)item.GetValue(Grid.ColumnProperty);
        if (row == 3)
        {
            if (col == 0)
            {
                row = 0;
                col = 3;
            }
            else
                col--;
        }
        else
        {
            if (row == 2)
            {
                row = 3;
                col = 2;
            }
            else
                row++;
        }
        item.SetValue(Grid.RowProperty, row);
        item.SetValue(Grid.ColumnProperty, col);
    }
}

And it looks pretty good to me.
But if you must have animations, try this.
void Move()
{
    var ads = new Rectangle[] { Ad1, Ad2, Ad3, Ad4, Ad5, Ad6, Ad7 };
    foreach (var item in ads)
    {
        var row = (int)item.GetValue(Grid.RowProperty);
        var col = (int)item.GetValue(Grid.ColumnProperty);
        var x = item.ActualWidth;
        var y = item.ActualHeight;

        // bottom
        if (row == 3)
        {
            // left-last
            if (col == 0)
            {
                row = 0;
                col = 3;
                x = -x;
                y = 0;
            }
            // others
            else
            {
                col--;
                x = -x;
                y = 0;
            }
        }
       // right
       else
        {
           // bottom-last
           if (row == 2)
            {
                row = 3;
                col = 2;
                x = -x;
            }
            else
            {
                row++;
                x = 0;
            }
        }

        var dr = new Duration(TimeSpan.FromSeconds(.5));
        var tx = item.RenderTransform = new TranslateTransform();

        var ax = new DoubleAnimation { To = x, Duration = dr };
        Storyboard.SetTarget(ax, tx);
        Storyboard.SetTargetProperty(ax, "X");

        var ay = new DoubleAnimation { To = y, Duration = dr };
        Storyboard.SetTarget(ay, tx);
        Storyboard.SetTargetProperty(ay, "Y");

        var st = new Storyboard { FillBehavior = FillBehavior.HoldEnd };
        st.Children.Add(ax);
        st.Children.Add(ay);
        st.Completed += (s, e) =>
        {
            item.SetValue(Grid.RowProperty, row);
            item.SetValue(Grid.ColumnProperty, col);
            st.Stop();
        };
        st.Begin();
    }
}

Best of luck!


text:
Q: How can I insert a photo into a MySQL database with PHP using Swift iOS I'm trying to insert a photo into a database using a php file with swift but I could only add the photo to a file under htdocs 'uploads' but I can't add the path to database.
Can someone tell me how to add a photo with parameters to database with swift knowing that I have used this tutorial:
http://swiftdeveloperblog.com/image-upload-example/
Here is my code:
Swift
  //  UploadViewController.swift

    import UIKit
     class UploadViewController: UIViewController,UIImagePickerControllerDelegate,UINavigationControllerDelegate
    {
     @IBOutlet weak var myActivityIndicator: UIActivityIndicatorView!
     @IBOutlet weak var myImageView: UIImageView!
     @IBAction func uploadButtonTapped(sender: AnyObject) {

            //my Image upload

             myImageUploadRequest()
     }
     override func viewDidLoad() {

            super.viewDidLoad()

            let defaults = NSUserDefaults.standardUserDefaults();

            print("fffffff" + defaults.stringForKey("abc")!)
               // Do any additional setup after loading the view.

        }
     override func didReceiveMemoryWarning() {

            super.didReceiveMemoryWarning()

            // Dispose of any resources that can be recreated.

        }
     @IBAction func selectPhotoButtonTapped(sender: AnyObject) {

              var myPickerController = UIImagePickerController()

            myPickerController.delegate = self;

            myPickerController.sourceType = UIImagePickerControllerSourceType.PhotoLibrary

 self.presentViewController(myPickerController, animated: true, completion: nil)

        }
     func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject])
    {

            myImageView.image = info[UIImagePickerControllerOriginalImage] as? UIImage

            self.dismissViewControllerAnimated(true, completion: nil)
     }
       func myImageUploadRequest()

        {
   let myUrl = NSURL(string: "http://localhost:8888/Swift/my-http-post-example.php");

            //let myUrl = NSURL(string: "http://www.boredwear.com/utils/postImage.php");
            let request = NSMutableURLRequest(URL:myUrl!);

            request.HTTPMethod = "POST";

            let param = [

                "firstName"  : "Sergey",

                "lastName"    : "Kargopolov",

                "userId"    : "9"

            ]

            let boundary = generateBoundaryString()

            request.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")

            let imageData = UIImageJPEGRepresentation(myImageView.image!, 1)

            if(imageData==nil)  { return; }

            request.HTTPBody = createBodyWithParameters(param, filePathKey: "file", imageDataKey: imageData!, boundary: boundary)

            myActivityIndicator.startAnimating();

            let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {

                data, response, error in

                if error != nil {

                    print("error=\(error)")

                    return

                }

                // You can print out response object

                print("******* response = \(response)")

                // Print out reponse body

                let responseString = NSString(data: data!, encoding: NSUTF8StringEncoding)

                print("****** response data = \(responseString!)")

                var err: NSError?

                do {

                var json = try NSJSONSerialization.JSONObjectWithData(data!, options: .MutableContainers) as? NSDictionary

                dispatch_async(dispatch_get_main_queue(),{

                    self.myActivityIndicator.stopAnimating()

                    self.myImageView.image = nil;

                });
            }

                catch let error as NSError {

                    print("An error occurred: \(error)")

                }

            }

            task.resume()

        }
        func createBodyWithParameters(parameters: [String: String]?, filePathKey: String?, imageDataKey: NSData, boundary: String) -> NSData {

            var body = NSMutableData();

            if parameters != nil {

                for (key, value) in parameters! {

                    body.appendString("--\(boundary)\r\n")

                    body.appendString("Content-Disposition: form-data; name=\"\(key)\"\r\n\r\n")

                    body.appendString("\(value)\r\n")

                }

            }

            // defaults.setValue(String("0"), forKey: "abc")

            let defaults = NSUserDefaults.standardUserDefaults()

            if ((defaults.stringForKey("abc")!) == ""){

                defaults.setValue(String("0"), forKey: "abc")

            }

            let filename =  (defaults.stringForKey("abc")!)+".jpg"

            defaults.setValue(String(Int((defaults.stringForKey("abc")!))!+1), forKey: "abc")

           // let defaults = NSUserDefaults.standardUserDefaults();

            //let filename = "user-profile.jpg"

            let mimetype = "image/jpg"

            body.appendString("--\(boundary)\r\n")

            body.appendString("Content-Disposition: form-data; name=\"\(filePathKey!)\"; filename=\"\(filename)\"\r\n")

            body.appendString("Content-Type: \(mimetype)\r\n\r\n")

            body.appendData(imageDataKey)

            body.appendString("\r\n")

            body.appendString("--\(boundary)--\r\n")

            return body

        }

        func generateBoundaryString() -> String {

            return "Boundary-\(NSUUID().UUIDString)"

        }

    }

    extension NSMutableData {

        func appendString(string: String) {

            let data = string.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)

            appendData(data!)

        }

    }

Here the PHP file in which I couldn't insert the photo in data
<?php

$firstName = $_POST["firstName"];

$lastName = $_POST["lastName"];

$userId = $_POST["userId"];

$target_dir = "uploads/";if(!file_exists($target_dir))

{

mkdir($target_dir, 0777, true);

}

$target_dir = $target_dir . "/" . basename($_FILES["file"]["name"]);

if (move_uploaded_file($_FILES["file"]["tmp_name"], $target_dir))

{

echo json_encode([

"Message" => "The file ". basename( $_FILES["file"]["name"]). " has been uploaded.",

"Status" => "OK",

"userId" => $_REQUEST["userId"]

]);

} else {

echo json_encode([

"Message" => "Sorry, there was an error uploading your file.",

"Status" => "Error",

"userId" => $_REQUEST["userId"]

]);

}

?>


text:
Q: Poetry already added module, but not installed My pyproject.toml is something like this
[tool.poetry.dependencies]
python = "^3.8"
numpy = "^1.19.4"
pandas = "^1.1.5"
matplotlib = "^3.3.3"
seaborn = "^0.11.0"
lightgbm = "^3.1.1"
jupyter = "^1.0.0"
notebook = "^6.1.5"
.
.
.
[build-system]
requires = ["poetry-core>=1.0.0"]
build-backend = "poetry.core.masonry.api"

After poetry install and open python, I found I could import some module(numpy and pandas), but not others like seaborn, lightgbm and etc..
Anyone knows how to fix this problem?
I got same situation, so I manually deleted .venv and poetry.lock. Then I re-added modules by poetry install. But it didn't go well...
$ poetry run python
Python 3.9.1 (default, Dec 10 2020, 10:36:35)
[Clang 12.0.0 (clang-1200.0.32.27)] on darwin
Type "help", "copyright", "credits" or "license" for more information.

>>> import numpy
>>> import pandas

>>> import seaborn
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ModuleNotFoundError: No module named 'seaborn'

>>> import lightgbm
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ModuleNotFoundError: No module named 'lightgbm'

I guess llvmlite is a main cause of this problem, so I'll work on looking around for solution. But if you already know about it, please share.
$ poetry cache clear pypi --all
$ rm -r .venv
$ rm poetry.lock
$ poetry install

### a lot of process goes on

  • Installing colorama (0.4.4): Installing...
  • Installing llvmlite (0.35.0rc3): Failed
  • Installing llvmlite (0.35.0rc3): Failed
  • Installing colorama (0.4.4)
  • Installing llvmlite (0.35.0rc3): Failed
  RuntimeError
  Unable to find installation candidates for llvmlite (0.35.0rc3)
  at /usr/local/Cellar/poetry/1.1.4/libexec/lib/python3.9/site-packages/poetry/installation/chooser.py:72 in choose_for
       68│
       69│             links.append(link)
       70│
       71│         if not links:
    →  72│             raise RuntimeError(
       73│                 "Unable to find installation candidates for {}".format(package)
       74│             )
       75│
       76│         # Get the best link

Followings are possible clues to solve
poetry replies it is already installed.
$ poetry add seaborn
The following packages are already present in the pyproject.toml and will be skipped:

  • seaborn

If you want to update it to the latest compatible version, you can use `poetry update package`.
If you prefer to upgrade it to the latest available version, you can use `poetry add package@latest`.

Nothing to add.

$ poetry run which python

/Users/<user>/.venv/bin/python

$ poetry env info

Virtualenv
Python:         3.9.1
Implementation: CPython
Path:           /Users/<user>/.venv
Valid:          True

System
Platform: darwin
OS:       posix
Python:   /usr/local/Cellar/python@3.9/3.9.1/Frameworks/Python.framework/Versions/3.9

$ poetry -V

Poetry version 1.1.4

A: I fixed this problem. This problem is just about failure of installing llvmlite, rather than poetry. llvmlite is pre-requisite for installing pandas-profiling I was trying to install.
Rule of thumb when it comes to finding dependence problem

*

*removing current environment

$ poetry cache list
# after finding out what cache exists
$ poetry cache clear <cache name> --all
$ rm -r .venv
$ rm poetry.lock

*Take a note or copy of what modules you have installed

$ cat pyproject.toml
# take a note or copy of what modules you have installed

$ rm pyproject.toml

*re-initialize environment and adding modules incrementally

$ poetry init
# not adding modules except ones you are sure not to cause problem

$ poetry add <module>

*Identifying what is actually problem

A: For me, I had a super-specific case, but it happened basically because direnv tool applied a different venv beforehand which mixed up everything.


text:
Q: Why is React redirect not working for me? I have a starter screen with two buttons which are login and register. Here is the code for the same:
import React from 'react';
import Header from './Header.jsx';
import Authentication from './AuthenticateCard.jsx';
import { Redirect } from 'react-router-dom';
function StarterScreen() {
  function loginClick()
    {
      return(<Redirect to= "/login" />);
      alert("Tru");
    }
    function registerClick()
    {
      console.log("Register");
    }
  return (

      <Authentication text="Login" onClickaction={loginClick} />
      <Authentication text="Register" onClickaction={registerClick}/>

  );
}

export default StarterScreen;

Here is my main app.js file:
import React from 'react';
import StarterScreen from './components/StarterScreen.jsx';
import LoginScreen from './components/LoginScreen.jsx';
import RegisterScreen from './components/RegisterScreen.jsx';
import 'bootstrap/dist/css/bootstrap.min.css';
import './App.css';
import {BrowserRouter,Route,Switch} from 'react-router-dom';
function App() {
  function loginClick()
    {
      console.log("Login");
    }
    function registerClick()
    {
      console.log("Register");
    }
  return (

    <BrowserRouter>
    <Switch>
    <Route component={StarterScreen} exact path="/"></Route>
    <Route component={LoginScreen} exact path="/register"></Route>
    <Route component={StarterScreen} exact path="/login"></Route>
    </Switch>
    </BrowserRouter>

  );
}

export default App;

when I click on login it just freezes and nothing happens afterwards. Screen does respond but no login action takes place with a bunch of errors:

A: Try:
import React from 'react';
import Header from './Header.jsx';
import Authentication from './AuthenticateCard.jsx';
import { withRouter } from 'react-router-dom';

function StarterScreen(props) {
  function loginClick()
    {
      props.history.push('/login');
    }
    function registerClick()
    {
      console.log("Register");
    }
  return (

      <Authentication text="Login" onClickaction={loginClick} />
      <Authentication text="Register" onClickaction={registerClick}/>

  );
}

export default withRouter(StarterScreen);

Note here, I added withRouter to wrap your component and imported it from react-router-dom. Then I'm using props.history.push to navigate

A: You should not return a Redirect within event handler in StarterScreen, you can take advantage of the withRoutes high oder component or using useHistory hook to have access to the history of the navigator and change the route by calling push with the route where you want to navigate to.
import { withRouter } from 'react-router-dom';

const StarterScreen = ({history}) => {
    const loginClick = () => {
        history.push("/login");
    }
    return

            <Authentication text="Login" onClickaction={loginClick} />
            <Authentication text="Register" onClickaction={registerClick}/>

;
}

export default withRouter(StarterScreen);

The withRouter high order component will pass 3 properties to you component has props match, location and history.
You can learn more here withRouter

A: Here is my way to redirect, i created a file call redirect.tsx, and then you can call from other file:
import { useHistory, withRouter } from "react-router-dom";

const Redirect = (props: any) => {
    const to = (props.to || '/');
    let history = useHistory();
        history.push(to);
        window.location.reload();
    return (
      <>
      </>
     )
   }
export default withRouter(Redirect);

Without window.location.reload(); browser still redirect but it can not show anything!
Good day!


text:
Q: How do I get an Intel alc 880 analog sound card working on an Asus A6V? I have an Asus A6V with Ubuntu 11.10 (32 bit). I don't find the drivers installed for Hda intel ALC 880 Analog and Digital. When I go into System Settings  and click on Sound (in the Hardware category), I should be able to select and enable the USB headphones/speakers in te Output tab. But I can't do that. There isn't any drivers installed.
What I should ?
Bye-bye


text:
Q: How to fix ARIMA MODEL bugs in Python I'm trying to create an ARIMA Model for my time series data. What can i do to my code for it to run smoothly?
I'm using statsmodels to create the ARIMA model in python but i'm getting error warnings
    indexedDataset_logscale.head(10)
    OUTPUT:
                Price
    Period
    2013-02-08  2.515274
    2013-02-11  2.526528
    2013-02-12  2.520113
    2013-02-13  2.515274
    2013-02-14  2.543961
    2013-02-15  2.544040
    2013-02-19  2.530119
    2013-02-20  2.516082
    2013-02-21  2.508786
    2013-02-22  2.5273

    #AR Model
    from statsmodels.tsa.arima_model import ARIMA

    model = ARIMA(indexedDataset_logscale, order=(0, 1, 2))
    results_AR = model.fit(disp = -1)
    plt.plot(datasetLogDiffShifting)
    plt.plot(results_AR.fittedvalues, color = 'red')
    plt.title('RSS: %.4f' %sum((results_AR.fittedvalues-datasetLogDiffShifting['Price'])**2))
    print('Plotting AR Model')

Error messages i get are:

*

*
"ValueWarning: A date index has been provided, but it has no associated frequency information and so will be ignored when e.g.
  forecasting. ignored when e.g. forecasting.', ValueWarning)

*
8 plt.title('RSS: %.4f' %sum((results_AR.fittedvalues-datasetLogDiffShifting['Price'])**2))
  TypeError: 'str' object is not callable

A: 1) It seems your index doesn't have set frequency
Try adding this befor Arima
df.index.freq = 'D'

D is for daily timestamp, it seems your is not linear/regular, hard to define looking at what's in the question. Check other frequency option in pandas.
To avoid warnings type this at the beginning of the script:
#Clear console
import warnings
warnings.filterwarnings("ignore")

A: The problem is that in your data, the index seems to be daily, but some dates are not consecutive days. You can supply missing dates and then interpolate values for these dates, as follows:
df = df.resample('D').mean()
df["Price"] = df["Price"].interpolate(method='linear', axis=0).ffill().bfill()

You will then be able to build a model and plot the fitted values.


text:
Q: How to resize WPF DataGrid to fit its content? The aim
I would like to set such size for the DataGrid (standard, from WPF) so all cells (text) would be fully visible. I have window with DockPanel, with DataGrid in it, so when I resize the window, all nested widgets (DockPanel and DataGrid) are resized accordingly.
Example (edit-1)
Let's say you have window, 100 pixels wide and you have DataGrid with one column, which cell is "the quick brown fox..." (400 pixels wide). Thus the DataGrid should be resized to 400 pixels (probably more, because of padding) and the Window should be resized to 400 pixels too (also more, because of padding).
I didn't find any standard method to do it (AFAIK WPF provides way to clip the content to desired width, my problem is exactly opposite), so I come up with such ugly workaround, which does not work too well.
The workaround

*

*iterate over DataGrid headers (assuming they are just strings) and compute width required for the text

*iterate over DataGrid rows per each column (assuming they are TextBlock or TextBox) and compute the maximum width required for the text -- add horizontal paddings for TextBlock/TextBox and horizontal margins for DataGrid cell

*sum all differences between DataGrid ActualWidth for columns and the maximum width computed in (2)

*increase the window width by the difference computed in (3)

THE PROBLEM
I did several tests, and in some cases the computed width is too big (this is minor problem), for some cases is too small. The problem starts at its core procedure -- computing the required width for TextBox/TextBlock, computed width is always 1 unit less than it should be (if I set the width to computed one, 1 pixel from text is always clipped).
So which factor I am ignoring here? Or maybe better -- is there already some method to resize DataGrid to fit its content?
The code
Computing width required for text (here for TextBlock):
    public static double TextWidth(this TextBlock widget, string text)
    {
        var formattedText = new FormattedText(text, // can use arbitrary text
                                              System.Globalization.CultureInfo.CurrentCulture,
                                              widget.FlowDirection,
                                              widget.FontFamily.GetTypefaces().FirstOrDefault(),
                                              widget.FontSize,
                                              widget.Foreground);

        return formattedText.Width+widget.Padding.Left+widget.Padding.Right;
    }

Adjusting the Window size to fit DataGrid content (ugly_factor is ugly workaround ;-) since I didn't figure out how to fix it properly I set it to 1.3 and this way my window is "never" too small):
    public static void AdjustWidthToDataGrid(this Window window, DataGrid dataGrid, double ugly_factor)
    {
        var max_widths = dataGrid.Columns.Select(it => window.TextWidth(it.Header as string)
                                                                        * ugly_factor).ToArray();

        foreach (var row in Enumerable.Range(0, dataGrid.Items.Count))
            foreach (var col in Enumerable.Range(0, dataGrid.Columns.Count))
            {
                var cell = dataGrid.GetCell(row, col);
                double width = 0;
                if (cell.Content is TextBlock)
                    width = (cell.Content as TextBlock).TextWidth();
                else if (cell.Content is TextBox)
                    width = (cell.Content as TextBox).TextWidth();

                if (cell.Content is FrameworkElement)
                {
                    var widget = cell.Content as FrameworkElement;
                    width = width + widget.Margin.Left + widget.Margin.Right;
                }

                max_widths[col] = Math.Max(max_widths[col],
                                           width*ugly_factor+cell.Padding.Left+cell.Padding.Right);
            }

        double width_diff = 0;

        foreach (var col in Enumerable.Range(0, dataGrid.Columns.Count))
            width_diff += Math.Max(0,max_widths[col] - dataGrid.Columns[col].ActualWidth);

        if (width_diff > 0)
            window.Width = window.ActualWidth+ width_diff;
    }

A: In my case, I found DataGrid use HorizontalAlignment="Stretch" VerticalAlignment="Stretch"  in default, So I set it to
<DataGrid ItemsSource="{Binding Source}" Width="Auto" Height="Auto"
          HorizontalAlignment="Center" VerticalAlignment="Center"/>

Then works.

A: I just came out of the same problem where I had to give options in a data grid's column to fit its width as per the content of both header and cell. I used the following code:
private void FitToContent()
    {
        // where dg is my data grid's name...
        foreach (DataGridColumn column in dg.Columns)
        {
            //if you want to size your column as per the cell content
            column.Width = new DataGridLength(1.0, DataGridLengthUnitType.SizeToCells);
            //if you want to size your column as per the column header
            column.Width = new DataGridLength(1.0, DataGridLengthUnitType.SizeToHeader);
            //if you want to size your column as per both header and cell content
            column.Width = new DataGridLength(1.0, DataGridLengthUnitType.Auto);
        }
    }

Also I provided an option on columns to fit as per the display (datagrid's width). for that I used the same code above with the following minor change:
column.Width = new DataGridLength(1.0, DataGridLengthUnitType.Star);
FOR ALL COLUMNS : Make sure you keep HorizontalScrollVisibility to Auto.

A: Marko's comment is the answer:

I'm at a bit of a loss with your resizing logic. First of all, if you set the window's SizeToContent="WidthAndHeight", then the window is shown to the full size of the datagrid. On the other hand, if you show a window at some predefined size, and you want to resize the window once the window is shown, then at that point resizing to the datagrid's desired with is very counter intuitive. Because the resizing will jump from say 100px to 400px, but what if I want to resize to only 250px... (asuming you resize by dragging the corner of the window)

A: If I understood your question right and you want to:

*

*A DataGrid where columns are as wide as it's widest content.

*The DataGrid fits to its contents.

This can be achieved with databinding:
<DataGrid AutoGenerateColumns="False"
          EnableRowVirtualization="True"
          Height="111"
          HorizontalAlignment="Left"
          ItemsSource="{Binding}"
          Margin="72,203,0,0"
          Name="dataGrid"
          RowDetailsVisibilityMode="VisibleWhenSelected"
          VerticalAlignment="Top"
          Width="{Binding Path=ActualWidth, ElementName=grid}">
    <DataGrid.Columns>
        <DataGridTextColumn x:Name="Column1"
                            Binding="{Binding Path=Something1}"
                            Header="Column1"
                            Width="Auto"  />
        <DataGridTextColumn x:Name="Column2"
                            Binding="{Binding Path=Something2}"
                            Header="Column2"
                            Width="*" />
    </DataGrid.Columns>
</DataGrid>

Here the first column is as wide is needed and the second is spreaded space which is left. However the DataGrid's width is the same as Grid's widht that is around it, so the wanted outcome is achieved.

A: SizeToCells is what worked for me. I like this because its in XAML and it's concise.
<DataGridTextColumn x:Name="nameColumn" Binding="{Binding Name}" Header="Name" Width="SizeToCells"/>

A: AutoGenarateColumns="False"


text:
Q: How to view SQL generated by Entity framework I have couple of lines written like this:
 _DbContext.Business.Where(lb=>lb.id == (int)Constants.Business.Retail).Frist();

 //and

_DbContext.Business.Where(lb=>lb.id == (int)Constants.Business.Retail).FristOrDefault();

How can I view SQL generated by this code during my debug (break point debug)?
The code suggested very lengthy. Any sample code for quick reference during debugging?
Thanks.


text:
Q: stateful never[] array is still being able to assign data I know that when passing an empty array to useState hook we should also provide the proper type, otherwise typescript would infer never[].
The following is something I did before knowing that and by my surprise is working:
It's a component intended to fetch some data, that data is of type any and will be stored in loadedUsers, which has a type of never[].
const AllUsers: FC<AllUsersProps> = () => {
  const [isLoading, setIsLoading] = useState(true);
  const [loadedUsers, setLoadedUsers] = useState([]);

  useEffect(() => {
    UserService.getAllUsers()
      .then((response) => response.json())
      .then((data) => {
        console.log("users after retrieving data", data);

        setIsLoading(false);
        setLoadedUsers(data);
      });
  }, []);

Then I use loadedUsers to render a simple view
if (isLoading) {
    return (

Loading users

    );
  }

  return (

Users table

        <UserTable users={loadedUsers} />

Find user by id

        <UserSearch />

  );
};

Why am I not getting any errors during compilation? even in vscode there is no warning message


text:
Q: GitLab.com Download Counter I uploaded a GIT repository at GitLab.com, everything seems to work fine.
But I cannot find download statistics. For me this is an essential feature, and GitLab.com hosting would be insufficient without it.
Did I miss something? Can anybody tell me how to get a counter for the number of downloads on GitLab.com?
Thanks in advance.

A: FWIW, as of today you can get the last 30 days' http fetch statistics using the REST API as detailed here: https://docs.gitlab.com/ee/api/project_statistics.html with
GET /projects/:id/statistics
where :id is the URL-encoded path of the project.
For instance
curl -X GET 'https://gitlab.com/api/v4/projects/username%2Fmy-repo/statistics' -H "PRIVATE-TOKEN: XYZ"

A: A similar question was asked in the Gitlab support tracker. The answer was, in March 2015:

I'm sorry, but we don't provide download statistics for files uploaded to GitLab.com

You would need to run your own instance of Gitlab CE and setup your own statistics if you would like to track usage like this. Gitlab EE switched from Google Analytics to Matamo for tracking users, but they just don't expose that information to end-users on Gitlab.com, probably for privacy reasons.
A feature request for this was created on the Gitlab CE issue tracker in September 2016, was noted as "a reasonable request" by the GitLab product VP and added to the "Backlog" in January 2018, and was marked "Accepting Merge Requests" in April 2018.


text:
Q: How to replace by order How can I replace something orderly? for example:
$var = "let's count: ?, ?, ?";

Now I want to replace it by 1, 2, 3 for the result to be "let's count 1, 2, 3". How can I do that? I can't replace by "%s" and use vsprintf() with an array because I wanna respect integers and floats. But I want to do it with an array. For example:
$var = replace( $var, "?", array(1, 2, 3) );

How can I do it? I can't get any idea.

A: How about:
$var = "let's count: ?, ?, ?";
$numbers = array(1,2,3);

foreach( $numbers as $number ) {
  $var = preg_replace("/\?/", $number, $var, 1);
}

A: PHP is fun.
$var = "let's count: ?, ?, ?";
$replace = array('1', '2', '3');
$needle = '?';

foreach($replace as $val) {
    $var[strpos($var, $needle)] = $val;
}

A: Since strpos() will return the first result of the occurance you could do something like this:
$var = "let's count: ?, ?, ?";
$index = 1;
while(strpos($var, '?'))
{
    $var[strpos($var, '?')] = $index;
    $index++;
}
echo $var;

A: Why you need use substr_count or strpos in answers above? You can use simple for for this task. Look into my example.) This is the most fastest solution for performance.
$var = "let's count: ?, ?, ?";
$replace = array(1,2,3);

for($i=0, $r=0; $i< strlen($var); $i++){

$var[$i] = '?' === $var[$i] ? $replace[$r++] : $var[$i] ;

}

var_dump($var);

Result:
string(20) "let's count: 1, 2, 3"

A: $str = "lets count: ?, ?, ?";
$search = "/\?/";
$replace = array(1,2,3);

if( is_array($replace) ) {
  $search = array_fill(0, count($replace), $search);
}

echo preg_replace( $search, $replace, $str, 1);

//output: lets count: 1, 2, 3

A: $var = "let's count: ?, ?, ?";
$cnt = substr_count($var, '?');

for ($i=1;$i<=$cnt;$i++)
    $var = substr_replace($var, $i, strpos($var, '?'), 1);

echo $var; //let's count: 1, 2, 3


text:
Q: How to do np.dot in specific axis If I have two arrays a #25x25x3x5 and b #25x25x5x3, how can I get dot product of a and b with the output 25x25x3x3?

A: What you want is not the dot product but matrix multiplication.
For two matrices with shapes (A,B) and (B,C) it is defines as:
(A,B) * (B,C) = (A,C)
This corresponds to your last two dimensions and the desired output (3,5)*(5,3)=(3,3).
You can use np.matmul like this:
import numpy as np

a = np.random.uniform(0,1,size=(25,25,3,5))
b = np.random.uniform(0,1,size=(25,25,5,3))

x = np.matmul(a,b)

print(x.shape) # (25, 25, 3, 3)


text:
Q: Client SSL certificate verify error in Nginx We have a ROOT CA ( ADCS ) which we use to signed a client certificate which we use for Client Certificate Verification in Nginx.
This is the relevant Nginx configuration file :-
 ssl_client_certificate /etc/nginx/ca.crt;
 ssl_verify_client   optional;

 ssl_crl /etc/nginx/latest.pem;
 ssl_verify_depth 1;

Were ca.crt is the ROOT CA certificate and latest.pem is the CRL.
However whenever I try for any certificate ( Working and Revoked ) , it always lead to 400 Bad Request in Nginx.
Error :-
client SSL certificate verify error: (3:unable to get certificate CRL) while reading client request headers
Info :-
Similar configuration seems to work perfectly in Apache however for NGINX it always leads to error. I tried changing the ssl_verify_depth to 1 and 2 but it leads to same error.


text:
Q: Optimization With Few Measurements? In the context of Statistics and Probability, we are often told it is not advisable to:

*

*If you have an independent variable with many categories (e.g. there are 41,683 ZIP codes in the USA - if you data on people from many ZIP codes and you decide to use the ZIP code they are located in as an independent variable), do not include this variable into a regression model (e.g. salary = bo + b1age + b2gender + b3*ZIPCODE)

I always wondered if there was a mathematical reason for this.
I have usually been told that the problem with this is the following: suppose your dataset is only 100,000 rows - this means that you will inevitably have very few rows for some of the ZIP codes. As a result, you will end up generalizing your results based on very few observations to the entire ZIP code. Therefore, it is better not to use this variable as a independent variable in your model.
But is there a mathematical reason for this as well? When writing the Maximum Likelihood Equations and attempting to optimize them in such a context (i.e. when you have decided to use the ZIP code as an independent variable) - are there any mathematical problems that may arise when attempting to optimize a system of equations a variable only has a few observations per group?
Thank you!

A: Zip codes should be considered about as random and unordered as first names.
Any correlation is more or less coincidental.
Actually, with first names, some correlation can be expected, since it also could relate to gender, age, and ethnicity. However, without a proper ordering of the first names, this relation is coincidental and not linear.


text:
Q: Are the rationals homeomorphic to any power of the rationals? I asked myself, which spaces have the property that $X^2$ is homeomorphic to $X$. I started to look at some examples like $\mathbb{N}^2 \cong \mathbb{N}$, $\mathbb{R}^2\ncong \mathbb{R}, C^2\cong C$ (for the cantor set $C$). And then I got stuck, when I considered the rationals. So the question is:
Is $\mathbb{Q}^2$ homeomorphic to $\mathbb{Q}$ ?

A: Yes, Sierpinski proved that every countable metric
space without isolated points is homeomorphic to the rationals:
http://at.yorku.ca/p/a/c/a/25.htm .
An amusing consequence of Sierpinski's theorem is that
$\mathbb{Q}$ is homeomorphic to $\mathbb{Q}$. Of course here one
$\mathbb{Q}$ has the order topology, and the other has the $p$-adic
topology (for your favourite prime $p$) :-)

A: As Gerald Edgar points out in his comment on Xandi Tuni's answer, the continued fraction trick works for the irrationals, not for the rationals.  But this turns out to be enough:
1) An irrational number has a unique continued fraction expansion.  Therefore the irrationals are isomorphic to an infinite direct product of ${\mathbb Z}$ with itself.  Therefore (writing ${\mathbb I}$ for the irrationals) we have ${\mathbb I}={\mathbb I}^2$.
2)  Therefore ${\mathbb I}^2$ imbeds as a dense subset of the reals.  Now map ${\mathbb Q}\times {\mathbb Q}$ to ${\mathbb I}\times {\mathbb I}$ by (say) adding $\sqrt{2}$ to each component.  This imbeds ${\mathbb Q}\times {\mathbb Q}$ as a countable dense subset of the reals.
3)  Now use the fact that every countable dense subset of the reals is homeomorphic to ${\mathbb Q}$.

A: Yes, they are homeomorphic. To construct a homeomorphism from $\mathbb Q$ to $\mathbb Q^2$, one can proceed roughly as follows: express $q\in \mathbb Q$ as a continued fraction $[a_0, a_1,a_2,...]$ (of finite length) and associate with it the pair $([a_0,a_2,...], [a_1,a_3,...])$.
Mind that this is a homeomorphism, but not an isometry (cf comment on Tom's answer).
I vaguely remember that there is a general Theorem in point set topology stating that all countable topological spaces "of the same kind as $\mathbb Q$" are homeomorphic.

A: I don't think so: the completion of $\mathbb{Q}^2$ is $\mathbb{R}^2$, so that a homeomorphism $\mathbb{Q}^2\to\mathbb{Q}$ would give a homeomorphism  $\mathbb{R}^2\to\mathbb{R}$?


text:
Q: Why isn't Zaeed's name listed? Zaeed was part of my team in ME2 & all of my team members made it out alive from the suicide mission.

 I ran in to Zaeed later at the Volus diplomat's quest & during the subsequent attack, Zaeed was killed. However, his name isn't listed in the dead list

 http://steamcommunity.com/id/sathyabhat/screenshot/486626996099715422

A: It seems to be just a bug, and not related to either DLC character:

For some reason they forgot Zaeed, but Kasumi still appears (circled above).

However, if Zaeed wasn't loyal to the mission, he will die saving Korlack. Oddly enough, he won't appear on the memorial wall on the crew deck, although Joker will mention him as a casualty before launching the last mission.

source

A: My guess is since Zaeed is a DLC character (ME2 Cerberus network), he just wasn't included in the base ME3 memorial wall code.


text:
Q: XSLT mapping values of attribute from range I'm new to xslt and i need your help.
My input xml file looks like this
<dataset>
    <item date="13days" />
    <item date="14days" />
    <item date="27days" />
</dataset>

And my output should look like this
<dataset>
    <item date="1week" />
    <item date="2week" />
    <item date="3week" />
</dataset>

Map would look like this:
0days<=1week<14days
14days<=2week<21days
21days<=3week<28days

For now i just know how to change specific date, but i need ranges. Here's my attempt.
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:my="my:my">
<xsl:output omit-xml-declaration="yes" indent="yes"/>
<xsl:strip-space elements="*"/>
<my:map>
<map>
<item from="13days" to="1week" />
<item from="14days" to="2week" />
<item from="27days" to="3week" />
</map>
</my:map>
<xsl:variable name="vMap" select="document('')/*/my:map/*/*"/>
<xsl:template match="node()|@*">
<xsl:copy>
<xsl:apply-templates select="node()|@*"/>
</xsl:copy>
</xsl:template>
<xsl:template match="@maturity[. = document('')/*/my:map/*/*/@from]">
<xsl:attribute name="maturity">
<xsl:value-of select="$vMap[@from = current()]/@to"/>
</xsl:attribute>
</xsl:template>
</xsl:stylesheet>

A: Couldn't you do simply:
XSLT 1.0
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<xsl:strip-space elements="*"/>

<!-- identity transform -->
<xsl:template match="@*|node()">
    <xsl:copy>
        <xsl:apply-templates select="@*|node()"/>
    </xsl:copy>
</xsl:template>

<xsl:template match="@date">
    <xsl:variable name="d" select="substring-before(., 'days')" />
    <xsl:attribute name="date">
        <xsl:choose>
            <xsl:when test="$d < 14">1week</xsl:when>
            <xsl:when test="$d < 21">2week</xsl:when>
            <xsl:when test="$d < 28">3week</xsl:when>
        </xsl:choose>
    </xsl:attribute>
</xsl:template>

</xsl:stylesheet>

Or, if you prefer:
<xsl:template match="@date">
    <xsl:variable name="d" select="substring-before(., 'days')" />
    <xsl:attribute name="date">
        <xsl:choose>
            <xsl:when test="$d < 14">1</xsl:when>
            <xsl:otherwise>
                <xsl:value-of select="floor($d div 7)"/>
            </xsl:otherwise>
        </xsl:choose>
        <xsl:text>week</xsl:text>
    </xsl:attribute>
</xsl:template>


text:
Q: Using OpenAPI 3.0 is there a way to link a boolean query param to a specific example I'm mocking this in swagger.com so the frontend dudes I'm working with have a mocked api they can send queries to while I build out the endpoints.
Is it possible to filter the examples on a given endpoint by varying the parameter and if so how can you do it?
To be more specific, I want to return #components/examples/default_vans when all_system_vans = false or null
While also returning #components/examples/all_system_vans-is-true when all_system_vans = true
Below is my openapi schema.
openapi: 3.0.0
info:
  title: "Van life"
  description: "VANS"
  version: "1.0.0"

tags:
- name: "van"
  description: "All things Van (life)."

paths:
  /vans:
    get:
      tags:
      - "van"
      summary: ""
      operationId: "getVan"
      parameters:
      - in: "query"
        name: "all_system_vans"
        description: "Default of false will get vans in ready to go, true will get all system vans."
        required: false
        schema:
          type: "boolean"
          default: false
      responses:
        "200":
          description: "Ok"
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Vans"
              examples:
                buffer_only_vans:
                  $ref: "#/components/examples/default_vans"
                all_system_vans:
                  $ref: "#/components/examples/all_system_vans-is-true"
        "400":
          $ref: "#/components/responses/400"
        "404":
          $ref: "#/components/responses/404"

components:
  responses:
    "400":
      description: "Invalid status value"
    "404":
      description: "Whatever you were looking for is not found."
  examples:
    default_vans:
      summary: ""
      value: {"vans": ["van_2", "van_3", "van_5", "van_7", "van_11"]}
    all_system_vans-is-true:
      summary: ""
      value: {"vans": ["van_1", "van_2", "van_3", "van_4", "van_5", "van_6", "van_7", "van_9", "van_10", "van_11"]}

  schemas:
    Vans:
      type: "object"
      properties:
       vans:
          type: "array"
          items:
            type: "string"

externalDocs:
  description: "Find out more about Swagger"
  url: "http://swagger.io"

A: OpenAPI Specification does not have any syntax to correlate response definitions to specific input values. Here's a related feature request in the OpenAPI Specification repository:
Request/response correlation
But some OpenAPI mocking / service virtualication tools support such request/response correlation. For example, ReadyAPI Virtualization (made by the company I work for) has various response dispatch options, including sequential and random response selection as well as choosing the response based on request data.


text:
Q: exist-db not reading gzip files I have just installed a new Exist-db and I'm willing to use it to parse XML files that are actually compressed in gzip.
It is my understanding that exist-db has the cappability to perform this kind of operations, but I keep getting the error MIME type invalid.
I've added a new MIME type in the mime-types.xml file with the following parameters:
<mime-type name="application/zip" type="binary">
  <description>GZIP archive</description>
  <extensions>.gz</extensions>
  </mime-type>

But I keep getting the same reading error.
Could somebody point me in the right direction? Am I missing something?
Thanks!
G.

A: eXist-db can only work on XML data that has been parsed and processed (and indexed) into the eXist-db internal storage format. This means that the data needs to be decompressed before it can be queried; A GZIPped XML document stored in the database is considered to be "a binary blob' and cannot be queried.
When the GZIP file is stored in the database, you can use the compression:unzip() function (link) to uncompress the document. The document can then be stored in the database.


text:
Q: convert TextField to Var Int (swift) Hi Im new to swift programming. I would like to get the input of a textfield, convert it to an int and then work with that int (decreasing it). Here is my code:
 @IBOutlet weak var minutes: UITextField!

 @IBOutlet weak var seconds: UITextField!

@IBOutlet weak var label_Timer: UILabel!

@IBAction func btn_Timer(_ sender: UITextField) {

    var min:Int = Int(minutes.text!)
    var sec:Int = Int(seconds.text!)

    timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(ViewController.timerRunning), userInfo: nil, repeats: true)

}

func timerRunning(){

    sec -= 1

//operate on min and sec here

}

A: As @vadian pointed out in the comments, you need to declare min and sec as properties so that they can be accessed from the timerRunning method.
Also, I suggest you make use of the nil coalescing operator ?? to safely unwrap the UITextField text values and the result of the Int conversion.
@IBOutlet weak var minutes: UITextField!

@IBOutlet weak var seconds: UITextField!

@IBOutlet weak var label_Timer: UILabel!

var min = 0
var sec = 0

@IBAction func btn_Timer(_ sender: UITextField) {

    min = Int(minutes.text ?? "") ?? 0
    sec = Int(seconds.text ?? "") ?? 0

    timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(ViewController.timerRunning), userInfo: nil, repeats: true)

}

func timerRunning(){

    sec -= 1

    //operate on min and sec here

}


text:
Q: Jsjws JSON Web signatures and tokens I'm trying to include jsjws in my current project (Backbone, Marionette) which uses RequireJS to include all modules. I have AMD and non AMD scripts included, the non AMD using shims but I'm not sure how jsjws (http://kjur.github.io/jsjws/) will work in this instance. Maybe someone can help?
Current RequireJS config with attempt at including jsjws:
    paths: {
    backbone: "vendor/backbone", "backbone.syphon":"vendor/backbone.syphon",
    jquery: "vendor/jquery",
    json2: "vendor/json2",
    underscore: "vendor/underscore",
    marionette: "vendor/backbone.marionette",
    jsjws: "vendor/jws-3.0",
    tpl: "vendor/tpl"
},

shim: {
    underscore: {
        exports: "_"
    },
    backbone: {
        deps: ["jquery", "underscore", "json2"],
        exports: "Backbone"
    },
    "backbone.syphon": ["backbone"],
    marionette: {
        deps: ["backbone"],
        exports: "Marionette"
    }
}

many thanks,
Wittner

A: Looking at the code for jsws and at the documentation, it seems to me that this is what you need to add to your shims:
jsjws: {
    exports: "KJUR"
}

Or I believe you could have it export "KJUR.jws" to skip the top level namespace (which seems useless in this context).
I was not able to find a clear list of what dependencies it has. If I look at the various samples in the github repo, the list of files loaded before jsjws seems to vary quite a bit depending on the specific needs of the project. At any rate, whatever your project needs for jsjws to do its job would have to be added to a deps field, and probably these dependencies would get shims of their own.


text:
Q: Change cursor of QgsMaptoolPan in QGIS programmatically I try to change cursor shape of QgsMaptoolPan using C++ without success.
I've connected the QgsMapTool::activated signal to a slot onPanActivate in a QgsMapCanvas Class.
in the slot, simply
QCursor crossCursor(Qt::CrossCursor);
this->mapTool()->setCursor(crossCursor)

The slot is called,  but the cursor shape still remains "the hand".


text:
Q: Continued Fractions from Digit Streams let $x=\sum_{i=1}^{\infty}\delta_i2^{-i},\ \delta_i\in\{0,1\}$.
Is there an algorithm that converts the sequence $(\delta_0,\ \delta_1,\ ...)$ of the binary digits of $x$ to the sequence $[a_0;a_1,\ ...]$ of its continued fraction representation?

A: No, there is not. Already $a_0$ is impossible to determine just by reading finitely many digits (namely, it is $1$ iff $\delta_i=1$ for all $i$). The same goes for the subsequent terms of the continued fraction, mutatis mutandis.

A: Yes, there is. The algorithm is due to Bill Gosper - he is considering the more general problem of doing linear fractional transformations with continued fractions - adding $2^{-i}$ is a special case. See also Liardet and Stambul, 1998 for a fancier (and probably more readable) explanation.

A: (This should be considered rather a comment on Emil's answer than an own answer; please feel free to downvote).
after some thinking about Emil's negative result, I found a way to possibly "resurrect" the existence of an algorithm by introducing the means of prediction and correction.
Emil's counterexample, in which $\delta_i=1$ for $i\ge i_0$, can be fixed by

*

*setting $x_0 := 0,\  \delta_0 := 0$

*$x_{i+1} = x_i+(\delta_{i+1}-\delta_i)\frac{\beta^{-i}}{\beta-1}$, where the $\delta$'s denote the digits and the $\beta$'s the base of the number system.

as the $x_{i+1}-x_i$ is zero in case of equal digits, the calculated coefficients of continued fraction in case of a trailing sequence $(\delta_i=\delta_{i+1}=\ ...)$ will be that of $x$ and not modified after $i$ steps.
The above idea however doesn't resolve the case of rational $x$ in general; here the best approximation property of continued fractions may be of use in predicting the true continued fraction of $x$: experiments suggest, that $a_i=0, i>=i_0$ in case of rational $x$, and that the value of one of the non-zero parameters $a_k\in\{a_1,\ ...,a_{i-1}\}$ keeps growing as more digits are processed, while the first $k-1$ parameters do not change after a sufficient number of digits have been processed.
In that case we can set $a_k:=\infty$, yielding $[0;a_1,\ ...,a_{k-1}]$ as the continued fraction of $x\in\mathbb{Q}$ if enough periods in the digit stream have been encountered.
I am however not an expert in continued fractions, so I'm not sure if my ideas are correct.


text:
Q: Creating a mySQL sub query to list distinct rows from two queries I have two queries:
'SELECT * FROM `table `WHERE weight = 0 OR weight IS NULL'

and
'SELECT * FROM `table `

The first query returns around 4000 values, the second query returns around 4100.
I'm attempting to create a query that will return the rows which are distinct between the two values, I'm attempting this by using a nested or sub query but I'm struggling with syntax here. Having only worked with very simple queries before. Could anyone suggest how I might do this.

A: I think this does what you want:
SELECT *
FROM `table`
WHERE NOT (weight = 0 OR weight IS NULL);

That is more simply written as:
SELECT *
FROM `table`
WHERE weight <> 0;

A: use MINUS operator as below
 SELECT * FROM `table`
 MINUS
 SELECT * FROM `table` WHERE weight = 0 OR weight IS NULL

A: SELECT * FROM table1
WHERE (table1.weight = 0 OR table1.weight IS NULL)
AND table1.Column not in (SELECT table2.column
                          FROM table2)


text:
Q: rainerscript: how to log to file named $programname substring? How can I write a rainerscript rule to log to a file whose name is a substring of $programname?
I want something along the lines of this pseudo-rule:
if $programname startswith "foo" then /path/to/<substring of $programname from 4 to end>

Also: is there a way to strip the "foo" prefix from $programname in the text that gets written to file?

A: Actually I'm feeling unhelpful with my comment to the OP. I did some more testing and here's a solid answer that I'd like to share:
Create /etc/rsyslog.d/00-local.conf with the following:
template(name="AdminLog" type="string" string="/var/log/admin_%syslogtag:R,ERE,1,ZERO::(.*):--end%")

if ($programname == "admin") then {
  action(type="omfile" dynaFile="AdminLog")
  stop
}

systemctl restart rsyslog
logger -t admin:backup starting
That results in /var/log/admin_backup getting the log.
Notes:

*

*I'm running Ubunto 20.04. Platform/version-specific nuances may affect your results.

*All changes and commands have been done under sudo -s.

*The template doesn't need to use a Regexp. The '%property:Field' notation would be more efficient. This is to demonstrate how to use the more complex Regexp. See syntax for both property replacer operations.

*See at the end of the %syslogtag that a colon is appended and needs to be accommodated in parsing.

*Use the very helpful regular expression test page for Rsyslog.

*Creating new files in a folder other than /var/log presents known complications and is outside the scope of the OP request. Get this working for files in /var/log and then take on the challenge separately to get it to work with a different folder.

*Note the action uses the dynaFile option.

*This could also be done by putting the result of the template into a variable with exec_template and then manipulating it further. Here is an example page.

*Rather than using a template, another way to do a regexp with Rainerscript is to use the re_extract function. Example:
set $.thefunction = re_extract($syslogtag,...)


text:
Q: Executing jar file through php I have a jar file that I am attempting to execute through php using
exec('java -jar DUapi.jar '.$USER.' '.$PWORD);

When I do that however, it does not output a text file to the directory like it's supposed to.  If I execute the jar on the command line, however, it works properly.  If I print the result code, the result is "Array".  Could this be an issue with permissions?


text:
Q: Why do (1 && !A) in c++ pre-processor In some C++ file, I found:
#ifndef UE_WITH_CHEAT_MANAGER
#define UE_WITH_CHEAT_MANAGER (1 && !UE_BUILD_SHIPPING)
#endif

Comming from CheatManager.h.
What is the difference with:
#ifndef UE_WITH_CHEAT_MANAGER
#define UE_WITH_CHEAT_MANAGER (!UE_BUILD_SHIPPING)
#endif

Is it in order to prevent warnings on some specific compiler?
Additional info:

*

*UE_BUILD_SHIPPING is 0 by default and is set to 1 for shipping builds (builds that are distributed to consumers/players).

*UE_WITH_CHEAT_MANAGER is used to exclude some part of the code from compilation.

(Edited to answer requests in comments.)

A: Nobody is perfect, not even the authors of the Unreal Engine.
Setting aside any possibility of operator overloading, the type and values of the two expressions are identical. I suspect (and it's only a hunch), that the author is forgetting that the type of (!B) is a bool in C++.
(1 && !B) is more explicitly perhaps a bool type as it contains the && operator.