text:
Q: Proving a space is Hausdorff if $f$ is continuous and bijective
Exercise: Let $(X,\tau_1)$ and $(Y,\tau_2)$ be  topological spaces and $f:(X,\tau_1)\to (Y,\tau_2)$ a continuous map. If $f$ is one-to-one, prove that $(Y,\tau_2)$ Hausdorff implies $(X,\tau_1)$ Hausdorff.

Attempted proof:
As $f$ is continuous and bijective $\exists \ x_1,x_2$ such that $x_1\neq x_2$ then $f(x_1)=y_1$ and $f(x_2)=y_2$ and $y_1\neq y_2$.
As $(Y,\tau_2)$ is Hausdorff $\exists \ U,V\in\tau_2$ such that $y_1\in U$ and $y_2\in V$ and $U\cap V=\emptyset$. As $f$ is continuous and bijective $f^{-1}(y_1)=x_1\in f^{-1}(U)\in\tau_1$ and $f^{-1}(y_2)=x_2\in f^{-1}(V)\in\tau_1$.
By the fact that $(Y,\tau_2)$ is Hausdorff and $\emptyset$ is open.
$\emptyset=f^{-1}(U\cap V)=f^{-1}(U)\cap f^{-1}(V)=$ such that $y_1\in f^{-1}(U)$ and $y_2\in f^{-1}(V)$. Then $(X,\tau_1)$ is Hausdorff.
Questions:
Is my proof right? If not. Why? What could be alternative proofs?
Thanks in advance!

A: This is wrong from the start. What you are supposed to prove is that for any two distinct elements $x_1,x_2\in X$, there are open sets $U_1$ and $U_2$ such that $x_1\in U_1$, $x_2\in U_2$, and $U_1\cap U_2=\emptyset$. Take open sets $V_1,V_2$ in $Y$ such that $f(x_1)\in V_1$, $f(x_2)\in V_2$ and $V_1\cap V_2=\emptyset$; such sets exist, since $Y$ is Hausdorff and $f$ is injective. Now, let $U_1=f^{-1}(V_1)$ and let $U_2=f^{-1}(V_2)$. Then $x_1\in U_1$, $x_2\in U_2$ and, since $f$ is continuous, $U_1$ and $U_2$ are open. And, since $V_1\cap V_2=\emptyset$, $U_1\cap U_2=\emptyset$ too.
Note that the fact that $f$ is surjective is irrelevant.

A: I think your ideas are correct but imprecise. We ought to prove that each pair of distinct points of $X$ have disjoint neighbourhoods.
If $x_1, x_2 \in X$ are distinct points, so are $f(x_1)$ and $f(x_2)$. Since $Y$ is Hausdorff, we have open disjoints sets $U_i \ni f(x_i)$, and thus  $V_i = f^{-1}(U_i)$ are open and disjoint, with $x_i \in V_i$. Hence $X$ is Hausdorff.
Another approach: a space $Z$ is Hausdorff if and only if the diagonal
$$
\Delta_Z = \{(z,z) : z \in Z \} \subseteq Z \times Z
$$
is closed. In your case,
$$
\Delta_X = \{(x,x) : x \in X\} = \{(x,x') \in X \times X  : f(x) = f(x')\}
$$
because $x = x'$ if and only $f(x) = f(x')$, since $f$ is bijective. Thus, $\Delta_X$ is the preimage of the (by hypothesis) closed set $\Delta_Y$ via the continuous function $(f \times f) : X \times X \to Y \times Y$,
$$
\Delta_X = (f \times f)^{-1}(\Delta_Y)
$$
and so it is closed, which says that $X$ is Hausdorff.
As José Carlos Santos notes in his answer, surjectivity is not needed. After all, we have only needed some bijective correspondence between $X$ and $f(X)$, and since $f(X) \subseteq Y$ is Hausdorff as well, we can let go of the surjectivity hypothesis.


text:
Q: How to check if user exists in database given an email or a phone number in DRF I need to check if a user exists in the database given their input: either their email or phone number. If the user exists, the user is used to take their order. If the user inputs both their email and phone and they don't exist in the database, I need to create the user. How do I do this?
This is the serializer:
class UserSerializer(serializers.ModelSerializer):

   class Meta:
       model = User
       fields = '__all__'
       extra_kwargs = {
           'email': {'required': True},
           'phone': {'required': True}
       }

   def create(self, validated_data):
       user= User.objects.create(
           email=validated_data['email'],
           phone=validated_data['phone']
       )

       user.save()

       return user

class OrderSerializer(serializers.ModelSerializer):
   food= FoodSerializer(many=True)

   class Meta:
       model = Order
       fields = ('date','food','phone','email')

       def validate(self, data):
           email = data.get('email')
           phone= data.get('phone')

           if not email and not phone:
               raise serializers.ValidationError("Email or phone required")

           return data

       def checkuser(self, cliente, data):

           if data['email'] or data['phone'] in user:
               return user
           elif data['email'] or data['phone'] not in user:
               pass

       def create(self, validated_data):
           order = Order.objects.create(
               email=validated_data['email'],
               phone=validated_data['phone'],
               date= validated_data['date'],
               food= validated_data['food'],
               quantity= validated_data['quantity'],
           )

           order.save()

           return order

A: get_or_create() helper is what you want.
   def create(self, validated_data):
       filters = {}
       if email := validated_data.get('email'):
           filters["email"] = email
       if phone := validated_data.get('phone'):
           filters["phone"] = phone

       user, _ = User.objects.get_or_create(**filters)
       return user

redpajama_set_name: RedPajamaStackExchange


text:
Q: How is the time complexity of Morris Traversal o(n)? http://geeksforgeeks.org/?p=6358
Can anyone please explain how Morris Traversal has a time complexity of o(n)?  In the traversal, whenever the node has a left child a copy of it is made to the right child of its predecessor. So worst case is that predecessor has to be found for each node
 while(pre->right != NULL && pre->right != current)
        pre = pre->right;

Which is going to increase the time complexity?
Am I missing anything here?

A: Another way of looking at it is to find out how many times a tree node will be traversed. As it is constant(3 times for a binary tree). We are looking at O(n).

A: First, I have a correction to make to a claim that you made:

In the traversal, whenever the node has a left child a copy of it is made to the right child of its predecessor

A copy of the [current] node is not made to the right child of its [current node's] predecessor - the right child of current node's predecessor is pointed to current node - a pointer does not make any copy; instead it just points to the current node that already exists.
Now to answer your question about your code snippet:
while(pre->right != NULL && pre->right != current)
        pre = pre->right;

*

*That loop does add time to the running of the algorithm [compared to if that loop were not in the code]

*But in a worst case, the time it adds is exactly n (taking the run time from n to 2n).  This worst case happens when every single node must be visited an extra time, in order to find all predecessors; by the way, each such extra visit of a given node is the only extra time it is visited when finding predecessors (that's because finding any other predecessor will never travel over the same nodes that were traveled through to find any other predecessor) - that explains why the extra time contributes going from n -> 2n [linear] but not n -> n^2 [quadratic]

*Even though 2n > n, when [Big-O] complexity is considered, O(2n) = O(n)

*In other words, taking longer time of 2n compared to n is not actual extra complexity:  n & 2n runtimes both have complexities of identical O(n) [they are both "linear"]

Now even though it may have sounded like I was implying above that the entire algorithm runtime is 2n, it is not - it is actually 3n.

*

*The loop that is in just the code snippet itself contributes n time

*But the algorithm as a whole runs in 3n because each node is visited at most 3 times {once/first to "thread" it back to the node that it is a predecessor of (the ultimate goal that the code snippet helps achieve); a 2nd time when it is arrived at in otherwise normal traversal [as opposed to anything to do with predecessor threading]; and then a 3rd/final time when it is found as predecessor [that itself for the 2nd/final time] again and its right-child pointer/thread is removed from pointing to right-child of current node [directly before printing current node]}

*And again [just as complexity O(2n) = O(n)], complexity O(3n) = O(n)

*So to summarize:  Yes, your code snippet loop does contribute time, but NOT extra time complexity
By the way, I don't think this line (from the full algorithm) to remove the old predecessor "thread" reference is strictly necessary (although it doesn't hurt, and can be considered nice tidying-up):
pre->right = NULL;

A: I discuss Morris inorder traversal here, because one node can be visited at most 4 times, so the time complexity is O(n).
Let's divide the types that one node is visited into two types:

*

*the current visits the node.
If one node has left child, current visits twice, otherwise visits once.

*build a loop and destroy the loop.
If one node is in a loop, it is visited twice, otherwise zero.
I draw the figure below and use A + B to represent the times, A is current, B is loop.

For the node D,  current moves from B to Dand from E to D. D is also in the loop A B D F G, D is visited when current move from A to B(build the loop) and from A to H(destroy the loop). Therefore, node D is visited 2 + 2 = 4 times.

A: The original paper for Morris traversal is Traversing binary trees simply and cheaply. It claims that time complexity is O(n) in Introduction section:

It is also efficient, taking time proportional to the number of nodes in the tree and requiring neither a run-time stack nor 'flag' bits in the nodes.

The full paper should have a analysis of time complexity. But the full paper can't be accessed for free.
Morris Traversal方法遍历二叉树(非递归,不用栈,O(1)空间) does some analysis. I have translated some relevant part and made some corrections based on my understanding. Here is my understanding:

A n-node binary tree has n-1 edges. In a Morris traversal, one edge is visited at most 3 times. 1st visit is for locating a node. 2nd visit is for looking for the predecessor of some node. And 3rd/final is for restoring the right child of the predecessor to null. In the following binary tree, red dashed line is for locating a node (1st visit). Black dashed line is for looking for predecessor node (traveled two times: for both 2nd visit AND 3rd visit). Node F will be visited when being located. It will also be visited when node H is looking for its predecessor. Finally, it will be visited when restoring the right child of node G (H's predecessor) to null.

A: it is not going to increase the complexity as the algorithm just rebuilds the tree in only one direction(rebuilding takes only O(n) after which its only O(n) again to print them... but they have merged both the functionality into a same function and gave a special name for the algo thats it...


text:
Q: Best way to expose OpenAPI specs to Client Services I have a set of independent micro-services, all of whom follow an API-first design approach (The Controller interfaces and Models are generated at build time with OpenAPI-3 contract as single source of truth). And I want to expose these OpenAPI contracts to my clients(which will in-turn will generate client code from exposed OpenAPI contracts, A client can consume multiple downstream services). The OpenAPI contract is
version-controlled in the same git repository where micro-service code lives.
What's the best way expose these contracts, considering above scenario? And are there any open-source tools to support this requirement?
Here are few options that i explored:

*

*Expose via git repository file link.(Cons: not suitable for private repositories)

*Expose via a public Gist. (Cons: Separate maintenance of the gist on every update to the contract)

*Export as a git sub-module. (Cons: Extra overhead of maintaining a separate repository for OpenAPI specs)

*At the service build time, upload the OpenAPI contracts to a service-discovery. (Not sure what service-discovery tools support this feature of exposing OpenAPI specs as urls, any help is appreciated. Also one concern is that the service-discovery may become single point of failure).


text:
Q: Set textview XML in java My app has edittext and a button. Everytime I click a button a new textview is added to activity. Below is the code:
public void novVnos (View v){
    EditText eText = (EditText) findViewById(R.id.editText1);
    RelativeLayout mLayout = (RelativeLayout) findViewById(R.id.relativeLayout);

    mLayout.addView(createNewTextView(eText.getText().toString()));
}

private TextView createNewTextView (String text){
    final LayoutParams lparams = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
    final TextView textView = new TextView(this);
    int counter = 0;

    counter += 1;
    textView.setLayoutParams(lparams);
    textView.setText(counter + ". " + text);
    return textView;
}

Now the thing is that whenever I add a new textview using the button, it is automatically placed in the upper left corner of the activity, but I want it somewhere else. I have already (manually) added a new textview to this activity and I want every new textview to be automatically placed UNDER this textview that already exists.

A: I'm not sure if you really need to have a RelativeLayout there, I strongly suggest using a LinearLayout instead and setting the orientation to vertical, which would make all views be added below each other.
If you really need to have a RelativeLayout, there is of course a way also. But you will have to specify the correct LayoutParams. Each of the default viewgroups have it's own LayoutParams class.
Using RelativeLayout.LayoutParams - especially the method addRule(RelativeLayout.BELOW, idOfOtherView) - you can tell a view to be below another view.

A: Use a LinearLayout with vertical orientation on your XML and no a RelativeLayout.


text:
Q: NullReferenceException using where clause I have a scenario that I am getting the result properly .But i have to search it in that result.Here is my code.
if(productSearch.Keyword !=null || productSearch.Code!=null)
{
    var key = productSearch.Keyword;
    var cod = productSearch.Code;

    if (productSearch.Code != null)
    {
        var Selected_Result = result.Results.Where(s => s.Code.ToLower().Contains(cod.ToLower())).ToList();
        result.Results = Selected_Result;
    }
    else
    {
        var Selected_Result = result.Results.Where(s => s.Keyword.ToLower().Contains(key.ToLower())).ToList();
        result.Results = Selected_Result;
    }
}

But it gives following exception :

Object reference not set to an instance of an object on  result.Results.Where(s => s.Code.ToLower().Contains(cod.ToLower())).ToList();

I know s => s.Code.ToLower() is coming NULL, but i dont know why, result has records.
Thanks in advance.

A: If it's null in the query then chances are it's null in the DB. To be on the safe side you can use the null coalescing operator to make sure you have at least something to call ToLower on e.g.
result.Results.Where(s => (s.Code ?? "").ToLower().Contains(cod.ToLower()))
              .ToList();


text:
Q: Display an SVG circle with both color and background I want to create one svg bubble that can be displayed with color,background image and text(somewhat like the following image).:

Following is what I've done so far:
Bubble.svg
<!DOCTYPE html>
<html>
 <body>
<svg xmlns="http://www.w3.org/2000/svg"    xmlns:xlink="http://www.w3.org/1999/xlink" width="700" height="660">
<defs>
<pattern id="image" patternUnits="userSpaceOnUse" height="100" width="100">
  <image x="0" y="0" height="100" width="100"  xlink:href="C:\Users\i333320\Desktop\images.jpg" opacity="0.5"></image>
 </pattern>
</defs>
<g id="Page-1" stroke="none" stroke-width="1" fill="none" fill-rule="evenodd">
<circle id="Oval-1" fill="url(#image)" cx="50%" cy="50%" r="30%"/>
<text x="50%" y="50%" fill="blue" stroke="red" stroke-width="1" text- anchor="middle" dy=".3em">Hello</text>
</g>
 </svg>
 </body>
 </html>

And output of above code is:

How can I fill color and display both background image as well as color.
It can be done with html-css or should I use React framework?

A: Maybe you can use a svg with background color overlying another svg with background image. And set the upper transparent.

A: You can use a filter for this. feImage will import an image, feBlend/screen will blend the image and the original. feComposite/in will clip the image to the source graphic.

<svg xmlns="http://www.w3.org/2000/svg"    xmlns:xlink="http://www.w3.org/1999/xlink" width="700px" height="660px">
<defs>
  <filter id="imageblend" primitiveUnits="objectBoundingBox">
<feImage height="120%" width="120%" xlink:href="https://upload.wikimedia.org/wikipedia/commons/8/81/Picea_abies.jpg" preserveAspectRatio="none"/>
    <feBlend mode="screen" in2="SourceGraphic"/>
    <feComposite operator="in" in2="SourceGraphic"/>

  </filter>
</defs>
<g id="Page-1" stroke="none" stroke-width="1" fill="none" fill-rule="evenodd">
<circle id="Oval-1" filter="url(#imageblend)" cx="50%" cy="50%" r="30%" fill="#0044ff"/>
<text x="50%" y="50%" fill="blue" stroke="red" stroke-width="1" text- anchor="middle" dy=".3em">Hello</text>
</g>
 </svg>

A: You don't even need SVG for your purpose, it can be done just by HTML/CSS. You'll need a div with equal width and height, and border-radius: 100%. Afterwards, you may set color, background and any other properties.


text:
Q: Creating SQL Indexes? I have two tables in my database that look roughly like this:
Communication: (Calls made)
Timestamp            FromIDNumber ToIDNumber GeneralLocation
2012-03-02 09:02:30  878          674        Grasslands
2012-03-02 11:30:01  456          213        Tundra
2012-03-02 07:02:12  789          654        Mountains

Movement:
Timestamp            IDNumber Type        X   Y
2012-03-02 11:02:30  379      pedestrian  32  46
2012-03-01 12:32:41  654      pedestrian  54  56
2012-03-02 07:02:16  789      pedestrian  39  52

and I want to run this query:
SELECT c.senderID, c.timestamp, m.timestamp, m.x, m.y
FROM communication c
JOIN movement m
ON c.senderID = m.visitorID
WHERE m.timestamp >= c.timestamp
ORDER BY m.timestamp LIMIT 1;

Basically, I want to find the closest movement timestamp to a given communication timestamp.
The thing is, these tables have millions of entries and I need to use indexes. The problem is, I'm new to SQL, and I'm not sure exactly how to structure my indexes.... would I need to have one for m.timestamp and c.timestamp separately like this?
CREATE INDEX mtstamp ON DBName.movement (timestamp);

CREATE INDEX ctstamp ON DBName.communication (timestamp);

Any help would be greatly appreciated, thank you!!

A: I think you need a composite index that includes both the ID that you're using in the JOIN and the timestamp. Otherwise, it will just use the ID indexes for the join, but it will then have to scan all the matching rows to do the timestamp comparisons.
CREATE INDEX sender_timestamp ON communication (senderID, timestamp);
CREATE INDEX visitor_timestamp ON movement (visitorID, timestamp);

A: I would create an index on timestamp on both table since that column is used in WHERE condition to filter out rows as well as in ORDER BY for sorting.
Also, create an index on senderID in Communication table and visitorID in Movement table unless those are primary key column on the respective table; since those two columns are involved in join condition.


text:
Q: document is not defined when do "tns test android" I create a login.component.spec.ts for my loginComponent. However, when I run tns test android, the TestBed.createComponent(LoginComponent) failed. The error is below:

NativeScript / 29 (10; Android SDK built for x86) LoginComponent
  Should create the app FAILED
Failed: StaticInjectorError(DynamicTestModule)[TestComponentRenderer
  -> InjectionToken DocumentToken]:
StaticInjectorError(Platform: core)[TestComponentRenderer ->
  InjectionToken DocumentToken]: document is not defined
error properties: Object({ ngTempTokenPath: null, ngTokenPath: [
  'TestComponentRenderer', InjectionToken DocumentToken ] }) at Jasmine

I cannot find any result in website about my problem. Thanks for helping.
I tried to include http module since someone said the undefined document may because of http. However, it still does not work.
This is code for login.component.spec.ts:
import "core-js";

import "zone.js/dist/zone";

import "zone.js/dist/proxy";

import "zone.js/dist/sync-test";

import "zone.js/dist/async-test";

import "zone.js/dist/fake-async-test";

import "zone.js/dist/jasmine-patch";

import "zone.js/dist/long-stack-trace-zone";

import { ComponentFixture, async, TestBed} from '@angular/core/testing';

import { By } from '@angular/platform-browser';

import { NO_ERRORS_SCHEMA, DebugElement} from '@angular/core';

import { RouterTestingModule } from '@angular/router/testing';

import { Router } from '@angular/router';

import { ActivatedRoute } from "@angular/router";

import { RouterExtensions } from "nativescript-angular/router";

import { BrowserDynamicTestingModule, platformBrowserDynamicTesting }
from '@angular/platform-browser-dynamic/testing';

import { LoginComponent } from '~/pages/login/login.component';

describe ('LoginComponent', () => {

    beforeEach(async( () => {

        TestBed.resetTestEnvironment();

        TestBed.initTestEnvironment(BrowserDynamicTestingModule, platformBrowserDynamicTesting());
        TestBed.configureTestingModule({

            imports: [

                RouterTestingModule

            ],
            providers: [],

            declarations: [

                LoginComponent

            ],

            schemas: [

                NO_ERRORS_SCHEMA]

        }).compileComponents();

    }));

    it('Should create the app', async( () => {
        const fixture = TestBed.createComponent(LoginComponent);
        const app = fixture.debugElement.componentInstance;
        expect(app).toBeTruthy();
    }));
});

A: You are using the BrowserDynamicTestingModule which is not valid for {N}. You are suppose to use NativeScriptTestingModule form nativescript-angular/testing.


text:
Q: How does subscribeOn work I have some doubts regarding the working on the subscribeOn operator. I read some article regarding this.
The observeOn is quite easy to understand, it changes only the downstram, and change affects to all the downstream.
But as told in the article subscribeOn can be put in any place in the stream because it affects only the time of subscription.:
To understand this , I did a samlpe and tried logging the thread at each point of time.
           Observable.just("Hello")
                    .map(s -> {
                        Log.d(TAG, s + " in " + Thread.currentThread());
                        return 1;
                    })
                    .subscribeOn(Schedulers.newThread())
                    .map(integer -> {
                        Log.d(TAG, integer + " in " + Thread.currentThread());
                        return true;
                    })
                    .map(aBoolean -> {
                        Log.d(TAG, aBoolean + " in " + Thread.currentThread());
                        return 11.0;
                    })
                    .subscribeOn(Schedulers.computation())
                    .subscribe(aDouble -> {
                        Log.d(TAG, "accept in " + Thread.currentThread());
                        Log.d(TAG, "accept: " + aDouble);
                    });

The result is
                 Hello in Thread[RxNewThreadScheduler-1,5,main]
                 1 in Thread[RxNewThreadScheduler-1,5,main]
                 true in Thread[RxNewThreadScheduler-1,5,main]
                 accept in Thread[RxNewThreadScheduler-1,5,main]
                 accept: 11.0

Here twice I'm applying subscribeOn, but everytime the first added one seem to be applied throughout the stream.
Can anyone please explain in simple words how does it actually work, since I'm a beginner and hard to digest this!
Thanks in advance

A: subscribeOn: If you have multiple subscribeOn then the first one takes effect. If you want to change the Scheduler on the stream after making a subscribeOn, then take a look at observeOn
observeOn: It changes the Scheduler going downstream.
For example:
just("Some String") // Computation
  .subscribeOn(Schedulers.computation()) // it changes scheduler to computation beginning from source to observer.
  .map(str -> str.length()) // Computation
  .observeOn(Schedulers.io) //change the scheduler from here till the observer
  .map(length -> 2 * length) // io
  .subscribe(number -> Log.d("", "Number " + number));// io


text:
Q: Loose threader in LTO-5 SAS internal drive Once more I have a tape drive issue.
I started seeing lots and lots of hardware errors with our LTO-5 SAS drive within our Superloader 3 changer. The main upshot was that the drive would think a tape was loaded when it was not.  I can add specific error messages here later on.
To buy support for this hardware will be more expensive than buying a new drive, so before buying fresh new hardware, I figured I'd try to (carefully) fix this one, only performing tricky actions when I can find information that supports it. I opened up the drive.
I saw the following:

From reading, I've learned that the part that I'm pointing to is the threader, which is supposed to link up with the leader pin on the LTO cartridges, to take up the actual tape in the cartridge.
From my other changer, I've seen that when there is no tape loaded, the threader is supposed to go through the black plastic assembly at the top right, then down along the right edge, into a section below the greenish tab with '3003' printed on it.
I'll probably just buy a new tape drive but in the meantime, I was wondering if someone would know how I might get the threader through the way it originally was before the issue.


text:
Q: Suppress Python matplotlib deprecation warnings for GtkButton:image-spacing How do I fix or suppress the warning from the following code:
from matplotlib import pyplot as plt
import warnings
warnings.filterwarnings('ignore')

plt.clf()

Output:
(__main__.py:188073): Gtk-WARNING **: 19:37:54.366: Theme parsing error: gtk.css:3408:30: The style property GtkButton:image-spacing is deprecated and shouldn't be used anymore. It will be removed in a future version

Numerous StackOverflow answers say to use the warnings library, which I have applied as broadly as possible in the code without success. This is just a small example code. I make plt calls throughout my main code, so I'm looking for some broad suppression.
I'm using Matplotlib 3.1.1 on CentOS 7.6.


text:
Q: Is there any API to get the cost consumption details of an Azure Resource? I need to display the costing details of a particular Azure resource in ASP .NET MVC application. I tried using the APIs given in the following links: https://learn.microsoft.com/en-us/rest/api/consumption/budgets/list, https://learn.microsoft.com/en-us/rest/api/consumption/charges/list. I am getting error 404 as a result in one, even when the scope is right and in another I am getting code 200 ie success but it is not displaying any result. Please provide the correct APIs/way to display the code details in MVC application.

A:
Is there any API to get the cost consumption details of an Azure Resource?

*

*Only billing accounts, billing profiles, and pay-as-you-go subscriptions have access to invoices.

*If you are using Azure free subscription, then you don't have access to the Invoice details

*If you are using Azure pay-as-you-go Subscription, then you need to give few permissions to access the Invoice/Azure resource costs

*Before you can use the billing API's , we need to provide permissions in Azure portal  to the API's to access the Invoice data.

Navigate to Azure Portal => Cost Management + Billing=> Your Subscription => Invoices =>Access to invoice => Select On => Save.

*

*Now we can access Invoice data/billing details using API's


text:
Q: Can causal implication be formalised? In this post I want to ask about the implication used in mathematical proofs. Well, as a far as I know, in our known logical model that is used in mathematics, implications are not causal, and thus statements like "moon revolves round the earth implies dinosaurs don't exist" or "moon is made of green cheese implies Socrates is a man" are true. But these are formal implications, not causal ones. Now  let us look at mathematical proofs. For example suppose a simple proof that $4$ is even should run as follows:
\begin{align}4=2×2&\implies \text{there exists an integer}\ n=2\ \text{such that}\ 4=2n\\&\implies 4\ \text{is even}\end{align}
If we assume that the implications used are material conditionals, then we can introduce further steps like:
\begin{align}4=2×2&\implies \text{there exists an integer}\ n=2\ \text{such that}\ 4=2n\\&\implies \text{the earth goes round the sun}\\&\implies \text{the sun rises in the east}\\&\implies 4\ \text{is even}\end{align}
Doesn't look like a healthy proof right? The implications used in the first proof satisfy the conditions of the material conditional, but still some intuition goes in our mind regarding the causal relationships between the successive steps that prevents us from writing the unnecessary steps. My question is whether we can formalize and incorporate this notion of causality in our existing material condition.


text:
Q: How to change multiple str to float in a file and then average the total without getting errors? I am very new to coding so please elaborate and use examples to explain. I have a text file that has many numbers along with names and other str. I need to know how i can convert the numbers that are currently str into floats so i can calculate the average.
I have tried using the str as floats but i get error TypeError: unsupported operand type(s) for +: 'int' and 'str'
which is expected
i have also tried setting the str to float but it gives me
Traceback (most recent call last):
  File "C:\Users\leona\Desktop\School Work\moretesting.py", line 9, in
    average = sum(num1) / len(num1)
TypeError: 'float' object is not iterable
file = input("Enter a filename: ")

with open(file, "r") as f:

   next(f)

   for line in f:

       lines = line.split(",")

       num1 = float(lines[6])

       average = sum(num1) / len(num1)

       print(average)

The file has this inside (just a portion of the text file because its way to big but i just need to understand how to do this type of problem):
zip,eiaid,utility_name,state,service_type,ownership,comm_rate,ind_rate,res_rate
52346,9417,Interstate Power and Light Co,IA,Bundled,Investor Owned,0.0922343168969,0.0589686412318,0.130070934252
72424,814,Entergy Arkansas Inc,AR,Bundled,Investor Owned,0.0735129328027,0.0594501735324,0.0908957415387

Traceback (most recent call last):
  File "C:\Users\leona\Desktop\School Work\moretesting.py", line 9, in <module>
    average = sum(num1) / len(num1)
TypeError: 'float' object is not iterable

A: You can append the values in that column to a list and then get the average of the list as follows:
file = input("Enter a filename: ")

with open(file, "r") as f:

  next(f)
  num_list = []

  for line in f:
    lines = line.split(",")
    num_list.append(float(lines[6])

  average = sum(l) / float(len(l))
  print(average)


text:
Q: Python alternative to _winreg I am accessing a python script using jython and apparently the _winreg module is not supported. Are there any alternatives to this module? I am using jython 2.5.

A: You'll need to access the Windows registry via Java instead.


text:
Q: Is there are any way to get change first and last letter in a string in JS? I need make some width function. It take a string and must to return an arrive with changed letters. For example:
enter code here

 let word = 'letter'
 function(word) {
 // code here
 return var // {letter, etterl, tterle, terlet, erlett, rlette]

A: you can do this:

function permut(string) {
  if (string.length < 2) return string;

  const permutations = [];
  for (let i = 0; i < string.length; i++) {
    const char = string[i];

    if (string.indexOf(char) !== i) continue;

    const remainingString =
      string.slice(0, i) + string.slice(i + 1, string.length);

    for (const subPermutation of permut(remainingString))
      permutations.push(char + subPermutation);
  }
  return permutations;
}

console.log(permut("hello"));

A: You can easily achieve the result if you first split the string, and then loop over the character array.
All you have to do is to push the first character at the end of the array on every iteration.

let word = 'letter';

function getResult(word) {
  const wordArray = word.split('');
  const result = [];
  for (let i = 0; i < word.length; ++i) {
    result.push(wordArray.join(''));
    wordArray.push(wordArray.shift());
  }

  return result;
}

console.log(getResult(word));


text:
Q: URLConnection getContent() return null I use the following method to get a bitmap input stream:
    private InputStream getInputStream(String urlString) throws MalformedURLException, IOException {
    URL url = new URL(urlString);
    URLConnection connection;
    connection = url.openConnection();
    //connection.setUseCaches(true);
    Object response = connection.getContent();
    if (!(response instanceof InputStream))
        throw new IOException("URLConnection response is not instanceof InputStream");

    return (InputStream)response;
}

It works great on Android 2.3 (GalaxyS2) but on Android 2.2 (GalaxyS)
response = null.
The remote url is a bitmap.
Any ideas?

A: connection = url.openConnection();
connection.connect(); // <-- does it work if you add this line?
Object response = connection.getContent();


text:
Q: Text widget form and URL variables I have an HTML form that I dropped into my Wordpress text widget that connects to a third party service so I need the form variables to be exactly right for it to work. The form is using GET rather than POST.
A select box I have is as follows:
<select name="a_mlsAreaMajor[]" id="IDX-a_mlsAreaMajor">
    <option value="DALLAS NORTHEAST (18)">Dallas Northeast (18)</option>
</select>

In the URL after submitting the form, it shows something like this

a_mlsAreaMajor%5B%5D=DALLAS+NORTHEAST+%2818%29

I need the URL to read

a_mlsAreaMajor[]=DALLAS+NORTHEAST+(18)

instead.. in order for the third party to process the form correctly.
What am I doing wrong here?


text:
Q: Why is FindOne where id using typeorm and mongodb doesn't work? I am using typeorm with MongoDB. When I am searching for a document by Id with this syntax
const manager = getMongoManager(); const user = await manager.findOne(User, {userId}); I got undefined result and when I use const manager = getMongoManager(); const user = await manager.findOne(User, {}); I got the result with userId expected in the first syntax.
Besides the same syntax works fine with any other criteria other than Id.
The declaration of the Id in the model is: @ObjectIdColumn({ name: '_id' }) @IsNotEmpty() public userId: ObjectID;
For now, I have only one user in the database with the userId that I search for.
Where could be the problem? And how to resolve that?

A: When you do await manager.findOne(User, {}); You are basically selecting the first entry in your User collection, that's why you get the user you were expecting.
What you need to do is query by the _id field if you have it, or create a custom field to query by, for example:
@Entity()
export class UserEntity
{
  @ObjectIdColumn()
  _id: string;

  @PrimaryColumn()
  id: string;

  @Column()
  public name: string;
}

This way you can do a query like this await manager.findOne(User, { _id: <your _id>});
Or await manager.findOne(User, { id: <your id> });


text:
Q: Trying to access style info by StaticResource through ResourceDictionary with x:Key I'm having a problem with WPF resources accessing external style info in an external ResourceDictionary through StaticResources.
I have inherited a bunch of code that uses a lot of DynamicResources in their WPF to get style information from a Shared.xaml. I would rather them be StaticResources so that the designer view becomes useful. I discovered that I can add a ResourceDictionary in the .Resources of the thing, which works fine UNLESS there is already a .Resources using in the WPF. In that case I am told I need to add a x:Key to my ResourceDictionary. I do that except that now I don't know how to use that key to find the resources statically.
Minimal example:
<UserControl x:Class="myClass"
  ...>
  <UserControl.Resources>
    <ResourceDictionary x:Key="Shared.xaml" Source="/ExteralResource;component/Shared.xaml"/>
    <BooleanToVisibilityConverst x:Key="BoolToVis">
  </UserControl.Resources>

  <TextBlock Background="{StaticResource BrushFromSharedXAML}" /> <!-- Never finds BrushSharedXAML -->
</UserControl>

Any ideas?

A: <UserControl.Resources>
  <ResourceDictionary>
      <ResourceDictionary.MergedDictionaries>
          <ResourceDictionary Source="/ExteralResource;component/Shared.xaml"/>
      </ResourceDictionary.MergedDictionaries>
      <BooleanToVisibilityConverst x:Key="BoolToVis">
  </ResourceDictionary>
</UserControl.Resources>

Though, be aware that doing this in each usercontrol is going to eat a lot of RAM, because you're actually creating a new instance of the Shared.xaml ResourceDictionary for every instance of this control at runtime. You should take a look at SharedResourceDictionary


text:
Q: How to trigger event when a widget reaches certain position of the screen? I want an event to be triggered when a widget is at a certain position of the screen. Let's say for example that we have a Container Widget that is still not visible. It is at a certain position of a scrollable Scaffold whose body's height is enough to have to be scrolled. We start to scroll and when the widget is visible and, let's say, reaches the middle of the screen, this triggers the event. In other words, the event should be triggered only if the Widget is at a certain position. Maybe something similar could be achieved with a ScrollController but I wonder if there could be other approaches for this.

A: So I started a little research and I found that what I wanted can be achieved with RenderBox objects. By using them you're able to get the size (of type Size) or position (of type Offset). Once you have them it is very easy to trigger an event. In this case I made a simple example, where I print a statement only if the position of a Container surpasses a given Offset on y axis (say, a specific percentage of the height of the screen, which you can obtain with MediaQuery.of(context).size.height). I set my limit to a 75% of the screen's height. The event is called when pressing the FloatingActionButton. If you'll test it, scroll a little, then press the button. Scroll again, and check it again and so on. You'll see that the event triggers when the limit is surpassed.
I achieved this with help of the following article: https://medium.com/@diegoveloper/flutter-widget-size-and-position-b0a9ffed9407
Here my example:
import 'package:flutter/material.dart';

class Example extends StatefulWidget {
  @override
  _ExampleState createState() => _ExampleState();
}

class _ExampleState extends State<Example> {
  GlobalKey _keyRed = GlobalKey();
  GlobalKey _keyPurple = GlobalKey();
  GlobalKey _keyGreen = GlobalKey();
  Offset positionGreen;

  _getSizes(){
    RenderBox renderBoxRed = _keyRed.currentContext.findRenderObject();
    Size sizeRed = renderBoxRed.size;
    print("red size is: $sizeRed");

    RenderBox renderBoxPurple = _keyRed.currentContext.findRenderObject();
    Size sizePurple = renderBoxPurple.size;
    print("purple size is: $sizePurple");

    RenderBox renderBoxGreen = _keyGreen.currentContext.findRenderObject();
    Size sizeGreen = renderBoxGreen.size;
    print("green size is: $sizeGreen");
  }

  _getPositions(){
    final RenderBox renderBoxRed = _keyRed.currentContext.findRenderObject();
    final positionRed = renderBoxRed.localToGlobal(Offset.zero);
    print("red position is: $positionRed");

    final RenderBox renderBoxPurple = _keyPurple.currentContext.findRenderObject();
    final positionPurple = renderBoxPurple.localToGlobal(Offset.zero);
    print("purple position is: $positionPurple");

    final RenderBox renderBoxGreen = _keyGreen.currentContext.findRenderObject();
    positionGreen = renderBoxGreen.localToGlobal(Offset.zero);
    print("green position is: $positionGreen");
  }

  @override
  Widget build(BuildContext context) {
    double limit = MediaQuery.of(context).size.height*.75;

    return Scaffold(
      floatingActionButtonLocation: FloatingActionButtonLocation.centerFloat,
      floatingActionButton: FloatingActionButton(
        backgroundColor: Colors.orange,
        onPressed: (){
          _getSizes();
          _getPositions();

          print("\npositionGreen in dy is ${positionGreen.dy} and limit is $limit");

          if(positionGreen.dy > limit){
            print("screen resizes");
          } else {
            print("screen doesn't resize");
          }

        },
      ),
      body: SingleChildScrollView(
        child: Column(
          children: [
            Container(
              height: 400,
              key: _keyRed,
            color: Colors.red,
            ),
            Container(
              height: 600,
              key: _keyPurple,
              color: Colors.purple,
            ),
            Container(
              height: 800,
              key: _keyGreen,
              color: Colors.green,
            ),
          ],
        ),
      ),
    );
  }
}


text:
Q: Print html and excel files with Print Service API I am using java print service API to print documents (pdf, jpg, excel and html). I am able to print pdf and images but I am unable to print html and excel.
public class Demo {

public static void main(String[] args) throws IOException, PrinterException {
    FileInputStream psStream = null;
    String filename = null;
     filename = "I:/abc.html";
        psStream = new FileInputStream(filename);
    DocFlavor psInFormat = DocFlavor.INPUT_STREAM.AUTOSENSE;
    Doc myDoc = new SimpleDoc(psStream, psInFormat, null);
    PrintRequestAttributeSet aset = new HashPrintRequestAttributeSet();

    PrintService myPrinter = PrintServiceLookup.lookupDefaultPrintService();

    if (myPrinter != null) {
        DocPrintJob job = myPrinter.createPrintJob();
        try {
        job.print(myDoc, aset);

        } catch (Exception pe) {pe.printStackTrace();}
    } else {
        System.out.println("no printer services found");
    }

}

}
I have searched on Internet and tried setting the Doc Flavor as:
DocFlavor.INPUT_STREAM.AUTOSENSE

But I am getting blank output.
Can I get some example on how to print excel and html using java print API?


text:
Q: how to request mongoDB nodejs with javascript client side app imagine in a left hand the following server #1 (in our Datacenter)
Mongodb
nodejs
Some Nodejs script that read and write to MongoDB
in the Right hand a nginx/apache server #2
a web app for displaying mongodb and send information to mongo
how can i , with javascript/Jquery on server 2
request the server #1, and get the Json response
the purpose is to build a web app that read & write to mongo
using JS/jquery on a "client side" server2
i was using a REst API service since now, but due to lot of bugs/changes,  i want to be independant of it..
how can i simply write a nodejs service that allow me to send get/put/delete etc.. to nodejs Script and ge t the json back ?
thanks for any help

A: On the server with MongoDB, you can write a basic NodeJS/Express application that reads from Mongo and outputs JSON data. For example, say you have a users collection in your database:
var MongoClient = require('mongodb').MongoClient
var express = require('express');
var app = express();
var bodyParser = require('body-parser');

app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());

// Connection URL
var url = 'mongodb://localhost:27017/yourDatabaseName';

app.get('/users', function(req, res) {
    var getUsers = function(db, callback) {
        var collection = db.collection('users');
        collection.find({}, {password: 0}).toArray(function(err, docs) {
            callback(docs);
        });
    };
    MongoClient.connect(url, function(err, db) {
        getUsers(db, function(docs) {
            res.json(docs);
        });
    });
});

app.listen(3000, function () {
    console.log('Example app listening on port 3000!');
});

Then on server #2 you can use jQuery's getJSON() method to access that data from the url server1's IP:3000/users like so:
$.getJSON( "server1IP:3000/users", function( data ) {
  var items = [];
  $.each( data, function( key, val ) {
    items.push( "
" + val + "
" );
  });

  $( "
", {
    "class": "my-new-list",
    html: items.join( "" )
  }).appendTo( "body" );
});

As for the other CRUD operations like PUT, DELETE, etc. you can use MongoDB's native NodeJS driver as I did in this example or an ORM like Mongoose


text:
Q: Vector of 16bit Integers I would like to define a vector $\mathbf{s} = [s_1, \ldots, s_N]^{\operatorname{T}}$ with length $N$ where each element is a 16bit two's complement signed integer (in C one would write int16_t si = 0; for a scalar 16bit integer and int16_t s[N] = {0}; for a vector).
A single element is thus $s_i \in \{x\in\mathbb{Z} \mid -2^{K-1} \leq x \leq 2^{K-1}-1\} = \{x\in\mathbb{Z} \mid -32768 \leq x \leq 32767\}$ with $K=16$ being the number of bits.
What I would write for the vector is $\mathbf{s} \in \{x\in\mathbb{Z} \mid -2^{K-1} \leq x \leq 2^{K-1}-1\}^N$.
But is there a more elegant way?
How do I, in an elegant and compact way, define a vector $\mathbf{a} \in A^N$, where A is set defined by me?


text:
Q: Linear transformation of normal distribution Not sure if "linear transformation" is the correct terminology, but...
Let $X$ be a random variable with a normal distribution $f(x)$ with mean $\mu_{X}$ and standard deviation $\sigma_{X}$:
$$f(x) = \frac{1}{\sigma_{X}\sqrt{\tau}}\exp{\left[\frac{-1}{2}\left(\frac{x-\mu_{X}}{\sigma_{X}}\right)^2\right]}$$
(Here, $\tau=2\pi$)
Let $Y$ be a random variable defined by the linear transformation
$$Y = u(X) = aX+b$$
Let $v(y) = u^{-1}(y) = \frac{y-b}{a}$. Then $v^\prime(y) = \frac{1}{a}$.
Prove: $Y$ is normally distributed, with density function
$$g(y)=f\bigl(v(y)\bigr)\,\bigl|v^\prime(y)\bigr|$$
$$= \frac{1}{\sigma_{X}\sqrt{\tau}}\exp{\left[\frac{-1}{2}\left(\frac{\frac{y-b}{a}-\mu_{X}}{\sigma_{X}}\right)^2\right]}\,\left|\frac{1}{a}\right|$$
$$= \frac{1}{\left|a\right|\sigma_{X}\sqrt{\tau}}\exp{\left[\frac{-1}{2}\left(\frac{y-(a\mu_{X}+b)}{a\sigma_{X}}\right)^2\right]}$$
with mean $\mu_{Y} = a\mu_{X}+b$ and standard deviation $\sigma_{Y} = \left|a\right|\sigma_{X}$.

A: If $X$ is a normally distributed random variable, then so is $g(X) = mX+b$.  But the proposition as you stated it is wrong.
A proof can go like this (first assume $m>0$, then mutatis mutandis):
$$
\begin{align}
F_{g(X)}(y) & = \Pr(g(X) \le y) = \Pr(mX+b \le y) = \Pr\left(X \le \frac{y-b}{m}\right) \\[12pt]
& = \int_{-\infty}^{(y-b)/m} \frac{1}{\sqrt{2\pi}}\cdot\exp\left(\frac{-(x-\mu)^2}{2\sigma^2}\right)\,\frac{dx}{\sigma} ;
\end{align}
$$
therefore
$$
f_{g(X)}(y) = \frac{d}{dy} \int\cdots\cdots\text{(ditto)}\cdots\cdots\quad = \frac{1}{\sqrt{2\pi}} \exp \left( \frac{-\left(\frac{y-b}{m}-\mu\right)^2}{2\sigma^2}\right)\frac{1}{\sigma}\cdot\frac{d}{dy}\,\frac{y-b}{m},
$$
and then simplify.


text:
Q: Python can't find my file because of a directory error So I have a function that scrapes instagram data and stores the number of likes to a dictionary.I think I have the function set up right but when I try to run a print statement, I keep getting a error that it can't find the file I'm looking for to run through the function.
This is the code I'm using to mount my google drive and set the directory to store my json files. I verified that this is all correct in my drive.
# Mount data location. Do not edit this cell except as indicated.

# Be sure you have a folder in the root of your Google Drive called APRD6342/Data.
# Data files for the course should be uploaded to that folder.
from pathlib import Path
try:
    from google.colab import drive
    drive.mount('/content/drive')
    datadir = Path('drive/My Drive/APRD6342/Data') # you may edit this location ...
except ModuleNotFoundError:
    datadir = Path('../../Data') # ... but don't change this!!!

INSTAGRAM_DIR = datadir / 'instagram'

Here is my function:
def engagement(filename, follower_count):
    """Return the brand post engagement for the Instagram metadata file,
    filename, given follower_count as the number of Instagram followers for
    the brand.

    Returns a decimal engagement rate rounded to 4 decimal places. Python's
    standard `round` function should be used. E.g.:

    >>> engagement('instagram/volvocars.json', volvocars_follower_count)
    0.0125
    """
    with open(datadir / filename) as f:
        for line in f: #for each line in the file
            line_object = json.loads(line)
            likes = line_object["GraphImages"]["edge_media_preview_like"]["count"] #find count

            if num in likes > 1:
                engagement.append(i) #add count to engagement
            comments = filename["GraphImages"]["edge_media_to_comment"]["count"] #find other count
            if num in comments > 1:
                engagement.append(i) #add count
            engage_perc = sum(engagement)/follower_count #sum all counts and divide by the number of followers
    return engage_perc

here is the print statement I'm trying to run and the error:
print('Honda:',
    as_percent(engagement(INSTAGRAM_DIR / 'honda.json', honda_follower_count)))

---> 12     with open(datadir / filename) as f:
     13         for line in f: #for each line in the file
     14             line_object = json.loads(line)

FileNotFoundError: [Errno 2] No such file or directory: 'drive/My Drive/APRD6342/Data/drive/My Drive/APRD6342/Data/instagram/honda.json'

I've ran that mounting code before fine but for some reason my directory is nesting itself or something. Thanks!

A: when you call the function with
print('Honda:',
    as_percent(engagement(INSTAGRAM_DIR / 'honda.json', honda_follower_count)))

you supply the full path, but then in the function, the path is added again
 with open(datadir / filename) as f:

Pass just the subfolder instagram and the file name. Note the docstring - they supply 'instagram/volvocars.json', so you need to supply 'instagram/honda.json'

A: So was able to figure out a way to not have to use a jsonl file but just json. Was mixing up some syntax.
def engagement(filename, follower_count):
    """Return the brand post engagement for the Instagram metadata file,
    filename, given follower_count as the number of Instagram followers for
    the brand.

    Returns a decimal engagement rate rounded to 4 decimal places. Python's
    standard `round` function should be used. E.g.:

    >>> engagement('instagram/volvocars.json', volvocars_follower_count)
    0.0125
    """
    engagement = [] #set empty list for like counts
    data = filename #store filename to variable
    with open(data) as f: #save open file as outfile
        parse = json.load(f)
        for n in range(0,200):
            likes = parse["GraphImages"][n]["edge_media_preview_like"]["count"] #find count
            if likes > 1:
                    engagement.append(likes) #add count to engagement
            comments = parse["GraphImages"][n]["edge_media_to_comment"]["count"] #find other count
            if comments > 1:
                    engagement.append(comments) #add count
            engage_perc = (sum(engagement)/len(range(0,200)))/follower_count #sum all counts and divide by the number of followers
        return round(engage_perc,4)


text:
Q: A specific sort of Objects according to a parameter within *ngFor My issue is caused by a lack in experience with angular2 and HTML5 so dont blame me please ;)
I have some food categories like this:
Here is their HTML :

  <md-card>
    <md-card-title-group>
      <md-card-title layout="row" layout-align="end center">

          {{item.name}}

           {{'ref' | translate}}: {{item.internal_reference | truncate : 22}}

{{item.description | truncate : 100}}

            {{item.item_type || 'no type for this '}} item

          {{'notAvailable' | translate}}

          {{item.price | currency: item.official_currency:true:'1.2-3'}}

      </md-card-title>
    </md-card-title-group>
  </md-card>

Each one of these food types belongs to a category (illustrated as an object parameter in each food object), So I want that the View of foods will be ordered by categories like this one:
I added these lines within the *ngFor loop:

                  {{item.category.name}}

But, -and logically-, it appeared like this :

Any Help or guidance or ideas Please ?

A: Like @Sakuto said in the comments, this is not related to HTML or Angular, its a problem in your logic.
You are trying to create a list by iterating with *ngFor through all the items.
What you want to achieve is to create different lists by category.
You have 2 solutions, or you change your data to be category driven instead of item driven, or you group your items by category.
So if you change your data, your object would look something like this:
interface FoodList {
  categories: Category[];
}
interface Category {
  name: string;
  items: FoodItem[];
}
interface FoodItem {
  //your item
}

And then on the list you do something like this:

{{category.name}}

      {{item.name}}

If you aren't able to change your data model, just group your items by category before "printing" it.

A: Your problem is not related to Angular but it's directly related to an algorithm problem, what you want can be done in two differents way:

*

*Retrieve the products ordered bt the category name, then just check if the previous category name is different than the current, if yes, print the category name, otherwise just print the product. Here's an explanation in pseudo code.
var currentCategoryName = "";
FOR product in products
    IF product.categoryName != currentCategoryName
        WRITE product.categoryName
    ENDIF

    WRITE product
ENDFOR

*Second way, if you can't order them or do not want to, you could just create a new collection where each category would have its element.
var yourList = [];

FOR product in products
    yourList[product.categoryName][] = product
ENDFOR

// Display
FOR category in yourList
    WRITE category[0].categoryName

    FOR product in category
        WRITE product
    ENDFOR
ENDFOR


text:
Q: MySQL query returns results without order I am trying to organize a queries output in 'orderindex' order to display the list correctly in my php functions loop with mysql.
Currently my SQL query is this:
SELECT * FROM (SELECT NewCustInfo.Driver, SUBSTRING_INDEX(NewCustInfo.Driver, '/', -1) AS orderindex, SUBSTRING_INDEX(NewCustInfo.Driver, '/', 1) AS thedriver, NewCustInfo.id,NewCustInfo.Accomplished
 FROM NewCustInfo WHERE NewCustInfo.Driver REGEXP 'Test123/' AND NewCustInfo.Accomplished='0' ORDER BY orderindex DESC) DUMMY_ALIAS1
UNION ALL
SELECT * FROM (SELECT PickupSlip.Driver, SUBSTRING_INDEX(PickupSlip.Driver, '/', -1) AS orderindex, SUBSTRING_INDEX(PickupSlip.Driver, '/', 1) AS thedriver, PickupSlip.id,PickupSlip.Accomplished
 FROM PickupSlip WHERE PickupSlip.Driver REGEXP 'Test123/' AND PickupSlip.Accomplished='0' ORDER BY orderindex DESC) DUMMY_ALIAS2
UNION ALL
SELECT * FROM (SELECT DeliverySlip.Driver, SUBSTRING_INDEX(DeliverySlip.Driver, '/', -1) AS orderindex, SUBSTRING_INDEX(DeliverySlip.Driver, '/', 1) AS thedriver, DeliverySlip.id,DeliverySlip.Accomplished
 FROM DeliverySlip WHERE DeliverySlip.Driver REGEXP 'Test123/' AND DeliverySlip.Accomplished='0' ORDER BY orderindex DESC) DUMMY_ALIAS3

I realize this is ordering by SELECT, rather than the entire query as a whole. Is there a way to order the full results of all 3 SELECTS?
e.g. turn the 3 selects into a variable, then somehow concatenate them into a single list, and then display with ORDER BY?

A: As per mysql's syntax on UNION, place an order by clause after the last select:
(SELECT a FROM t1 WHERE a=10 AND B=1)
UNION
(SELECT a FROM t2 WHERE a=11 AND B=2)
ORDER BY a


text:
Q: different result once square root is added inside tacit Very new to J. I love it but still far from fluent in it.
I have managed to hit an issue and I don't know why it is happening. If somebody could please explain why this is occuring I could learn more about this straight-to-the-point language.
Basically I'm doing difference (-) then squared (*:) then sum (+/) then want to take the square root (%:).
Now the sum square error part ( (+/@:*:@:-) ) works fine:
   1 2 3 4 5 (+/@:*:@:-) 2 2 2 2 2
15

Then I can get the square root this way (just add %: to left):
   %: 1 2 3 4 5 (+/@:*:@:-) 2 2 2 2 2
3.87298

But when I add square root to left of the atco (tacit?) part in the middle it doesn't give me the right result:
   1 2 3 4 5 (%:@:+/@:*:@:-) 2 2 2 2 2
1.57001

It instead returns 1.57001 instead of 3.87298.
My understanding is all I have done is add a 'then do square root' but obviously I am wrong. But I don't understand why.
When I dissect:
require 'debug/dissect'
dissect '1 2 3 4 5 (%:@:+/@:*:@:-) 2 2 2 2 2'

I see diff (-) and square (*:) are in their own dissect boxes. But then the last box combines sum (+/) and square root (%:) together, showing %:@:+/ . Not a separate box for +/ and then %: .
As I said I am new to J and am struggling to understand why this is occuring here.
I've tried changing to &, &: and @ instead but as expected that didn't fix this issue.
It doesn't appear to be due to some composition limit either since this works fine (has many more atco's combined):
   (>:@:>:@:>:@:>:@:>:@:>:@:>:@:>:@:>:) 2 2 2
11 11 11

Thank you

A: The issue that you are encountering is that
(%:@:+/@:*:@:-)

is being evaluated as
   1 2 3 4 5 ((%:@:+)/@:*:@:-) 2 2 2 2 2
1.57001

and not
   1 2 3 4 5 %:@:(+/@:*:@:-) 2 2 2 2 2
3.87298

because of the way that conjunctions take as much of the left operand as possible. This means that your partial result from *:@:- is being processed by %:@:+/ when you want %: to apply to the result of +/@:*:@:-
Since you are just starting your journey with J, this may be a bit advanced, but at some point you may want to read the tacit programming section of J for C programmers by Henry Rich. It has a very good explanation about how J sentences are parsed. Parenthesis are your friend when you want to change the order of execution. https://www.jsoftware.com/help/jforc/contents.htm#_Toc191734581
Edit: As @Eelvex points out in the comment below the break actually occurs at (+/), but the result is the same because of the way that conjunctions are evaluated left to right.

A: You are trying to form a dyadic verb for the expression:
%: +/ *: x - y  NB. which we can write as

f g h x - y     NB. if we define:

f =: %:
g =: +/
h =: *:

f g h x - y
3.87298

One way of making this a dyadic verb is to apply @: everywhere:
x (f@:g@:h@:-) y
3.87298

x (%: @: (+/) @: *: @: -) y
3.87298

A more idiomatic way of doing it uses under (&.) which inverses a verb after applying another:
f &.: g  y             NB. expands to
(g-inverse) f g y

g &.: h (x - y)
3.87298

x ( g &.: h @: -) y
3.87298

NB. or if you prefer monadic verbs:
(g &.: h @: -/) x,: y


text:
Q: C++ Template Inheritance Issues (Warnings and Errors) I'm trying to mimic the .Net implementation of a generic List in C++.
I've fleshed out the various interfaces as purely virtual abstract classes as follows:
template <typename T>
class ICollection {

public:
    virtual void Add(T item) = 0;
    virtual void Clear(void) = 0;
    virtual bool Contains(T item) = 0;
    virtual void Remove(T item) = 0;

    virtual int32_t Count(void) const = 0;

};

template <typename T>
class IList : public ICollection<T> {

public:
    virtual T Item(int32_t index) = 0;
    virtual int32_t IndexOf(T item) = 0;
    virtual void Insert(int32_t index, T item) = 0;
    virtual void RemoveAt(int32_t index) = 0;

};

Now when I attempt to implement my main List class as follows:
template <typename T>
class List : public IList<T>, public ICollection<T> {

public:
    List(void);
    List(int32_ capacity);

    // ICollection<T>
    void Add(T item);
    // other functions from ICollection

    // IList<T>
    T Item(int32_t index);
    // other functions from IList

    void AddRange(IList<T> items);

private:
    typedef vector<T> ListType;

    ListType *m_pList;
};

template <typename T>
List<T>::List(void) {
    m_pList = new ListType();
}

template <typename T>
void List<T>::Insert(uint32_t index, T item) {
    // Insert an entry into the list at the specified offset
    m_list->insert(index, item);
}

// Implementation of other functions here...

As soon as I try to use the List<T> class as follows:
List<int32_t> myList;

A warning occurs saying:
In instantiation of 'class List<long int>':
    required from here
warning: direct base 'ICollection<long int>' inaccessible in 'List<long int>' due to ambiguity [enabled by default]

class List : public IList<T>, public ICollection<T> {
       ^

Followed by the following error:
In instantiation of 'void List<T>::Insert(uint32_t, T) [with T = long int; uint32_t = long unsigned int]':
    required from here
error: no matching function for call to 'std::vector<long int, std::allocator<long int> >::insert(uint32_t&, long int&)'

m_list->insert(index, item);
^

note: std::vector<_Tp, _Alloc>::iterator std::vector<_Tp, _Alloc>::insert(std::vector<_Tp, _Alloc>::iterator, const value_type&) [with _Tp = long int; _Alloc = std::allocator<long int>; std::vector<_Tp, _Alloc>::iterator = __gnu_cxx::__normal_iterator<long int*, std::vector<long int, std::allocator<long int> > >; typename std::_Vector_base<_Tp, _Alloc>::pointer = long int*; std::vector<_Tp, _Alloc>::value_type = long int]

 vector<_Tp, _Alloc>::
 ^

 note:   no known conversion for argument 1 from 'uint32_t {aka long unsigned int}' to 'std::vector<long int, std::allocator<long int> >::iterator {aka __gnu_cxx::__normal_iterator<long int*, std::vector<long int, std::allocator<long int> > >}'

If I modify the declaration of the List<T> class so as to remove the IList<T> and ICollection<T> abstract classes, no errors are generated.
I'm guessing that the way in which I'm using the templated base classes is not correct in this instance.

A: This issue is not directly related to templates.
class A {
    public void f() {}
};

class B : public A {};

class C : public A, public B {};

int main() {
    C c;
    c.f(); // Error: ambiguous base class!
}

When you inherit a class, the derived class contains an object for the base class, called a base class subobject.  So in my example, every B contains an A.  And every C contains an A and a B.  The problem is, when I try to call f as a member of C, the compiler needs to find the A subobject to call it on.  But there are two subobjects with that type!  One is directly inherited by C, and the other is inside the inherited B subobject.  So the compiler can't figure out what I mean.
The solution in this case is to just not inherit a class twice.  In my example, C doesn't need to directly inherit A, since inheriting B will provide it with an indirect A subobject and access to all its members.
In your case, List<T> doesn't need to inherit ICollection<T> directly.  It's enough to just derive from IList<T>.
(In other cases, it can be useful to use "virtual inheritance", which tells the compiler "only create one base class subobject for this type, even if I indirectly inherit it more than once in some derived class". But that might be overkill for your code as it stands.)


text:
Q: React FullCalendar - can't get dateClick to work on v5 I'm using FullCalendar version 5.10.1 and I can't get dateClick to fire despite having interaction plugin
export default function MainCalendar() {

  function dateSelectHandler(info) {
    console.log(info);
  }

  return (
     <div>
       <FullCalendar
        dateClick={dateSelectHandler}
        plugins={[dayGridPlugin, timeGridPlugin, interactionPlugin]} />
     </div>
   );
}

package.json:
    "@fullcalendar/core": "^5.10.1",
    "@fullcalendar/daygrid": "^5.10.1",
    "@fullcalendar/interaction": "^5.10.1",
    "@fullcalendar/react": "^5.10.1",
    "@fullcalendar/timegrid": "^5.10.1",

I did managed to get it to work on v4 so I really don't understand what am I doing wrong here


text:
Q: Deserializing xml returns zero elements This is my xml:
<?xml version="1.0"?>
<orders>
  <order>
    <customer_id>5675757</customer_id>
    <order_code>6456</order_code>
    <products>
      <product>
        <product_item_code>577868</product_item_code>
        <product_item_amount>22</product_item_amount>
      </product>
    </products>
  </order>
</orders>

And this is my class:
[XmlRoot(ElementName = "orders")]
public class Orders
{
    public List<OrderModel> OrdersList { get; set; }
}

[XmlRoot(ElementName = "order")]
public class OrderModel
{
    [XmlElement(ElementName = "customer_id")]
    public string CustomerId { get; set; }

    [XmlElement(ElementName = "order_code")]
    public string OrderCode { get; set; }

    [XmlElement(ElementName = "products")]
    public List<Product> products { get; set; }
}

[XmlRoot(ElementName = "product")]
public class Product
{
    [XmlElement(ElementName = "product_item_code")]
    public string product_item_code { get; set; }

    [XmlElement(ElementName = "product_item_amount")]
    public string product_item_amount { get; set; }
}

And this is my code:
using (FileStream fileStream = new FileStream(filePath, FileMode.Open))
{
    var serializer = new XmlSerializer(typeof(Orders));
    var orders = (Orders)serializer.Deserialize(fileStream);
}

But it returns 0 elements. I know I am missing something obvious but I don't know what.

A: Change you class Orders and OrderModel:
[XmlRoot(ElementName = "orders")]
public class Orders
{
    [XmlElement(ElementName = "order")]
    public List<OrderModel> OrdersList { get; set; }
}

[XmlRoot(ElementName = "order")]
public class OrderModel
{
    [XmlElement(ElementName = "customer_id")]
    public string CustomerId { get; set; }

    [XmlElement(ElementName = "order_code")]
    public string OrderCode { get; set; }

    [XmlArray(ElementName = "products")]
    [XmlArrayItem(ElementName = "product")]
    public List<Product> products { get; set; }
}

Then it should work

A: Modify your classes as below and it will work.
[XmlRoot(ElementName = "orders")]
public class Orders
{
    [XmlElement(ElementName = "order")]
    public List<OrderModel> OrdersList { get; set; }
}

public class OrderModel
{
    [XmlElement(ElementName = "customer_id")]
    public string CustomerId { get; set; }

    [XmlElement(ElementName = "order_code")]
    public string OrderCode { get; set; }

    [XmlArray(ElementName = "products")]
    [XmlArrayItem(ElementName = "product")]
    public List<Product> products { get; set; }
}

public class Product
{
    [XmlElement(ElementName = "product_item_code")]
    public string product_item_code { get; set; }

    [XmlElement(ElementName = "product_item_amount")]
    public string product_item_amount { get; set; }
}


text:
Q: How to add a new variant to MUI's default typography (TypeScript) This question rose when I was trying out the MUI official instruction here.

*

*in file newTheme.ts, customize the primary color, and add a  new variant type post:

import { createTheme } from "@mui/material";

const newTheme = createTheme({
  palette: {
    primary: {
      main: "#f00" // red
    }
  },

  // uncommenting caused compiler error:
  // Type '{ poster: { color: string; }; }' is not assignable to type 'TypographyOptions | ((palette: Palette) => TypographyOptions) | undefined'.
  // Object literal may only specify known properties, and 'poster' does not exist in type 'TypographyOptions | ((palette: Palette) => TypographyOptions)'.ts(2322)
  // typography: {
  //   poster: {
  //     color: '#f00',
  //   },
  // },
});

export default newTheme;

*under the same directory, added a file newTheme.d.ts:

import { ThemeOptions } from '@mui/material/styles';

declare module '@mui/material/styles' {
  interface TypographyVariants {
    poster: React.CSSProperties;
  }

  // allow configuration using `createTheme`
  interface TypographyVariantsOptions {
    poster?: React.CSSProperties;
  }
}

// Update the Typography's variant prop options
declare module '@mui/material/Typography' {
  interface TypographyPropsVariantOverrides {
    poster: true;
  }
}

I have two problems:

*

*received the compiler error if I tried to add in the poster variant

*the primary color didn't turn red

here is codesandbox
What had I missed?

A: The code in your question has the following line:
import createMuiTheme from '@material-ui/core/styles/createMuiTheme';

This is importing the v4 version of createTheme. You shouldn't be mixing any @material-ui/* packages (v4) with @mui/* packages (v5). You should be using v5 for everything.
Here's a working example using a custom Typography variant:
demo.tsx
import * as React from "react";
import { createTheme, ThemeProvider } from "@mui/material/styles";
import Typography from "@mui/material/Typography";
import Button from "@mui/material/Button";

const theme = createTheme({
  typography: {
    subtitle1: {
      fontSize: 12
    },
    body1: {
      fontWeight: 500
    },
    button: {
      fontStyle: "italic"
    },
    poster: {
      color: "red"
    }
  }
});

export default function TypographyVariants() {
  return (
    <div>
      <ThemeProvider theme={theme}>
        <Typography variant="subtitle1">subtitle</Typography>
        <Typography variant="poster">poster</Typography>
        <Typography>body1</Typography>
        <Button>Button</Button>
      </ThemeProvider>
    </div>
  );
}

typography.d.ts
import "@mui/material/styles";
import "@mui/material/Typography";

declare module "@mui/material/styles" {
  interface TypographyVariants {
    poster: React.CSSProperties;
  }

  // allow configuration using `createTheme`
  interface TypographyVariantsOptions {
    poster?: React.CSSProperties;
  }
}

// Update the Typography's variant prop options
declare module "@mui/material/Typography" {
  interface TypographyPropsVariantOverrides {
    poster: true;
  }
}


text:
Q: Crystal report viewer memory leak asp.net webforms I am working on ASP.NET webforms application and it is using Crystal report for report generation.
when the user clicks on a button (view invoice) , the application will open a pop up window and in that crystal report viewer opens along with the data.
The problem i am facing is that when the user close the pop up screen window (directly) then crystal report object is not disposed and IIS is giving out of memory exception due to CR print limit.
Please advise how can force the browser to dispose the CR objects when the user closes the pop up window.


text:
Q: How can I get the last build date of a .NET-assembly? I put in my project:
System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString() & " - " &
File.GetLastWriteTime(System.Reflection.Assembly.GetExecutingAssembly().Location).ToShortDateString

But I don't understand exactly what this GetExecutingAssembly().Location is doing.
In my first machine, I Have 12/08/2022 (in my local machine i search the location its of my dll its : .dll in framework/temporary asp.net/..)
In my second machine, I have 13/08/2022.
I don't understand the difference between my 2 machines. Why does the .dll has a different date?
I tried to find a solution : my local machine is in CLR 4.0 and my machines are 2.0.
So I think my location is different between local and machines.
How could I have a common date despite my "clr" ?


text:
Q: Piping input to a shell command and keeping the created shell alive My overarching program is a shell script. This shell script calls a C program that I need to pipe input to, and ultimately the C program will create a shell.
However, when I pipe my input into the C program within the shell script
Do_Other_Stuff
./my_prog < file1

I can't get the shell to stay alive. Running just,
Do_Other_Stuff
./my_prog

works, as I have to input the stdin myself, and the shell correctly spawns when my_prog exits. I'm pretty sure wrapping up the ./my_prog call in a C program, and compiling and running that would work, but I'm curious as to whether there's a cleaner way with shell.
I've tried several combinations of using cat file1 | ./my_prog and using & in different situations, and haven't had any success.
Thanks!

A: Try:
cat file1 - | ./myprog

Many programs recognize the "filename" - to mean stdin.

A: Do you have access to the C program source code?  My guess is that the C program is using istty(0) to determine if stdin is coming from a terminal.  It probably only creates an interactive shell when that is the case.  Using stdin redirection, whether from a file or a pipe, means that istty(0) returns false.


text:
Q: React Router v5 - Global No match in Nested Routes I have two route 'stacks' in my React app:

*

*Public (Login, Register, 404, etc - /login, /register)

*Private (Dashboard - /app/*)

When user is logged, Dashboard routes stack is used where is next nested router to match sub pages.
When route does not exist I want to show global No Match (404) route from 'Public' stack, but when I have this at the end of router, empty Dashboard route is shown, not the last in setup:
App.tsx
return (
      <Router>
        <Switch>
          <Route path="/login" component={Login} exact />
          <Route path="/app/*" render={(props) => (isAuthenticated ? <Dashboard {...props} /> : <Redirect to="/login" />)} />
          <Route component={NotFound} />
        </Switch>
      </Router>
    );

Dashboard.tsx
export default function Dashboard(props: RouteComponentProps): ReactElement {
  return (

Dashboard

      <Switch>
        <Route path="/" component={Welcome} exact />
        <Route path="/create" component={CreateContent} />
        <Route path="/manage" component={ManageContent} />
      </Switch>

  );
}

So when I for example access /foobar I see content of component Dashboard without any other content.
I tried to make a redirect at the end of Dashboard, but this does not seems ok to me by design:

// End of Dashboard Switch
<Route render={() => <Redirect to="/404" />} />

// Changed NotFound route
<Route path="/404" component={NotFound} />

A: According to the documentation (https://reactrouter.com/web/guides/primary-components/route-matchers):

When a  is rendered, it searches through its children  elements to find one whose path matches the current URL. When it finds one, it renders that  and ignores all others.

Using Redirect block helps to solve the problem in this case. Add it to your Dashboard component:
export default function Dashboard(props: RouteComponentProps): ReactElement {
  return (

Dashboard

      <Switch>
        <Route path="/" component={Welcome} exact />
        <Route path="/create" component={CreateContent} />
        <Route path="/manage" component={ManageContent} />
        <Route><Redirect to="/404" /></Route>
      </Switch>

  );
}


text:
Q: PPTP network for server backend LAN? Here is our problem:
We have several webservers, which should be reached from public.
The database servers that store the data for the web apps on those webservers though shall not  have a public IP.
So, since I want to be able to connect to the SQL servers using ssh for example, and those servers need to talk with each other, I had this idea:
Internet
|
------------------
|                |
Webserver 1      Webserver 2     Database Server
|                |               |
-------------- vLAN --------------
|
PPTP
|
Workstation (my PC)

My idea was that I can connect to the vLAN using PPTP so that I have access to all servers in that LAN, but the database server remains unvisible to the public.
Is this infrastructure a good idea?

A: You just described a DMZ.  There's no need to vpn to get to this.  Simple routing from the internal network to the DMZ is normally sufficient.
A typical company network looks like this.
Internet -- firewall -- dmz
               |
      protected networks

The only time I would resort to a VPN is to access the protected networks or management services/ports on the dmz servers from somewhere on the internet....like from home.


text:
Q: Add record to ACF Field group programatically I've created a Field Group using ACF. All the fields are simple text fields. I now want some way to create a function that can add a record using php code. How is it possible to do that?

A: You can use:
update_field( 'my_field', 'my_value', $post_id );

Here is the source: https://www.advancedcustomfields.com/resources/update_field/


text:
Q: How do I call a method on an object when it is outside the scope of where the object was created I have an ArrayList called "filmList" in a separate class called actors, I want to use case 2 in the switch to call newActor.filmList.get(i); but I keep getting object may not be initialized errors from the compiler. If I put the same line in switch case 1 it works fine, but in case 2 i get the error. Can someone please tell me how I can call a method on the object from outside where the constructor creates the newActor object, I will be eternally grateful, it is doing my head in and my lecturer is terrible at explaining things. Thanks.
public class ActorsMain {

public static void main(String[] args) {

    Scanner kb = new Scanner(System.in);

    String fName="";
    String lName="";
    String address="";
    int age;
    String filmEntry="";
    String code="";

    ArrayList actors = new ArrayList();
    ArrayList films = new ArrayList();
    int choice=0;
    while(choice!=3){
    System.out.println("Make your selection.\n1. Add Actor\n2. List Actors");
    choice=kb.nextInt();

    switch (choice){

    case 1:
            System.out.println("\nPlease enter the actors first name:");
            fName=kb.next();
            System.out.println("Please enter the actors second name:");
            lName=kb.next();
            System.out.println("Please enter the actors address:");
            address=kb.next();
            System.out.println("Please enter the actors age:");
            age=kb.nextInt();
            kb.nextLine();

            for(int a=0;a<10;a++){
            System.out.println("Please enter the actors film.\nType 'Stop' to stop entering films.");
            filmEntry=kb.nextLine();
            //kb.nextLine();
                if(filmEntry.equalsIgnoreCase("stop")){
                    break;
                }
                else {

                    Films filmObject = new Films(filmEntry,code);
                    films.add(filmObject);
                }
            }

            Actors newActor = new Actors(fName,lName,address,age);
            actors.add(newActor);

            newActor.setFilm(films);
            films.clear();
            break;

    case 2:

        break;

    }
    }

}

}

A: Im guessing your Actor class has an ArrayList called filmList and you want to get the value from it at a certain position. If that is the case you should probably create a getFilmListIndex(int pos) method in your Actor class that takes in an index value and returns whatever object your film list stores.  Assuming your filmList stores String it might look something like this.
  public String getFilmListIndex(int pos)
      {
         return filmList.get(i);
      }

Then call this method from your ActorMain class.
  String result = newActor.getFilmListIndex(i);

A: age is uninitialized when you declare it. In case 1 it will be set, but in case 2 it is not clear that it has been set yet.
You could assign it a dummy value when you declare it, but in general it is better practice to mostly scope variables only where they are actually being used & have a valid value.
That would suggest putting all the actor details into a separate method or (not as nice) inside {} curly brackets, and only declare them as you are assigning the value. Having accessible variables hanging around with undefined, dummy or outdated values is provably less correct than only having a variable declared with a scope equivalent to when it's value is valid & applicable.

A: You will have to declare newActor outside the scope of the switch statement. Inside case 2 of your switch, newActor doesn't exist.
int c = 0;
switch (c) {
    case 1:
        Object obj = new Object();
        break;
    case 2:
        System.out.println(obj.toString()); // obj only exists in case 1
        break;
}

This is actually a little peculiar and maybe somebody else can explain why, but the error you are getting seems to be particular to the switch statement. If you try to do the following:
int c = 0;
if (c == 1) {
    Object obj = new Object();
} else if (c == 2) {
    System.out.println(obj.toString());
}

You will get a different error that says "cannot find symbol" which is more to the point. Apparently cases inside a switch share scope such that they can "see each other". I assume this is related to the sans-break fall-through. Switches are all one block and the cases only determine the entrance point.
I'm not sure what you are trying to do to tell you where to put your newActor declaration but the point is right now case 2 in your switch can't use it. It only exists inside case 1.
Also you shouldn't use a switch for such a long statement. You should at least refactor it so it uses if statements. Switches are just not meant for this kind of thing. They are meant for long conditions with lots of possibilities and small statements for each case:
char operator = '*';
int leftNumber = 5;
int rightNumber = 9;

switch (operator) {
    case '+': System.out.println(leftNumber + rightNumber);
              break;
    case '-': System.out.println(leftNumber - rightNumber);
              break;
    case '*': System.out.println(leftNumber * rightNumber);
              break;
    case '/': System.out.println(leftNumber / rightNumber);
              break;
    case '^': System.out.println(Math.pow(leftNumber, rightNumber));
              break;
    default:  System.out.println("Unknown operator");
}

As a long side note, you are not passing a type parameter to your ArrayLists. Java doesn't know that your ArrayLists contain Actors and Films unless you say so:
ArrayList<Actors> actors = new ArrayList<Actors>();

ArrayLists and other generics are supposed to be initialized with a bracketed parameter of <E> where E is the desired class type of the elements in the array.
The type parameter is a little bit like extending a class. The ArrayList class will have E all over the source code and when you pass Actor in to the E parameter, E is replaced with Actor.
class ArrayList<E> {
    Object[] array = new Object[some_length];
    public E get(int index) {
        return (E)array[index];
    }
}

becomes
class ArrayList<Actor> {
    Object[] array = new Object[some_length];
    public Actor get(int index) {
        return (Actor)array[index];
    }
}

Note that even then whether or not Java knows that that ArrayList contains Actors while the application is running is still vague due to the way generics are implemented. They are implemented using something called erasure. At runtime there is no way to know that the ArrayList is of the Actor type.
If you declare them with the type parameter, you will be able to access their elements using get() as Actors and Films in your code which you won't be able to right now.
In other words you can do this:
System.out.println(actors.get(aIndex).filmList.get(fIndex));

Which it looks like you are starting to try to do under case 2 but you also won't be able to do at the moment. Without <Actor> or <Film> it will tell you "cannot find symbol" or "incompatible types" because the ArrayList holds an array of Object without the type parameter. (It's still an array of Object with the type parameter but you can use it like the type you pass in.)


text:
Q: Chef missing artifact, nested github dependency When using chef exec berks install I am getting errors relating to having a missing artefact.
My tree is
a -> b -> c. b and c are both hosted on github. b is able to install, but when trying to install from a I get the missing artefacts error.

A: You need to tell it where to get b and c from. Berksfiles, like Gemfile are not transitive. If you are trying to source from git, you'll need to add that to a's Berksfile as well.


text:
Q: Quartz.net How to set MisfireInstruction on trigger In Quartz 1.0.x it was possible so set a MisfireInstruction on the trigger by simply setting it:
trigger.MisfireInstruction = MisfireInstruction.CronTrigger.DoNothing;

We upgraded the Quartz version to 2.3.2 and it's not possible to set it like this anymore because trigger.MisfireInstruction has no setter anymore.
How is it possible to set the MisfireInstruction on a trigger now?
I tried to recreate the trigger with a TriggerBuilder like this:
trigger = trigger.GetTriggerBuilder()...

but I couldn't find a MisfireInstruction-Method on the TriggerBuilder too.
Thanks for any help

A: This behaviour has changed with version 2, I guess.
MisfireInstruction is now a read-only property and it is set using the builder as you can see in the codebase.
Now you can set the the MisfireInstruction using the TriggerBuilder:
ITrigger myTrigger = TriggerBuilder
    .Create()
    .WithIdentity("trigger1", "myGroup")
    .WithCronSchedule("0 0 12 1/5 * ? *", x => x.WithMisfireHandlingInstructionDoNothing())
    .Build();

You can use a few options:
you can use these options:

*

*WithMisfireHandlingInstructionDoNothing

*WithMisfireHandlingInstructionFireAndProceed

*WithMisfireHandlingInstructionIgnoreMisfires

A really good article with a good explanation can be found here.


text:
Q: Prove that if $p\mid ab$ where $a$ and $b$ are positive integers and $a\lt p$ then $p\le b$ I have found an old textbook called "Real Variables by Claude W. Burrill and John R. Knudsen" in the first chapter this textbook uses 15 axioms to derive much of the well known and basic facts about the integers, i have been reading and solving all the exercise and so far so good until exercise 1-27 which asks the following: "Prove that if $p$ is prime and divides $ab$ where $a$ and $b$ are positive and $a\lt p$, then $p\le b$." this would be very easy if we assume Euclid's lemma but it hasn't been proven and the very next exercise asks for its proof so i believe that there is a way to prove it without Euclid's lemma but how? Is there even a way to prove this without Euclid's lemma? I also believe i'm not allowed to use Bézout's identity because its proof is exercise 1-29
I have been thinking about this problem since yesterday and i searched online for exercise solutions for this textbook but there was no results.
As another question:does the theorem above imply Euclid's lemma in a straightforward way?

A: We use induction on $a$ to prove the claim.
If $a=1$, then $p \mid b$ and clearly $p \le b$.
Now let $a>1$ and $ab=cp$. We can write $p=ka+a'$, where $k$ and $a'$ are integers and $0 \le a' < a$. Moreover, $a' \ne 0$ because $p$ is prime and $1<a<p$. Hence, $a'b=(p-ka)b=(b-kc)p$, i.e. $p \mid a'b$ and we can apply the induction hypothesis to $a'<a$.

With regard to your second question: yes, this result implies Euclid's lemma. If we assume that $p \mid ab$, but $p \nmid a$ and $p \nmid b$, then the same would be true if we replace $a$ and $b$ by $a_1=a \pmod p$ and $b_1=b \pmod p$ respectively. This contradicts the above result since $1 \le a_1<p$ and $1 \le b_1<p$.

A: As a way to suggest that this is at least nearly equivalent to Euclid (or something like it), let's see how it does with the so-called Hilbert Numbers.  These are just the naturals of the form $4k+1$.  They are useful for thinking about things like unique factorization, since such basic properties do not hold for them.  For instance, numbers like $3\times 7=21$ are "prime" here, since neither $3$ nor $7$ are Hilbert Numbers.  Thus you can have something like $$21\times 209= 33\times 133$$ as two distinct "prime" factorizations of $4389$.  (Note:  Here, of course, $209=11\times 19$ and $133=7\times 19$ so, in the context of the natural numbers, all we've done is to 'reapportion' the various primes.  As all those primes are of the form $4k+3$ none of them  are Hilbert Numbers, of course).
How does your result fare in your context?  Well, the largest "prime" in our example is $209$ so let that be $p$.  Then, letting $a=33,b=133$ we see that both $a,b<p$ but $p\,|\,ab$ nonetheless.  So...whatever proof the authors had in mind, it has to fail for the Hilbert Numbers.


text:
Q: What experiments have been proposed to discriminate between interpretations of quantum mechanics? There are a lot of potentially correct interpretations of quantum mechanics. While I've heard descriptions of a lot of them, I've never heard of an experiment being done to test any of them aside from the old Bell test experiments.
What ongoing experiments are looking to test interpretations of quantum mechanics?
What about experiments that have been proposed, but not actually performed?

A: There are a variety of thought experiments that are designed to make some interpretations seem more plausible than others (e.g. the PBR experiment).  The problem is that there is no argument that will ever make anybody change their mind (just like with religion or politics).
As for actual experimental outcomes, all interpretations always predict the same outcome so the differences are untestable.  Otherwise we would have tested them and thrown out the interpretations that didn't fit.  The exception to this is the dynamical collapse theories, which predict that the wave function collapses on its own due to some not yet known physical principle, such as quantum gravity or something.  Under these theories, large scale delicate experiments (such as quantum computers, or large objects in superposition states) could expose these new effects.  I see proposals pop up on arXiv occasionally, but unfortunately I don't remember any of the titles.


text:
Q: Using load function instead of ready function in jquery Cycle slideshow This is part of my code:
  <script type="text/javascript">
  $(document).ready(function(){
$('#slideshow').cycle({
fx: 'cover',
speed: 2500,
timeout: 2000
});
});
</script>

I want to use load function instead of ready, because I want my slideshow to be started after all images are completely loaded.
In stackoverflow question below, it's suggested to use this code:
Check if images are loaded?
$('.slideshow img').load(function(){
$('.slideshow').show().cycle();
});

and also display the images in the body tag as : none.
when I apply this code to my own slideshow (without displaying the images as none), my slideshow doesn't start.
How I should write this code?
Thanks

A: You could try the following
$(window).load(function() {
   $('#slideshow').cycle({
     fx: 'cover',
     speed: 2500,
     timeout: 2000
   });
});

This should wait to all content and graphics are loaded before running the cycle.


text:
Q: Signal wait always high I'm not sure if this is the right place to ask this question, so apologies in advance if not.
Problem I'm facing is: One of my server's signal wait floats at around %35 and won't go down.
Top 3 waits are:

SOS_SCHEDULER_YIELD (55%)
OLEDB (10%)
ASYNC_NETWORK_IO (6%)

CPU utilization of the instance is at around 22%.
What might be causing this to happen?. Where should I look at to investigate further?
I'm on SQL Server 2012.
Thanks all.

A: Based on your comment about the "unwieldy" SP I'd almost guarantee that is at least part of your problem.  Try running the following query replacing DBName and SPName as appropriate.
USE DBName
GO

SELECT SUBSTRING(text, statement_start_offset/2,
        CASE WHEN statement_end_offset = -1 THEN 999999 ELSE
            (statement_end_offset-statement_start_offset)/2-1 END)
    ,*
FROM sys.dm_exec_query_stats
CROSS APPLY sys.dm_exec_sql_text(sql_handle) query
WHERE query.dbid = db_id('DBName')
  AND query.objectid = object_id('SPName')

This will break down your SP into pieces and you can sort by one of the elapsed_time, logical_reads columns, or total_worker (cpu) columns to decide what specific commands you want to work on first.  The actual command will be the first column.
By breaking it down like this you can start picking off the low hanging fruit and speed the over all SP a bit at a time.  This doesn't of course take the place of reviewing the whole thing at once.  For example it will help to reduce the speed of a query that's being run a dozen times in the SP, it will help even more if you can figure out a way to run it only once (personal recent experience).
Now to be fair this doesn't answer your original question and it is more meant as a response to the comment and a helpful way to deal with a "problem" sp.

A: Starting with the highest and moving down:
SOS_SCHEDULER_YIELD
This wait type is usually caused when you have queries performing huge scans. I'd suggest checking to make sure you have the proper indexes in place and you don't have any out-of-date statistics resulting in an inefficient query plan.
OLEDB
OLEDB waits indicate that your query has to reach out somewhere remotely, usually a linked server. If you're seeing performance issues with this, consider figuring out if there are performance issues on the remote server or making some attempt to bring that data local (replication, etc.).
ASYNC_NETWORK_IO
This one signals that SQL Server is waiting for a go-ahead to send data across the network. Your culprit is likely to be some application pulling data row-by-row instead of pulling the entire result set at once.

Obviously, you're going to want to focus on SOS_SCHEDULER_YIELD. Like I said, checking your indexes and statistics and analyzing your query plans are probably the best way to go about reducing your waits in this case.
You can find more info about all of these in this wonderful post by Paul Randal and more in-depth information about SOS_SCHEDULER_YIELD in this wonderful post also by Paul Randal.


text:
Q: How do i stop the readarray prompt using a specific keyword? #!/bin/bash
tty=$(readlink /proc/$$/fd/2)

echo "Paste Content below"
readarray -d '\n' lines < $tty
printf '%s\n' "${lines[@]}" > links.txt

So i am using the above script to store a block of text in a variable lines and write it to a file links.txt .
The thing is when the readarray prompt shows up and i paste my text , i have to stop the read process by doing ctrl + d , after that the script proceeds further and writes the stored variable to links.txt
Ideally i want some particular keyword to act as endpoint of my paste where the read prompt ends automatically as soon as that particular word is detected
For example , after i have pasted my content. if i enter stopread on a new line it should stop the read process and proceed further with the script
( i have just used the word stopread as an example )
Example - In readarray prompt , if i paste
1
2
3
stopread

it should store 1 ..3 in variable lines and and proceed further in script without the need of doing ctrl + d to stop close read prompt

A: You should be doing this with a while read loop, since this will allow you to only read the necessary data and no more (due to a buffer size of 1), allowing the rest of the script to consume the rest of the input in a robust way:
lines=()
while IFS= read -r line && [[ "$line" != "stopread" ]]
do
  lines+=("$line")
done

However, since you ask how to do it readarray, you can do:
readarray -d '\n' lines < <(sed '/stopread/q')

This inherently reads in larger buffer sizes, so it may overconsume input. For example, if the stop word appears half way into a buffer, then the rest of the buffer is necessarily discarded. It's even worse than just being fragile and unpredictable, because you won't be able to spot any problems in casual testing at typical human input speeds, and may therefore more easily be fooled into thinking it's a good solution.

A: Just like in your previous question, an array isn't useful for what you're trying to do:
$ foo=$(awk '/stopread/{exit} 1' file)
$ echo "$foo"
1
2
3

or to read from stdin:
$ foo=$(awk '/stopread/{exit} 1')
1
2
3
stopread
$ echo "$foo"
1
2
3


text:
Q: Prolog doesn't pass variables In a Prolog rule, I tried to pass variable from case to another but it doesn't work
plane(c130,propeller,high,conventional,conventional,under-wing).
plane(c141,jet,high,sweptback,ttail,upperwing).
plane(c5a,jet,high,sweptback,ttail,none).
plane(b747,jet,low,sweptback,conventional,aftcockpit).

planeinfo:-
    plane(Name,Eng,Wing,Shape,Tail,Bulges),
    write(Name),put(10),
    write(Eng),put(10),
    write(Wing),put(10),
    write(Shape),put(10),
    write(Tail),put(10),
    write(Bulges).

getplane:-
    write('enter engine type '),
    read(Eng),
    Eng == 'propeller' ,Name ='c130',
    planeinfo,!;
    write('enter wing postion'),
    read(Wing),
    Wing == 'low' , Name = 'b747',
    planeinfo,!;
    write('enter the bulges type'),
    read(Bulges),
    Bulges == 'upperwing' , Name = 'c141', write(Eng),write(Wing),
    planeinfo,!;
    write('enter wing shape'),
    read(Shape),
    write('enter tail'),
    read(Tail),
    planeinfo,
    write("Plane Is Not Found , Please Retry"),
    repeat.

and here is the output
?- getplane.
enter engine type jet.
enter wing postion|: high.
enter the bulges type|: upperwing.
_L155_L156c130

propeller
high
conventional
conventional
under-wing
true.

in addition to a wrong output .

A:
I tried to pass variable from case to another but it doesn't work

It's because the or operator (;, post the first planeinfo,!) activate the backtracking and cancel the effect of the first read/1.
If you want to maintain the read values for engine (Eng), wing (Wing) and bulges (Bulges), you have to work with parentheses to limit the backtracking effect of the ; operator.
Not sure about what do you want obtain but... the following is an example
getplane:-
  write('enter engine type '),
  read(Eng),
  (  Eng == 'propeller' ,Name ='c130',
     planeinfo,!
   ;
     write('enter wing postion'),
     read(Wing),
     (  Wing == 'low' , Name = 'b747',
        planeinfo,!
      ;
        write('enter the bulges type '),
        read(Bulges),
        (  Bulges == 'upperwing' , Name = 'c141', write(Eng),write(Wing),
           planeinfo,!
         ;
           write('enter wing shape '),
           read(Shape),
           write('enter tail '),
           read(Tail),
           planeinfo,
           write("Plane Is Not Found , Please Retry"),
           repeat
        )
     )
  ).