CLLocationManager instance in embedded framework not requesting authorization?

Question: I am working on an embedded framework that uses CLLocationManager to perform some BeaconRegion monitoring. The CLLocationManager instance in the framework just won't request authorization from the user. What am I missing?

The NSLocationAlwaysUsageDescription is set in both the app's and the framework's Info.plist file, to be sure.
The app's background capabilities Location Updates and Uses Bluetooth LE accessories are set.

I am trying to request the authorization like this:
- (void)requestPermissionsIfNecessary {
    if ([_locationManager respondsToSelector:@selector(requestAlwaysAuthorization)]) {
        [_locationManager requestAlwaysAuthorization];
    } else {
        NSLog(@"_locationManager does not respond to 'requestAlwaysAuthorization'!");
        NSLog(@"CLAuthorizationStatus: %d", [CLLocationManager authorizationStatus]);
    }
}

The _locationManager does not respond to the selector and the CLAuthorizationStatus is 0 (kCLAuthorizationStatusNotDetermined).
I am testing on an iOS 8.1.1 iPhone 6 Plus.
Any help? Thanks in advance!
Edit:
Now at least I'm able to make the _locationManager request authorization. No idea why it is requesting it now.
The locationManager:didChangeAuthorizationStatus: delegate method, however, again reports the status of kCLAuthorizationStatusNotDetermined. Sounds like an Info.plist issue?
Comment: please debug and see the value of _locationManager. Maybe it's nill, or some other class than CCLocationManager ?
Comment: Just did and the _locationManager ivar is properly initialized and of class CLLocationManager. Too bad it wasn't that easy to fix. :/
Answer: Delaying the request solved my problem here.
When triggered at the top level by the viewDidLoad method of my rootViewController it has always been denied. Requesting authorization just a second or so later on a button click worked perfectly. Never experienced this kind of behavior when the CLLocationManager was used regularly in a project and not in an embedded framework. In fact I previously used the exact same implementation in a project and everything went fine.


How do I reverse an int array in C?

Question: I am trying to reverse the array.
<code>#include<stdio.h>
//code to reverse the current array1
void reverse(int array1[]){
    int i;
    int n=3;
    for  (i = 0; i <n; i++)
    {
        array1[i]=array1[n-i-1];
        printf("%d\t",array1[i]);
    }

}

int main(){
    int array1[]={1,2,3};
     reverse(array1);
}
result 3 2 3
</code>
when i compile this code i am getting 3 in array[0] poistion what is my error?
Comment: This would be a great problem for using a **Debugger**.  Step through each line of code, and watch the array change at each step.  Then the error will be obvious.
Answer: You are reading and writing the same array, so some writing will break data that are not read yet.
Typical way to reverse is to swapping elements in former half and latter half.
<code>void reverse(int array1[]){
    int i;
    int n=3;
    for  (i = 0; i <n; i++)
    {
        if (i < n-i-1) /* avoid swapping the same pair twice */
        {
            int tmp=array1[i];
            array1[i]=array1[n-i-1];
            array1[n-i-1]=tmp;
        }
        printf("%d\t",array1[i]);
    }

}
</code>
Answer: Can't write code right now.
You're overwriting array's value at position 0 on the first loop, so when your code checks the value at position 0 it reads the new value instead of the old one).
Create a second array to write the inverted values instead of overwriting them.

How do I reverse an int array in C?


On matrices with trace value zero

Question: I would like to ask you something regarding the trace of a matrix (the value of the diagonal after adding all its members, a value which is said to remain constant independently from base changes):
Do matrices with trace value zero constitute a (sub)group? If so, which properties tell them apart from matrices with non-zero trace values? Should a matrix with diagonal entries such as , say, [2, -3, 1], group together with that showing [0,0,0]?
I am particularly interested in those cases in which all the members of the diagonal equal zero. Do they have interesting algebraic properties as compared with the other zero trace matrices and the nonzero matrices altogether?
Thanks in advance.
Comment: Useful Point: Skew Symmetric matrices have trace 0. (in fact, all diagonal elements zero.)
Comment: http://en.wikipedia.org/wiki/Trace_%28linear_algebra%29#Other_properties has useful information towards it.
Comment: If you consider the $K$-vector space of square matrices $M_n(K)$, then the trace is a linear form $\operatorname{Tr}:M_n(K) \longrightarrow K$, hence the space of traceless matrices is the kernel of this form. This implies that it is a subspace of $M_n(K)$ of dimension $n^2-1$.
Answer: For the group question, try computing the square of the $2\times2$ matrix describing a quarter turn.
The traceless matrices do form a Lie algebra (the bracket is the commutator $[A,B]=AB-BA$). In fact the commutator of any pair of square matrices is traceless.
There is nothing particularly interesting about matrices with all diagonal entries zero, since that condition is not invariant under change of basis (while the value of the trace is).
Comment: How come the zero diaginal entries condition not be invariant? As you correctly state, the value fo the trace remains constant. All diagonal entries being zero means the trace value is zero, and that zero value will remain invariant across changes of basis. Do you mean that value would remain zero while the zero entries rearrange themselves with different values which nonetheless yield zero as their sum? Could you provide a specific example withchange of base? Thanks.
Comment: Is it fair to say that traceless matrices represent a scenario where the group does not undergo any movement whatsoever?
Comment: @JavierArias: For instance the permutation matrix $(\begin{smallmatrix}0&1\\1&0\end{smallmatrix})$ has all diagonal entries zero, but it is diagonalisable with diagonal form $(\begin{smallmatrix}1&0\\0&-1\end{smallmatrix})$, which does not have all diagonal entries zero (though it is still traceless).  Diagonalisation is obtained by an appropriate change of basis.
Comment: @JavierArias: For your second comment, I don't know what you mean by "group does not undergo any movement whatsoever"? What group, which action? What one can say is that for the adjoint (conjugation) action of $GL(n)$ on itself, the derivatives (which is what the Lie bracket gives) are always in the direction of the codimension$~1$ subspace of the tangent space given by the traceless matrices. This does not mean the derivative is zero; certainly things do undergo change.
Comment: Well, a Lie Algebra represents a Lie Group, right? A continuous movement group, right? I am sorry, I am not a mathematician, just someone trying to understand certain structures in order to better understand linguistics, for instance; someone who relies on books such as the Encyclopedia of Mathematics by Kolmogorov or on Jules Vuillemin's chapter on Lie in his "La philosophie de l'algèbre". I make an effort to understand, but probably have many formal lacunae. Sorry if that is the case.
Comment: You can think of a Lie algebra as a kind of derivative of a Lie group; the group determines the algebra, but not conversely. More precisely the Lie algebra is the _tangent space_ to the group at the identity element (so it models very small deviations from the identity), and it is equipped with a structure (Lie bracket) that corresponds to the derivative of conjugation $x\mapsto gxg^{-1}$; this measures at an infinitesimal scale the non-commutativity of the group (since for commutative groups conjugation is just the identity).
Comment: Is it fair to consider the group as possibly undegoing movement (for instance, rotation, or sliding), while keeping itself topologically compact (no modification of the initial distances between two given points, or, even better, keeping adjacency conditions between any two given elements?
Comment: By the way, isn't the term traceless matrix misleading? I think a zero value does not entail being traceless. Traceless matrix are those non quadratic matrices which do not allow for a diagonal value, right? I am saying this because as a linguist I would like to keep a difference between a structure having left a "mute" trace behind after its movement, from a structure not having moved and therefore not having left any trace whatsoever.....Does it make sense to you what I am saying??
Comment: @JavierArias: linguistically speaking you are right: a traceless matrix is a matrix that has disappeared without leaving a trace. But since it is rare to discuss those in mathematics, it is not unheard of to call matrices with trace zero [traceless](https://en.wikipedia.org/wiki/Trace_%28linear_algebra%29#traceless). But it is true that nobody would call a matrix with determinant zero "determinantless". By comparison, many theorems that state that some quantity is zero are called "vanishing theorems" (even though the theorems, and the people they are called after, remain).
Comment: Let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/22840/discussion-between-javier-arias-and-marc-van-leeuwen).
Comment: Thanks for your response. Wouldn't it make sense to talk about non-quadratic matrices as being traceless, thus keeping the term just for that purpose? It may be "deformation profesionelle" on my part, but anyway.....
Comment: This is not exactly what I am pursuing, but it provides a nice view on what can be done for the study of language with such tools: http://www.its.caltech.edu/~matilde/GraphGrammarsLing.pdf

On matrices with trace value zero


Generating a Curse of Dimensionality Chart

Question: I'm trying to demonstrate the curse of dimensionality in Python. Here's how the curve should look like:

I want to do this for dimension from 2 to 30 with a step size of 1 and for each dimension I want to generate 100 random data points. Can anyone let me know how can I go about doing this?
Here's my current code:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
import os
import math
from random import randint

Below, I'm generating random values to variables x and y and then I calculate the Euclidean distance using np.linalg.norm. After that, I store the value in a list.
x=np.array([randint(0, 101),randint(0, 101)])
y=np.array([randint(0, 101),randint(0, 101)])
ed_list = []
d=np.array([1,2])
ed = np.linalg.norm(x - y)
ed_list.append(ed)
ed_list
print(x)

Now, I use a for loop to generate the more random values and then store and plot it.
for i in range(2,50):
    xval = randint(0, 101)
    yval = randint(0, 101)
    x = np.append(x,xval)
    y = np.append(y,yval)
    d= np.append(d,i+1)
    try:
        ed = np.linalg.norm(x - y)
        ed_list.append(ed)
        ed = 0
    except:
        ed = 0
    print(x, y)

plt.plot(ed_list)
plt.xlabel('Number of dimensions')
plt.ylabel('Euclidean Distance')
plt.show()

However, my curve looks like this because I'm just plotting the Euclidean distance and not calculating according to the formula in the above Curse of Dimensionality picture.

So I have 2 questions. How can add the formula that is given in the curse of dimensionality picture. Also, how do I do this for dimension 2 to 30 and for a random 100 data points as I have stated above. If anyone can help me on this, that would be great!
Answer: All you are showing is the distance between two points as you add extra dimensions. Naturally, that will keep growing larger and larger. The curse of dimensionality says that, given a whole set of points, P, and a reference point, Q, if you compute the distance from Q to each of the points in P, the difference between the maximum distance and the minimum distance goes to 0. You need WAY more than 2 points to show that.
For each dimension, generate a bunch of points (I picked 10000), pick another random point, compute the distance to each, grab the min and max from those distances, and plot the result.
import numpy as np
import matplotlib.pyplot as plt
import os
import math

deltas = []
for N in range(2,50):
    # Generate 1000 random points in N dimensions.
    P = [np.random.randint(-100, 100, N) for _ in range(10000)]
    Q = np.random.randint(-100,100,N)
    diffs = [np.linalg.norm(p-Q) for p in P]
    mxd = max(diffs)
    mnd = min(diffs)
    delta = math.log10(mxd-mnd)/mnd
    deltas.append( delta )

plt.plot(range(2,50),deltas)
plt.xlabel('Number of dimensions')
plt.ylabel('Euclidean Distance')
plt.show()

Result:
Comment: Thanks a lot for your help! I guess I couldn't understand the way to go about getting these multiple dimensions and then finding out the distance between them but your code definitely helps in giving an idea to do it. Will take a deeper look at the code and then will ask you if I have any questions.


Add new instance of movieClip_A to position of movieClip_B

Question: I am creating a farm game and I am trying to drag an object (red spot) over the ground. When the object rolls over a soil square it highlights a different color. I am trying to drop the object onto the colored soil and have it plant some corn. My cornCrop movieClip is supposed to appear in the middle of the highlighted soil. I posted some code and a screenshot. In the code snippet i have some hard-coded x,y coordinates for the corn stalk to appear. How do I get the corn stalk to dynamically appear in the center of the highlighted soil movieClip? Plus, I can see that I should probably use some sort of array for the corn because I don't know how many times a user will want to plant them. I am not sure how to do that either.
ScreenShot URL: http://sdrv.ms/193vyIm
if (bucketCorn.hitTestObject(Grid.Cell_3_1))
        {
            var gridID = Grid.Cell_3_1;
            //addCrop();
            //myColorTransform.color = 0x00FF33;
            //Grid.Cell_3_1.transform.colorTransform = myColorTransform;
            trace("Yogi Bear!");
            var cropCorn1 = new CropCorn();

            cropCorn1.x = 50;
            cropCorn1.y = 400;

            addChild(cropCorn1);
        }

        if (bucketCorn.hitTestObject(Grid.Cell_3_2))
        {
            //addCrop();
            //myColorTransform.color = 0x00FF33;
            //Grid.Cell_3_2.transform.colorTransform = myColorTransform;
            var cropCorn3 = new CropCorn();

            Grid.Cell_3_2.addChild(cropCorn3);

        }

Thanks,
Alex
Answer: For the x,y coordinates
cropCorn1.x = bucketCorn.x;

cropCorn1.y = bucketCorn.y;

or
cropCorn1.x = bucketCorn.x + Grid.Cell_3_1.width / 2;

cropCorn1.y = bucketCorn.y + Grid.Cell_3_1.height / 2;

for the array of corn
var cornArray:Array = new Array();

for (var i:int = 0;i<100;i++){

    cornArray.push(CropCorn());

}

then just use each positon of array starting at 0. so
cornArray[0].x = bucketCorn.x;

cornArray[0].y = bucketCorn.y;

and on your next event
cornArray[1].x = bucketCorn.x;

cornArray[1].y = bucketCorn.y;


Easy examples of discrete/atomic probability measures on $\mathbb{R}$ weakly converging to a probability measure with continuous density function

Question: I'm trying to construct some easy examples of sequence of discrete/atomic probability measures $P_n$ on the real line that converges weakly to a measure $P$ on the same, but that has a continuous density function $f$ (i.e. Radon-Nikodym derivative) w.r.t. the Lebesgue measure on the real line. I'm thinking along the line of Riemann integral...some hints of solutions would be appreciated!
Answer: Take the sequence of  $\frac{\delta_{0}+\delta_{\frac{1}{n}}+....+\delta_{\frac{n-1}{n}}}{n}$ where each $\delta_{\frac{k}{n}}$ is a dirac measure.
If you examine the convergence with respect to continuous functions with compact support you will see that the weak limit is the measure $v(A)=m(A)$ if $A \subseteq [0,1]$ and $v(A)=0$ otherwise.
Here $m$ denotes the Lebesgue measure.
Comment: Thank you Marios, yes, I see that, the integral of any contonuous, bounded $f$ is the Riemann sum, which converges to its integral over $[0,1]$ as $n \to \infty$.


Unable to exit from watch

Question: I have executed
>> watch tree ./

Now my problem is I'm unable to exit from watch - without closing the terminal.
I read man page of watch but they have not mentioned how to exit from watch screen.
Is there is magic key combo that you need to use to exit from watch ?
It's like one those problems you face when you for the first time open vim and don't know how to close it.
Comment: Watch works like `tail -f`, a command to inspect realtime logfiles, for example: `sudo tail -f /var/log/syslog`. It will not end, unless you type Ctrl-C
Answer: Press Ctrl-C to interrupt watch. Ctrl-C is the general key combination to kill the foreground process in the shell. If that fails (it sometimes does for hung processes), pressing Ctrl-Z and issuing kill -9 %1to kill process number one works.
If you press Ctrl-Z you can do more things:

Resume the job to foreground by running fg
Resume the job in the background running bg
List running jobs using jobs
Manipulate the job, as mentioned, using kill
Change priority of job using renice
Start new jobs, leaving the old running in the background
Comment: It does say:  By default, watch will run until interrupted. This is unix-ese for ending it with Ctrl-C :)
Comment: okay, this works. But did the `watch` developers not give way to exit from it, like what we have key - `q` for exiting from htop/top. I was looking for something like that.
Comment: * if you prefer you can make your own `watch` with a `while` loop like this: `while true; do clear; tree ./ ; read -t2.0 -s -n1 k;[[ $k == "q" ]]&&break done` - I wrapped a custom `ps|awk` pipeline this way because "it looks like `top`" I wanted it to behave like it.
Comment: Ctrl+z or ctrl+c not working in single user Mode...

Unable to exit from watch


apache airflow variables on startup

Question: I'm learning Airflow and am planning to set some variables to use across different tasks. These are in my dags folder, saved as configs.json, like so:
{
  "vars": {
    "task1_args": {
      "something": "This is task 1"
    },
    "task2_args": {
      "something": "this is task 2"
    }
  }
}

I get that we can enter Admin-->Variables--> upload the file. But I have 2 questions:

What if I want to adjust some of the variables while airflow is running? I can adjust my code easily and it updates in realtime but it doesn't seem like this works for variables.
Is there a way to just auto-import this specific file on startup? I don't want to have to add it every time I'm testing my project.

I don't see this mentioned in the docs but it seems like a pretty trivial thing to want.
Comment: `"..I can adjust my code easily and it updates in realtime but it doesn't seem like this works for variables..."` It works for everything including `Variable`s, `Pool`s, & `Connection`s. See [this](https://stackoverflow.com/a/55896121/3679900) answer, it describes creating dynamic workflows and uses programmatic `Variable` updation to change structure of DAG on the fly (even as it is running)
Answer: What you are looking for is With code, how do you update an airflow variable?

Here's an untested snippet that should help
from airflow.models import Variable

Variable.set(key="my_key", value="my_value")

So basically you can write a bootstrap python script to do this setup for you.
In our team, we use such scripts to setup all Connections, and Pools too

In case you are wondering, here's the set(..) method from source
@classmethod
@provide_session
def set(
    cls,
    key: str,
    value: Any,
    serialize_json: bool = False,
    session: Session = None
):
    """
    Sets a value for an Airflow Variable with a given Key
    :param key: Variable Key
    :param value: Value to set for the Variable
    :param serialize_json: Serialize the value to a JSON string
    :param session: SQL Alchemy Sessions
    """

    if serialize_json:
        stored_value = json.dumps(value, indent=2)
    else:
        stored_value = str(value)

    Variable.delete(key, session=session)
    session.add(Variable(key=key, val=stored_value))
    session.flush()

Comment: Thanks but this is not exactly what I had in mind - by edit I meant actually opening that json file and manually editing a variable or two. I was wondering if there is a way to (1) have such edits appear in my airflow instance without manually reloading on the variable UI, and (2) automatically import the contents of that `.json` file when airflow starts up

apache airflow variables on startup


What is the difference between the filter on my furnace and an Air Exchanger?

Question: I live in the Pacific Northwest (Seattle area) and the allergy season has started for me. It is so bad that I am thinking about getting an air exchanger for next year. The house I live in was built in 2007. It has a standard gas furnace and the furnace has a large 20 x 25 x 4 filter attached to it (I change the filter twice a year).
What is the difference between the filter attached on my furnace and an air exchanger? Are they doing the same thing? Would I get much better air in the house with an air exchanger? Is it worth getting an air exchanger?
Thank you!
Comment: This is a pretty broad question as written.  An air filter simply tries to catch dust and an exchanger actually takes new air from outside and puts that into your house.  One is not a replacement for the other.  You may want to do some basic research and focus your question more with any specific questions you have.
Answer: Do you mean HRV/ERV? They won't help with allergens. In fact they are likely to make the situation worse. Their job is to bring in fresh air and pre condition it with the outgoing air. They do have filters but they are just to protect the exchange core. If your allergic reactions are due to pollen and the like an HRV will make it worse as the equipped filter is not a MERV rated filter. You would be better off installing a whole house HEPA unit.
Duct mount HEPA

Elecro-Air Five Seasons
I've installed lots of these. You would leave the furnace fan running constantly as well as the HEPA filter fan. There are much better options available from IQAir but they are very expensive.
Comment: MERV is the ASHRAE standard for filter performance. MERV 12 will capture 35% of the particles that are 0.3 microns, the HEPA standard is 90%, equivalent to MERV 16. There is debate among allergy specialists as to whether or not this ultimately makes much of a difference for sufferers, but I believe it helps.
Comment: I only install them on a request basis. I have zero allergies and can eat just about anything. Anytime I've put the HEPA units in I've always got very positive feedback. Could be a placebo. I don't have any tools to test how well they work. I just don't know.
Answer: Conceptually they are the same if you have a fan forced furnace, but not all furnaces are like that, some are passive (convection). But also, the filter on your furnace must allow the proper amount of air to pass through it based on the blower capacity and air ducting, otherwise your furnace efficiency drops and it costs you more to operate it. But you should be able to buy "hypoallergenic" filters for most furnaces, where they use highly pleated filter media to increase the total surface area in order to compensate for the lower air flow through the media. These filters will cost you a lot more than standard filters, upward of 10x the plain filter cost depending on what level of filtration you want.
With an air exchanger, flow efficiency is irrelevant so the filter can be more restrictive and can operate with a low air volume since you typically leave it on all of the time.
Comment: Thanks for the reply. I have a forced air furnace. If I understand you well, a $85 filter MERV 12+ would do the same job, right?

If I was to get an Air Exchanger installed, would it use my existing duct?


When does an Embedding extend into a Homeomorphism?

Question: This is from a post in sci.math that did not get a full answer; I may repost it for the OP there:
I am  interested on the issue I read in another site of when an embedding from a closed set extends into a homeomorphism, i.e., if $C$ is closed in $X$, and $f:C \rightarrow Y$ is an embedding, when can we extend $f$ to $F$ so that $F:X \rightarrow Y$ is a homeomorphism, and $F|_C=f$ (i.e., $f=F$ in $C$ )?  Of course there are trivial cases
like when $f$ is the identity on $C$:
I know of, e.g., Tietze Extension, and I think there are results about extending
maps from a space into its compactification; I think the map must be regular (inverse
image of a compact set is compact). But I don't know of any general result.
I will learn Latex as soon as I can; my apologies for using ASCII
Answer: gary, I think your question is too general. For instance, there is something called 'cofibration' in topology, which deals with this type of problem under a strong condition: Namely, $f:A\rightarrow Y$ is continuous and has an extension iff every $g\colon A\rightarrow Y$ satisfies this property where $g$ is homotopic to f.
If a space $(X,A)$ has homotopy extension property with respect to $Y$ then it is easier to check if a map $f\colon A\rightarrow X$ has an extension, because , now, there are billions of maps that should simultaneously have extensions. However, even under this condition, there is no general theorem that I know.
Answer: This will never happen unless $C=X$. Consider the identity embedding $C \to C$; by your hypothesis, this extends to a homeomorphism $X \to C$ extending $C \to C$. This is an inverse to the inclusion $C \to X$. Thus $C=X$.

In general, this is unlikely. Consider any $Y$ between $X$ and $C$. Then there is an embedding $C \to Y$ which by your condition extends to a homeomorphism $X \simeq Y$. So $X$ is homeomorphic to all its closed subspaces that contain $C$ (with a homeomorphism that extends $1: C \to C$). This generally will not happen in natural examples (though it will if $X$ is a [Toronto space][1] and $C$ has the same cardinality as $X$): for instance, it means that $X/C$ is homeomorphic to any of its closed subspaces.
Comment: I was considering explaining my situation more clearly, but after the 2-3 downvotes I don't see the point. Specially 2 downvotes to someone who was at that point clearly a newbie.
Comment: what is $A$ supposed to be in your answer?  I don't see it in the question.
Comment: @Pete: Dear Pete, thanks for the correction: I meant $C$.
Comment: okay, but I still feel like I am missing something.  If we start with a homeomorphism $F: X \rightarrow Y$, restrict $F$ to a closed subset $C$ of $X$ and call if $f$, then it seems to me that we have an affirmative answer to the OP's question not covered by your response.  No?
Comment: @Pete:  I was under the assumption that the OP wanted the result to hold for *all* spaces $Y$. I may have been mistaken -- can the OP clarify?
Comment: What's the reason for the 2 Courics? I had trouble with my original logon, so I used a different one. Aren't down votes usually explained?
Answer: Thanks both for your comments.
I am sorry if I did not make this clear; I don't know if you were assuming this,
   but the embedding is into Y, and not onto it, i.e., we have an embedding
   e:C-->e(C) , and not e:C-->Y, which,  as you said, cannot be 1-1. I can see
   how my using the identity on C was misleading, sorry; what I meant was if, e.g.,
   we had a map from (0,1) as a subspace of R embedded by identity into another
   copy of (0,1) in R. Then we would define f^ (R-(0,1))->R-(0,1) by f(x)=x (though
   there are many other options, using, e.g., bump functions and partitions of unity.)
   But R, R^n are too nice in too many ways, and it would be great to have more general
   results.
And, re your second question, Akhil: I would like , if workable, to fix Y, and
   not look for a result for all possible spaces Y, which may be too ambitious for
   me at this point. so maybe we could look for properties that Y may have to be
   able to have this extension.
Comment: Are you the same user as gary? If so, would you like me to merge your accounts?


RabbitMQ / .NET integration - "The remote certificate is invalid according to the validation procedure", but the cert is valid

Question: I have a RabbitMQ integration built in a .NET Standard library, which is being used by a few .NET Framework 4.7.2 apps. It's configured to connect to the RabbitMQ broker securely over port 5671 with a self-signed cert that has been installed in the Trusted Root Certificate Authorities of my local machine and our app development/testing server.
Both the development server and the RabbitMQ broker are running on AWS EC2 instances within our "local" network.
When I run these apps in debug on my local machine (connected to the "local" network through a VPN), the secure connection to the RabbitMQ broker is initialized correctly, and everything works as expected.
When I try to run the apps on the development server, however, the connection fails with the following exception:
<code>AuthenticationException: The remote certificate is invalid according to the validation procedure.
   System.Net.Security.SslState.InternalEndProcessAuthentication(LazyAsyncResult lazyResult) +8343681
   System.Net.Security.SslState.EndProcessAuthentication(IAsyncResult result) +76
   System.Threading.Tasks.TaskFactory`1.FromAsyncCoreLogic(IAsyncResult iar, Func`2 endFunction, Action`1 endAction, Task`1 promise, Boolean requiresSynchronization) +83
   System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() +31
   System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +60
   RabbitMQ.Client.Impl.<>c__DisplayClass2_0.<TcpUpgrade>b__0(SslOption opts) +82
   RabbitMQ.Client.Impl.SslHelper.TcpUpgrade(Stream tcpStream, SslOption options) +512
   RabbitMQ.Client.Impl.SocketFrameHandler..ctor(AmqpTcpEndpoint endpoint, Func`2 socketFactory, TimeSpan connectionTimeout, TimeSpan readTimeout, TimeSpan writeTimeout) +830
   RabbitMQ.Client.ConnectionFactory.CreateFrameHandler(AmqpTcpEndpoint endpoint) +122
   RabbitMQ.Client.EndpointResolverExtensions.SelectOne(IEndpointResolver resolver, Func`2 selector) +191
</code>
What's even more weird is that, when I navigate to the secure RabbitMQ Management UI (port 15671) through a browser on the development server, the browser correctly recognizes the certificate as valid.
Thinking this may be a firewall/port issue, I made sure that the development server firewall was set to allow outbound TCP traffic to port 5671, but this also hasn't fixed the issue.
What am I missing? Is there some extra IIS configuration needed for this that I don't know about?
Thanks!
Comment: Open csproj file with notepad and check if the SSSL/TLS option is using the default operating system or Net.  If Net change to to default (remove line in project file).  If using operating system than there is issues with operating system.  What version of Windows is being used?  If Core you may need to update kernel on machine.
Comment: OS is Windows Server 2016 Datacenter. I don't see any option for default SSL/TLS in the .csproj - I'm assuming that means it's using the default operating system? What would the option look like?
Comment: See : https://learn.microsoft.com/en-us/dotnet/framework/network-programming/tls#switchsystemnetdontenablesystemdefaulttlsversions
Answer: The answer turned out to be rather simple. I had mistakenly installed the cert in the development server's admin user Trusted Root Authorities, rather than the machine's Trusted Root Authorities. Since the application was set up to run with a different user, that user didn't have access to the installed cert. Once I had installed it in the machine's Trusted Root Authorities, the connection worked as expected.
Props to Luke Bakken from the RabbitMQ team for the answer: https://groups.google.com/g/rabbitmq-users/c/tJHnDEnCZxM
Comment: Thanks for following up here!


In RegEx, require at least one a-z character, but optional other characters

Question: I'm trying to work out how to write some RegEx that requires at least one a-z character, but it can also optionally contain 0-9_- characters as well.
I started out with the below initially when all characters were optional, as long as it contained at least one of them:
add_rewrite_rule('for-sale\/([a-z0-9_-]+)\/?$', 'index.php?pagename=for-sale&search_slug=$matches[1]', 'top');

But then I needed to change it so that it is a requirement that at least one a-z be present, but the other characters are optional.
I tried the below, but unfortunately this obviously only works if these other characters are after the a-z characters:
add_rewrite_rule('for-sale\/([a-z]+[0-9_-]*)\/?$', 'index.php?pagename=for-sale&search_slug=$matches[1]', 'top');

I need these optional characters to be able to be prepend, append OR even be between a-z characters; easy enough how to allow them to be in front, but not sure how to allow them in-between.
Is there a clean way to do this?
Comment: Replace `([a-z0-9_-]+)` with `([0-9_-]*[a-z][a-z0-9_-]*)`
Comment: Thanks a lot. So simple ha!
Answer: You can replace ([a-z0-9_-]+) with ([0-9_-]*[a-z][a-z0-9_-]*) and use
add_rewrite_rule('for-sale\/([0-9_-]*[a-z][a-z0-9_-]*)\/?$', 'index.php?pagename=for-sale&search_slug=$matches[1]', 'top');

The [0-9_-]*[a-z][a-z0-9_-]* matches zero or more digits, underscores or hyphens first, then matches a lowercase ASCII letter (thus, requiring at least one occurrence) and then zero or more digits, lowercase ASCII letter, underscores or hyphens.


How to make a layout for JApplet

Question: I am creating a simple Sudoku game. Since this is my first "big" i want to do everything myself (without the NetBeans interface designer that i normally use to make GUIs). So for the GUI i created a class that extends JApplet and i drew a simple sudoku field in the paint() method.
Now i need to make 81 text fields each of which will take in 1 number. How do i position them on the screen?  Also, i was thinking of making an array so i'll be able to change the enitre matrix of fields with one for loop.
Comment: P.S. This is the first "real" GUI i'm making, take that into consideration :)
Comment: If you want to use Swing controls why don't you use one of the "grid" layouts: GridLayout or GridBagLayout. This doesn't really help with painting gridlines.
Comment: @HovercraftFullOfEels :  :-), My Bad, today is really one such day I shouldn't answer people, I never thought about multiplying.
Answer: Suggestions:

Never draw directly in the paint method of a top-level component such as a JApplet, JFrame, JDialog, or the like.
If you need to do custom drawing, do this instead in the paintComponent(...) method override of a component that extends JComponent such as a JPanel or JComponent itself.
Your problem doesn't really require custom painting, at least not yet, and is much better and more simply solved by other means.
Use components such as JLabels, JTextFields, etc... and position them using the Swing layout managers (the other means noted above). You can find the tutorial on how to use this here: Laying Out Components in a Container
Layouts to focus on first include GridLayout for your Sudoku "cells" and BorderLayout for the overall GUI. Avoid the GridBagLayout and GroupLayout, at least when starting out.
Remember that you can create complex applications by nesting JPanels that each use a simple layout manager.
A simple way to "paint" gridlines is to set the background color of the the JPanel that uses GridLayout and holds the JTextFields to Color.BLACK, and be sure to give your GridBagLayout a small vertical and horizontal gap so that the black shows through. The tutorials listed above will show you how to do this.
If this were my application, I'd gear my GUI towards creating a JPanel that held the application. Then if I needed to display it in a JApplet, I'd create a very small application that subclasses JApplet and then in the init() method, add my Sudoku JPanel into the JApplet's contentPane. This way, if I wanted to instead display my app in a JFrame, all I'd need to do would be to create another small class that creates a JFrame and add's my Sudoku JPanel into the JFrame's contentPane, then call pack() on the JFrame, and then setVisible(true).

Regarding your question on how to add a JPanel to a JApplet, again the tutorials will show you how to do this. If you haven't linked to the tutorial's big index, you will want to do so: The Really Big Index.
A very simple example goes like so:
import java.lang.reflect.InvocationTargetException;
import javax.swing.*;

public class MyApplet extends JApplet {
   @Override
   public void init() {
      try {
         SwingUtilities.invokeAndWait(new Runnable() {
            public void run() {
               getContentPane().add(new MyJPanel());
            }
         });
      } catch (InterruptedException e) {
         e.printStackTrace();
      } catch (InvocationTargetException e) {
         e.printStackTrace();
      }
   }
}

Comment: @Squeazer: the `paint(Graphics g)` method in the JApplet was overriding the applet's own paint method. Since your method was empty, no painting could be done since the applet's own paint method was being bypassed. If you need to override the JApplet's `paint(...)` method (which I don't recommend in general), *be sure* to call the `super.paint(g);` in the method override so that the applet's original paint method can do all that is needed for its painting needs.
Comment: @HovercraftFullOfEels I figured it out. I was only putting 1 or 2 object at a time to test it, and they filled the entire row / column. When i added 81 objects to the scene it filled the entire grid correctly.
Comment: Good advice; [`CellTest`](http://stackoverflow.com/a/4151403/230513) maybe of interest going forward.
Comment: Thanks for the advice! I'll do the entire thing in a JPanel. But i always had a problem inserting a JPanel into JApplet, it never worked. How do you do it properly? For instance, if i had a JPanel with a custom drawing and a few text fields how do i insert that into JApplet?
Comment: It's nice to know there are people out there willing to help :) Thanks for the support!
Comment: @mikera: since this is all usually done in the JApplet's init method, you wouldn't use a JApplet variable such as your myJApplet. You would just use `getContentPane().add(...)` or even simpler, `add(...)`.
Comment: Hey one quick question...i finally got it to work. I have 2 classes, one extends JApplet the other one JPanel. I did a custom drawing in the JPanel class (inside paintComponent() ) then i inserted that panel into the JApplet class with the code above. But it didnt work, untill i removed the (empty) paint() method i had in the JApplet class. Why is that?
Comment: @Squeazer: I'm not sure I understand your question. If you construct your GridLayout with 9, 9 parameters, you'll get 9 columns and 9 rows, which should work for your purposes. Alternatively you could nest 9 JPanels that each use GridLayout(3, 3) in a larger JPanel that also uses GridLayout(3, 3).

How to make a layout for JApplet


Passing Chart Series from Controller to Razor View

Question: I am u sing asp.net mvc 4 and placed a chart on view. i want to load its series from controller. how can i do that ? please can anyone explain it with piece of code.
Index View
@{
var myChart = new Chart(width: 600, height: 400)
    .AddTitle("Chart Title")
    .AddSeries(
        name: "Views",
        xValue: new[] {  "Monday", "Tuesday", "Wendesday", "Thursday", "Friday" },
        yValues: new[] { "2", "6", "4", "5", "3" })
    .AddSeries(
        name: "Downloads",
        xValue: new[] { "Monday", "Tuesday", "Wendesday", "Thursday", "Friday" },
        yValues: new[] { "1", "2", "3", "4", "5" })

        .Write();
}

Controller
    public ActionResult Index()
    {
        return View();
    }

Answer: It is absolutely possible. Let's start by creating a new view model to represent the chart data.
public class ChartSeriesData
{
    public string[] XValues { set; get; }
    public string[] YValues { set; get; }
    public string Name { set; get; }
}

public class MyChartData
{
    public List<ChartSeriesData> Series { set; get; }
    public string Name { set; get; }
}

And in your Action method, create an object if the MyChartData class, Set the different property values and send it to the view.
public ActionResult MyChart()
{
    var vm= new MyChartData { Name = "MyChartTitle",Series = new List<ChartSeriesData>()};
    vm.Series.Add(new ChartSeriesData
    {
        Name = "View",
        XValues = new[] { "Monday", "Tuesday", "Wendesday", "Thursday", "Friday" },
        YValues = new[] { "2", "6", "4", "5", "3" }}
    );

    vm.Series.Add(new ChartSeriesData
    {
        Name = "Downloads",
        XValues = new[] { "Monday", "Tuesday", "Wendesday", "Thursday", "Friday" },
        YValues = new[] { "1", "2", "6", "5", "3" }
    });
    return View(vm);
}

Now in your view ,which is strongly typed to a our MyChartData view model, we will iterate through the Series property and call the AddSeries method.
@model ReplaceWithYourNameSpaceHere.MyChartData
@{
    var myChart = new Chart(width: 600, height: 400)
        .AddTitle(Model.Name);

    foreach (var item in Model.Series)
    {
        myChart.AddSeries(name: item.Name, xValue: item.XValues, yValues: item.YValues);
    }

    myChart.Write();
}

If you want to include the chart in another razor view, you can use an image tag and set the src attribute value to MyChart action method.

Assuming MyChart action method exists in HomeController.


hide html page source

Question: Is there is any way to hide asp.net page view source?
Comment: See [What are some good ways to prevent people from copying my source code?
](http://stackoverflow.com/questions/2562775/what-are-some-good-ways-to-prevent-people-from-copying-my-source-code).
Comment: Actually pankaj wants to hide the image source path so a viewer cant get images save or see path to download image
Comment: @Rajesh: Open a new question for that. That's a completely different can of worms. If you want to make it so you can't download an image, you can't do it with straight HTML. You can make it a lot more difficult by embedding it in Flash, but even still, a determined thief can nab it (either by screenshoting or decompiling the Flash).
Comment: @Mark: thanks for explaination. @Matthew: thanks for link, its really very good.
Answer: If you mean, can you hide your ASP.NET code: it's not visible in View Source.
If you mean can you hide your HTML: you can discourage casual peeking by creating your HTML on the fly via Javascript or AJAX, but a developer will always be able to see what you are doing, using simple tools like Firebug and Fiddler.
Edited to add:
I wasn't thinking of obfuscation (though that also discourages casual peeking), I was thinking of using javascript to pull down HTML. Doing a View Source will only show a bunch of

hide html page source


Where this solution of $f ' (x) = g(x)$ comes from?

Question: I would have liked to solve the following first-order linear ODE for $f(x)$:
$$ f'(x) = g(x) $$
I attempted to solve it like this:
$$ \int f'(x)\,dx = \int g(x)\,dx $$
$$ f(x) = \int g(x)\,dx+C $$
Then I gave $ f'(x) = g(x) $ to WolframAlpha and its solution was quite surprising to me:
$$ f(x) = c_1+\int_1^{x} g(\xi)\,d\xi $$
I then actually paid for WolframAlpha|PRO to see the step-by-step solution, but it shows exactly the attempt and solution of mine...

So my question is where do the definite integral and xi come from? What is the trick here I'm unaware of?
Knowing this would help me understand the exact solution of the quasispecies equation.
Comment: This is for functions that do not have an antiderivative that can be expressed in terms of elementary functions, so you can calculate the integral till a given value of $x$ using numerical methods, but might not be able to express $\int g(x)$ as a function, but rather as a number. The constant is probably to quantify the boundary values
Answer: There is no difference between
$$\int f'(x)\,dx+c=f(x)+c$$ and $$\int_a^x f'(t)\,dt+c=f(x)-f(a)+c.$$
Both describe some antiderivative of $f'$, with an indeterminate constant.

Note that you can also solve the ODEs with definite integrals:
$$f'(x)=g(x)\iff\int_{f_0}^fdf=\int_0^x g(t)\,dt\iff f(x)-f_0=g(x)-g(0).$$
Answer: It depends on the initial value. In this case, Wolfram Alpha chooses $1$ as initial "time" and you have
$$
y(x) = y(1)+\int_1^x g(t)\, dt, \quad c_1 = y(1),
$$
because of the fundamental theorem of calculus. Apparently Wolfram uses the name "$\xi$" for the integral variable.


How to filter stacked bar chart?

Question: I found following example for a stacked bar chart with dc.js:
https://dc-js.github.io/dc.js/examples/stacked-bar.html

If I click on some (or several) legend item, I would like the chart to

only show the corresponding items (e.g. red and blue) and

adapt the total numbers to only consider the selected items

I already managed to add some click event to the legend entries:
chart.on('pretransition.hideshow', ()=> {
    chart.selectAll('.dc-legend-item')
      .on('click', function (data, index, nodeList) {
        const stackName = data.name;
        if(data.hidden){
           chart.showStack(stackName);
        } else {
           chart.hideStack(stackName);
        }
        dc.redrawAll();
      });
  });

This hides some stack but the sum is not shown as expected (multiplie, overlapping values are shown).

=>How can I filter the data correctly?
I also tried to use chart.filter() but that only seems to be able filter the x axis and not the stacks.
Currently, if I hover over a legend entry, the chart already adapts but does not show the wanted behavior.
Comment: Please try this: https://stackoverflow.com/a/39375071/676195
Answer: Thanks to Gordon I found following solution:
Step 1: Create an extra dimension for the stack property:
const stackDimension = crossFilter.dimension(d => d.stackProperty);

Step 2: Create an event handler and filter on that dimension:
  const selectedStackNames = [];

  const legendItemClickHandler = (data, index, nodeList) => {

    const stackName = data.name;
    if(selectedStackNames.includes(stackName)){
       const index = selectedStackNames.indexOf(stackName);
       selectedStackNames.splice(index,1);
    } else {
       selectedStackNames.push(stackName);
    }

    if(selectedStackNames.length){
      stackDimension.filter((name)=>{
          return selectedStackNames.includes(name);
      });
    } else {
      stackDimension.filter(null);
    }
    dc.redrawAll();

  };

  chart.on('pretransition.hideshow', ()=> {
    chart.selectAll('.dc-legend-item')
      .on('click', legendItemClickHandler);
  });

Step 3: Highlight selected legend items
 chart.on('pretransition.show', ()=> {
    chart.selectAll('.dc-legend-item')
      .on('click', legendItemClickHandler);

    const selectedStackNames = new Set(
      stackDimension.top(Infinity)
        .map(d=>d.stackProperty)
    );

    chart.selectAll('.dc-legend-item')
      .each((data, index, nodeList)=>{
        const node = nodeList[index];
        const colorRect = node.children[0];
        if(selectedStackNames.has(data.name)){
          colorRect.style.outline = "1px solid grey";
          colorRect.opacity="";
          data.hidden=false;
        } else {
          colorRect.style.outline = "";
          data.hidden=true;
          colorRect.opacity="0.3";
        }
      });
  });

How to filter stacked bar chart?


How to replace a light bulb in ceiling light

Question:
So I have those lights out of which most lightbulbs burned down, thus I want to replace them. Problem is that I have no idea how to get to them, tried to pull down the entire thing - but that just pulls down the entire "socket", tried to pry the "metal rim" with a flat top but that also didn't seem right, and I didn't want to possibly ruin it so I gave up.
Any ideas on how to get in and replace the bulbs? Also what type of bulb may it be so I can order replacements?
Comment: Did you try pushing gently on the glass & turning counter-clockwise?
Comment: @brhans yep, no luck on either of the sockets.
Answer: That looks like an old school can/recessed light which utilized flood light style bulbs. You should be able to apply slight pressure with your finger tips while turning counter clockwise to loosen/remove the bulb.
Comment: @TymoteuszPaul - if you can't get it with your hands, I doubt a cup will help you. Those lights get really hot and are probably fused to the the paint on the escutcheon and to the socket to some extent. Go nuts and when you break it, go buy LED replacement 'can' lights to cover the hole.
Comment: yes, you should be able to unscrew the light bulb with finger pressure, or maybe try to find a suction cup that will grip the exposed surface of the bulb.
Comment: @Mazura those don't get so hot, those are CFLs.  You can see the screwball behind the bezel.
Comment: I just gave that a try and no luck, and just to be sure tried on few different bulbs as they are indeed quite old. Guess can go and buy a suction cup tomorrow and see if that will do.
Comment: @Mazura aw, not the answer I was hoping for. Ah well, thanks for that and guess will go shopping for someone to come and replace the lights with leds. Accepting the answer as it's correct, at least in theory of it ;).


Will this command block always teleport the correct player(s)?

Question: Does that teleport the player closest to the command block or the player closet to the coordinates in the execute portion?
May goal is to teleport anyone that steps in a specific block, but I want to make sure I'm doing it right
/execute @a[x=112,y=34,z=14,r=1] ~ ~ ~ tp @p 90 29 8

Comment: Err, try running it?
Comment: Works great when I run it, but I'm the only player....so I'm always the closest player to both blocks, so running it doesn't really help me here :\
Comment: Try running it in mltiplayer. Make sure there is another player there.
Answer: You should skip the execute command and use the target selector with arguments in the tp command:
/tp @a[x=112,y=34,z=14,r=1] 90 29 8

If you want to use the execute command for some reason, use the @s target selector in the tp portion of the command.  This selects the entity which executed the command. This would be the same entity the execute command targeted within the coordinates:
/execute @a[x=112,y=34,z=14,r=1] ~ ~ ~ tp @s 90 29 8

Comment: Thanks.  I think I'll switch mine over to this, since it guarantees it affects the right people unambiguously.
Comment: Question for you, you mention 2 command blocks.  What is the 2nd for?  Is that 2 per teleport station for a `testfor` block as the first?
Comment: Sorry, I think I was probably ambiguous.  There's one command block.  The two blocks are the command block and the block they step into to be teleported.  I was asking when using the `/tp @p` method, if the proximity was in proximity to the block used in the `execute` portion, or to the command block itself.  Once you pointed out to just use `@a` again, that part of my question became irrelevant.
Comment: Because your adding the selectors to the `/tp` the `/execute` part is unnecessary, also if I remember correctly `r=1` will have a 3x3 around the center as such `r=0` would be more accurate, if the coordinates is the location the player will stand, not the block they will stand on
Answer: Yes, it does target the player standing on the block.
However, in the extremely unlikely case that two players stand on exactly the same coordinates, it could have issues where one player targets the other player and therefore he himself is not teleported. If you don't turn off the command block the next tick or do something else that prevents it, that's not a big issue, he would just be teleported the next tick, because then he's the only player left there.
But if you want to be completely sure that you always target everyone instantly, you can replace the @p in your command with @s, which always targets the command executor.
Or in your specific case, you could also just replace the whole command with
/tp @a[x=112,y=34,z=14,r=1] 90 29 8

That has the exact same effect.
And if you want to test something with @p in the future, you can just use @e[c=1], this does the same as @p, but with all entities. Then you can just put a bunch of sheep everywhere to test. You could also use items, but sheep are cuter.
Comment: Also: In 1.13 you will be able to use `@a[x=112,y=34,z=14,dx=1,dy=1,dz=1]` to target exactly everyone on that block, because there will be no more centering on the block. You could then even use `dy=0.1` for players on the ground, because it will allow non-integers. Currently it doesn't.
Comment: that sounds useful, is the dx, dy, dz, part documented o the wiki?  I'm guessing from context, that it's either an offset "distance" or shape, "diameter" but I'm not certain just by reading it.
Comment: Yes, it's in the wiki: https://minecraft.gamepedia.com/Commands#Target_selectors It's the size of a selection box.
Comment: Archive: https://minecraft.gamepedia.com/index.php?title=Commands&direction=next&oldid=1204429#Target_selectors


Python: .send function of socket programming

Question: I send some message 'hello' from client to server using this command on server
    #Send some data to remote server
    message = 'hello'

    try :

    s.send(message)
    print 'data sent successfully'
    except socket.error:
    #Send failed
    print 'Send failed'

Now on server side , I want to check whether this message is present as a key in dictionary which is created on server side.
    msg=c.recvfrom(1024)

     if msg in data2.keys():
 print("key for this msg exists", msg)
     else:
     print("no such key exists",msg)

Now, the problem is it always says no such key exits. When I print the msg on server side which I have got from client.It comes out to be:
   ('hello', None)

I don't get it why it gives None along with hello.
because of this I am not even getting a match in dictionary. Please tell me where I am doing wrong.
Answer: As the documentation for socket states: The return value is a pair (string, address) where string is a string representing the data received and address is the address of the socket sending the data.
So your ('hello', None) is this pair and if you want to pick the message string from it to search it in your dict, you have to use msg[0].
Answer: If you look at the documentation for socket.recvfrom() you will see that it returns a tuple.  If you only want the data portion, you're better off just calling socket.recv().


Remove light switch

Question: I have a back room that was converted from a back porch to a room. It has a light switch on one wall that doesn't appear to work anything. I checked to see if it has current coming to the switch and it was showing less than 1 volt. The switch is very old and has 2 red wires and 2 black wires coming to and going away from it. How do i safely eliminate  this switch? I do not want to replace it with another. I just want it gone.
Comment: When you measured voltage how did you do it?  One test lead to each switch screw?
Comment: Are you in the UK?
Comment: My moms furnace has a switch in the mud room / pantry. Several years ago she asked if I would remove it because she forgot what it controlled, took a few minutes but I traced the DPST switch to the blower motor 240v , good thing I did not remove it. You should always know what you are doing and what it feeds.
Comment: What happens if you remove each wire, cap them and turn the power back on?
Comment: Is it possible that it used to control say the top half of the duplex outlets, and then someone replaced one or more of them and failed to break off the tab?
Answer: Shut off power and trace the cables leaving that box. (See How to trace mystery switches.) Once you've identified the cables and confirmed they're truly not connected to anything else, you can cap them in the box or cut them back (see What is the proper way to leave unused nonmetallic sheathed cable inside walls or ceilings?), remove the box, and patch the wall.
Answer: Turn off the power at the circuit breaker for safety. Cap all wires with a wire nuts. Replace with blank faceplate and then turn the power back on.
Comment: Not a good idea to disconnect all the wires and individually cap them. The switch might be acting as a splice connector.
Comment: Given the reference to "red" and "black" wires, the OP is much more likely to be in the UK than the US.  Wirenuts are forbidden in the UK.

Remove light switch


4Store vs Sesame, features

Question: I'm looking for a triple store to use with Java EE.
I ended with 2 possibilities, 4Store and Sesame but can't see the real difference between the two in term of features.
I don't mind about performances details.
Comment: Your question is likely to be closed as this kind of "opinion-based" question is considered off-topic for this site. I recommend that you try and determine what your requirements are, then find out how each tool meets those requirements, and then pick one. If you have more specific questions about either tool, you might also try answers.semanticweb.com.
Comment: Thx for your comment. I'm asking what are the differences in term of features, I don't think this is "opinion-based", that's facts.
Comment: I don't dispute that, but any answer you get is likely to be opinion-based in the sense that it will highlight a particular feature of one tool. Without knowing more about your use case requirements it's not really possible to make a valid objective recommendation.

Having said that, I gave it a stab, hope it's useful, I've tried to be as objective as possible.
Comment: My use case is quite simple : import RDF, store in a triple store, setup a SPARQL end point.
Answer: I can't give you a full list of features for either tool, but I reckon that an important difference for your use case (given what little you've told us) is that wile 4Store is an RDF database implementation (or "triplestore"), Sesame is a framework API for handling RDF in Java, giving access to multiple triplestore implementations (including some of its own, but also many third-party products). The possible advantage of this is that it allows you switching to a different database (if you so require) without major changes to your code.
I would also imagine that Sesame's API, being developed in and for Java, is slightly more feature-rich and easy to use in a Java EE environment, but this is merely an assumption as I am not sufficiently familiar with 4Store to make an actual comparison.
(disclosure: I am on the Sesame development team)
Comment: Thanks, I see the main difference between the two system and can guess that for a simple use case there isn't big differences.

4Store vs Sesame, features


Accessing google spreadsheet using shared link

Question: I am building a python app where user can provide 'Anyone can edit' link to their spreadsheet and data can be read from there. I am using python's gspread module but it throws SpreadSheetNotFound error.
<code>import gspread
from oauth2client.service_account import ServiceAccountCredentials
scope = ['https://spreadsheets.google.com/feeds']
credentials = ServiceAccountCredentials.from_json_keyfile_name('myauth.json', scope)
gc = gspread.authorize(credentials)
wks = gc.open_by_url(urls_given_by_user_having_edit_permission)
</code>
Above code is not working. Is there any way to achieve this?
Comment: Could you share the `urls_given_by_user_having_edit_permission` format? Just to give a general idea of a value. You may omit some characters if you'd like to hide the real value.
Comment: @Burnash its like https://docs.google.com/spreadsheets/d/1N0_Ao-U2Euub0_cadx44R3EPMpEC0KUJW-t3E where value after d/ is the key. I am searching for any way to get the above task done, not stringent on gspread.
Comment: did you try to open the spreadsheet by key? https://github.com/burnash/gspread#opening-a-spreadsheet
Comment: another possible solution is to access your spreadsheets via json interface: https://spreadsheets.google.com/feeds/list//od6/public/values?alt=json for list, and https://spreadsheets.google.com/feeds/cells//od6/public/values?alt=json for cells
Comment: @Burnash by key extracts key from url, that's it and that didn't work as well. Feeds will give spreadsheets from out own account, isn't it? I was looking to access doc of another user that is shared with edit permission.
Comment: You're right, it won't work with public sheets. Only with private sheets _shared_ with client email address. Did you try accessing your spreadsheets with json api links?
Comment: did you ever find a solution?
Answer: wks.share('', perm_type='anyone', role='reader')
Read permission for all people with link. reference https://gspread.readthedocs.io/en/latest/api.html#gspread.models.Spreadsheet.share


Setting NSPredicate in Swift CoreData

Question: Am Rewriting my existing objective c code(ios) to swift and now am facing some issues with Coredata NSPredicate in swift as there is some many to one relationships and vice-versa.. am using the following code,
    let fetchRequest = NSFetchRequest(entityName: "TUMessage")
    let sortSequence = NSSortDescriptor(key: "sequence", ascending: true)
    let sortTime = NSSortDescriptor(key: "epoch_time", ascending: true)
    var filterPredicate:NSPredicate = NSPredicate(format:"thread == [c] %@",contact.threads.anyObject())
    fetchRequest.predicate = filterPredicate
    var sortDescriptor:NSArray = NSArray(objects: sortTime,sortSequence)
    fetchRequest.sortDescriptors = sortDescriptor
    fetchRequest.fetchBatchSize = 50
    return fetchRequest

where    "TUMessage" is the table we need to fetch data from,  "sequence" for sorting the fetched result, "thread == [c] %@" is a relationship of message table (many to one since each contact have multiple thread) ,
and  contact.threads.anyObject() is the predicate which am trying to add.Unfortunately am getting the following error
  type anyobject? does not confirm to protocol, CVarArgType

Any help would be appreciated..
Thank you
Comment: I can't check it at the moment, but I assume that you have unwrap the optional: `contact.threads.anyObject()!`
Comment: If thread is a relationship, why are you performing a case insensitive search using [c]?
Answer: You need to unwrap it and cast to the specific class
contact.threads.anyObject()! as MYClass

Setting NSPredicate in Swift CoreData


Complete the character table of a group with 4 conjugacy classes containing 1, 3, 4, 4 elements, respectively

Question: Consider a group $G$ with exactly 4 conjugacy classes $C_1,\;C_2,\;C_3\;C_4$ containing exactly 1, 3, 4, 4 elements, respectively. Let $\zeta$ be a primitive third root of 1 and the following table its character table. Complete it.

My attempt: The group has 4 irreducible representations. Let $\chi_0, \chi_1, \chi_2, \chi_3$ the corresponding irreducible characters. Using the character of the regular representation I found that
$\chi_0(1)=\chi_1(1)=\chi_2(1)=1$ and $\chi_3(1)=3$.
Now, since each element of $C_2$ has order 2, then $\chi_0(g)=\chi_1(g)=\chi_2(g)=\chi_3(g)=1$, where $g$ is an element of $C_2$.
Also using that $1=<\chi_2,\chi_1>$, I found that $\chi_2(g)=2-\zeta$, where g is an element of $C_4$.
Therefore, so far the table goes like this.

Problem: I don't know how to find the other four values. I have tried with the orthogonality rules but I have not been able to eliminate any of the 4 unknowns.
Comment: I think you'll have to explain more clearly where your $2-\zeta$ comes from (I think it's wrong - surely $\chi_0, \chi_2$  are orthogonal is what you  need). You say $\chi_3(1)=3$ but in the table you seem to show $\chi_3(1)=1$. Hint: the complex conjugate of a character is a character. Hint. If an element has an unreal character it is not conjugate to its inverse.
Comment: I just realized what my mistake was in the above calculation. $<\chi_2,\chi_0>$ should be 0 and no 1.
Comment: I did this to calculate $\chi_2(g)$. $12<\chi_2,\chi_0>=\sum_{t\in G}\chi_2(t)\chi_0(t)*=\sum_{t\in G}\chi_2(t)=\chi_2(id)+3\chi_2(g_2)+4\chi_2(g_3)+4\chi_2(g_4)=1+3+4\zeta+4\chi_2(g_4)$. Then $3=1+\zeta+\chi_2(g_4)$,  i.e $\chi_2(g_4)=2-\zeta$, where $g_i$ is a representative of the conjugacy class. You're right, I have a mistake in the table, I should put $\chi_3(1)=3$.
Answer: (a)
At the outset we have (if we add the trivial character)
$$
\begin{matrix}
1 & 1 &1 &1\\
1& & \zeta&\\
\\
\\
\end{matrix}.
$$
(b) Recall that the complex conjugate of an irreducible  character is also an irreducible character and get
$$
\begin{matrix}
1 & 1 &1 &1\\
1& & \zeta&\\
1 & &\zeta^2\\
\\
\end{matrix}.
$$
(c) Use the fact that $|G|=1+3+4+4$ to get
$$
\begin{matrix}
1 & 1 &1 &1\\
1& & \zeta&\\
1 & &\zeta^2\\
3& \\
\end{matrix}.
$$
(d) Use the fact that $|C_3|=4$ to see that the length of the 3rd column is $12/4=3$ and so get
$$
\begin{matrix}
1 & 1 &1 &1\\
1& & \zeta&\\
1 & &\zeta^2\\
3& &0 &\\
\end{matrix}.
$$
(e) Note that as the second character is not real on $C_3$ the elements of $C_3$ are  not conjugate to their inverses, so their inverses form a distinct class, say $C_4$, and each character on $C_4$ is the complex conjugate of the values on $C_3$, since the eigenvalues of the representation on $C_4$ are the inverses of the eigenvalues of the representation on $C_3$. So we have
$$
\begin{matrix}
1 & 1 &1 &1\\
1& & \zeta&\zeta^2\\
1 & &\zeta^2&\zeta\\
3& &0 &0\\
\end{matrix}.
$$
(f) Use the fact that the second column is orthoogonal to each of the other columns, to see first that it is orthogonal to the sum of the other three columns, and so get
$$
\begin{matrix}
1 & 1 &1 &1\\
1& & \zeta&\zeta^2\\
1 & &\zeta^2&\zeta\\
3&-1 &0 &0\\
\end{matrix}.
$$
(g) Use whatever orthogonality relations you like to complete the table and get
$$
\begin{matrix}
1 & 1 &1 &1\\
1& 1& \zeta&\zeta^2\\
1 &1 &\zeta^2&\zeta\\
3&-1 &0 &0\\
\end{matrix}.
$$
Note. I think it is possible to do this without the hypotheses that the four classes have orders $1,3,4,4$ but it's a bit harder.
Answer: Here is a proof that does not use the sizes of the classes, just that it has four classes. Let $x_i$ be an element from class $C_i$. We start by inserting the trivial character, the action of $\chi_2$ on $x_3^{-1}$ (which, since $\chi_2$ acts as $\zeta\not\in\mathbb R$, must not be conjugate to $x_3$), then the dual of $\chi_2$, to obtain the following partial table.
$$\begin{matrix}
&x_1&x_2&x_3&x_3^{-1}\\
\chi_1&1&1&1&1
\\\chi_2&1&&\zeta&\zeta^2
\\\chi_3&1&&\zeta^2&\zeta
\\\chi_4&a
\end{matrix}$$
Now let's compute the order, which is $1+1+1+a^2$. Since the order of $x_3$ is a multiple of $3$ (as the image of $x_3$ under the homomorphism $\chi_3$ has order $3$), $3\mid |G|=3+a^2$. Thus $a$ is a multiple of $3$, and in particular, $|G/G'|=3$. Thus $G'\neq 1$, and some non-trivial class must be in it. This is $x_2$.
$$\begin{matrix}
&x_1&x_2&x_3&x_3^{-1}\\
\chi_1&1&1&1&1
\\\chi_2&1&1&\zeta&\zeta^2
\\\chi_3&1&1&\zeta^2&\zeta
\\\chi_4&a&b
\end{matrix}$$
Now by column orthogonality, $ab=-3$. But $3\mid a$, and $b$ is an algebraic integer. Thus $a=3$, $b=-1$. Finally, $\chi_4$ is clearly real, so its values on $x_3$ and $x_4=x_3^{-1}$ are the same.
$$\begin{matrix}
&x_1&x_2&x_3&x_3^{-1}\\
\chi_1&1&1&1&1
\\\chi_2&1&1&\zeta&\zeta^2
\\\chi_3&1&1&\zeta^2&\zeta
\\\chi_4&3&-1&c&c
\end{matrix}$$
Column orthogonality with (say) $x_1$ gives the result. If you don't want to work with any complex numbers, note that orthogonality of columns 1 and 3 gives $\alpha+3c=0$ for some $\alpha$, and columns 2 and 3 gives $\alpha-c=0$. Thus $c=0$.
$$\begin{matrix}
&x_1&x_2&x_3&x_3^{-1}\\
\chi_1&1&1&1&1
\\\chi_2&1&1&\zeta&\zeta^2
\\\chi_3&1&1&\zeta^2&\zeta
\\\chi_4&3&-1&0&0
\end{matrix}$$
Comment: Well done @David. I see you get $c$ last: my own taste (for historic reasons) is to get it first by observing that $C_3$ must contain an element of order $3k$, and since $G$ can't be abelian we get $k=1$ and $c=0$ etc.


How soon can I group in The Secret World?

Question: I'm attempting to play The Secret World with my girlfriend.  She will have no patience for soloing whatsoever, so I need to be in her group 100% of the time in order to keep her playing.  How soon is a new character freed to group up, and what is the best way to do it?
Answer: When you create a character you will go through a short introduction level where you are escaping. This level is mainly designed to get you used to using skills and moving around the game world, but is instanced away from the rest of the game so during this time you cannot group.
Once you get past the introduction you are dropped near a town called Kingsmouth with your actual character - from this point onwards you're able to group, explore, do quests, etc.
It shouldn't take more than 15-20 minutes to do the introductory mission, and after completing this mission, most of the side quests and investigation quests through the rest of the game can be completed in a group - there are a few areas within the game that are designated as solo instances but these are clearly marked as you accept the quests and before entering the instances.
Entering these instances won't remove you from your party but you will be unable to enter them together. These instances are also optional (like every side quest in the game).
The main story missions for each faction are also solo, and cannot be completed in a group.
A full list of missions within The Secret World which cannot be completed in a group (ie: are solo only) can be found on The Secret World forums. Outside faction ranking missions and the main story, the number of missions with solo instances is probably less than twenty missions across the entire game.
Comment: Don't forget the solo dungeon bits of most Investigation and Sabotage missions. Might be worth noting. :)
Comment: If my memory serves me correctly I did many of the investigations with multiple people, but the act of one person completing a step doesn't automatically progress the investigation for all people - meaning that even though you could do them in a group, you still have to complete each step yourself.
Comment: No - you're right, the story missions are solo
Comment: Ah yeah, I remember a couple of these. I played the whole game through solo so it wasn't really a problem - entering one of these instances won't remove you from the party you're in, but you won't be able to enter them together.
Comment: Yeah, that's more what I was getting at. Not-insignificant parts of the Story Quest, and most Investigations and Sabotages have at least some degree of "I'm by myself"-ness to it.
Comment: Oh yeah, I'm not saying every one of 'em has a solo instanced part, but quite a few do. Of the ones I can remember, I think it's like 60/40 that do?
Comment: I could have sworn most of the instances in the main plot missions were solo instances, there just aren't that many.
Comment: I did a lot of the early story with people from Arqade, so I'm pretty sure that you can, I think it's down to whether or not you're members of the same faction - like I said though, it's been ages since I played so I could be wrong on the story missions
Comment: So, to clarify, the only things you can do in a group are PvP and 2/3rds of the side missions?  No paring up for the main story?
Comment: Probably higher than 2/3rds of the side missions, the handful listed in that article are only a small quantity of the missions in the game, but yes, no story missions


Android - where it is the best place to store a list of images locally?

Question: I am working at an application that currently will have data only locally (server part is not ready) - the apk must contain the displayed data too.
So I will have a list of items, each item having an image. Where it is the best place to store those images, such that the apk size is kept as small as possible?
Searching I found that /raw or /assets can be such places. Or is it better to store images as base64 encoded dirrectly in the loaded JSONs? Which is best?
Comment: No matter where you put your images, your APK still contains your images & size won't be smaller. I would suggest you to download from web server at first launch to avoid the images to be bundled in the APK.
Comment: Could you elaborate on the "loaded JSONs" ? The whole .apk file is actually a zip file, so it will be compressed the same way wherever you put it. Keep in mind that base64 means +30% in size, even though zipping should reduce the impact. If your images are more than a few MB, forget it and work on your server: 20MB for a small app is a pain for users.
Comment: I have files with the json data that i load in my app such that when the server is ready, this jsons will be comming from the server in the exact same structure. For images i suppose i will have separate URLs for getting them, but for the moment i have to manage without the server part. And I am searching for the best solution to store those images with minimal impact within my app...
Answer: your.package/assets - put any data in your app. You can save any files in this folder. This is may be JSON or BASE64.
Comment: Please elaborate your answer
Answer:
Searching I found that /raw or /assets can be such places. Or is it
  better to store images as base64 encoded dirrectly in the loaded
  JSONs? Which is best?

if you have a different image for each density you should go for ths drawable-* folders, otherwise it does not make that much difference from the apk's size perspective. I would avoid the base64 solution
Comment: could you tell me why you would avoid base64?
Comment: for once, are encoded into the json, and you have to allocate memory for the String and the Bitmap. If you use assets to store the bitmap, you can load those when you need, and you save some memory


Name of printer media trays

Question: I currently retrieve some printer information about the possible media trays with this code snippet:
 Media med[] = (Media[])printService.getSupportedAttributeValues(Media.class, null, null);
 if( med != null ) {
     for (int k=0; k<med.length; k++) {
          sb.append("Name : " + med[k].getClass() + " - Value : " + med[k].getValue() +
                " - Name : " + med[k].getName()+"\n" );
     }
 }

Sadly, this just returns some tray numbers, which I find relatively useless:
Name : class javax.print.attribute.standard.MediaSizeName - Value : 40 - Name : media
Name : class javax.print.attribute.standard.MediaSizeName - Value : 41 - Name : media
Name : class javax.print.attribute.standard.MediaSizeName - Value : 42 - Name : media
... more ...
Name : class sun.print.Win32MediaTray - Value : 5 - Name : media
Name : class sun.print.Win32MediaTray - Value : 25 - Name : media
Name : class sun.print.Win32MediaTray - Value : 26 - Name : media
Name : class sun.print.Win32MediaTray - Value : 27 - Name : media

How can I retrieve useful names?
Answer: This will give you all printer properties, including tray names
String printName = "HP Officejet Pro 8500 A910 (Network)";
AttributeSet aset = new HashAttributeSet();
aset.add(new PrinterName(printName, null));
PrintService[] services = PrintServiceLookup.lookupPrintServices(null, aset);
for (int i = 0; i < services.length; i++) {
  PrintService service = services[i];
  System.out.println(service);
  DocFlavor flavor = DocFlavor.SERVICE_FORMATTED.PAGEABLE;
  Object o = service.getSupportedAttributeValues(Media.class, flavor, null);
  if (o != null && o.getClass().isArray()) {
    for (Media media : (Media[]) o) {
      System.out.println(media + " ID: " + media.getValue() + "\t" + media.getClass().getName());
    }
  }
}

Comment: `media.toString()` (which is what you do in the println) gives a "useful" name; one has to separate between the `MediaTray` class which are the actual trays, and `MediaSizeName` class which are media sizes. These can't be used as class parameter for `getSupportedAttributeValues()`, `Media.class` still needs to be used. What a pain.
Answer: This code retrieve the Printer Name, media tray name by size and id:
public static void printByName(String printName) {
//Inicio Codigo PrintByName
    try{
        AttributeSet aset = new HashAttributeSet();
        aset.add(new PrinterName(printName, null));
    PrintService[] services = PrintServiceLookup.lookupPrintServices(null,aset);
    MediaSizeName mn=null;
    MediaSize mz=null;
    Destination dd=null;
    for (int i = 0; i < services.length; i++) {
        PrintService service = services[i];
        System.out.println(service);
        DocFlavor flavor = DocFlavor.SERVICE_FORMATTED.PAGEABLE;
        Class category = Media.class;
        Object o = service.getSupportedAttributeValues(category, flavor,null);
        if (o == null) { // Attribute is not supported
            }
        else if (o.getClass().isArray()) {
            // Attribute values are a set of values
            Media[] media = (Media[]) o;
            for (int j = 0; j < media.length; j++) {
                //System.out.println("ATributo: " + media[j].getValue() );
                if(media[j] instanceof MediaSizeName) {
                mn=(MediaSizeName)media[j].clone();
                //mz=getMediaSizeForName(mn);
                mz=MediaSize.getMediaSizeForName(mn);

                //System.out.println((media[j].toString()));
                System.out.println("\t Bandeja: \t\t"+ mn + " ID: " + mn.getValue() );
                }
                }
            }
        }
    //System.exit(0);
    } catch(Exception e){
    System.out.println("Exception is " + e);
            }
}

Name of printer media trays


How can I and improve array matrix [0,1] by row and column constraints in Python?

Question: Suppose I have an matrix array table.
uvv = np.array([[0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0],
                [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
                [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0],
                [0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
                [0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
                [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0]])

I will focus on the row that has all zero value such as row 2
Then, I would like to random 1 two or three times in some column of row 2 but that column must not appear 1 in other rows. According to uvv table,I can random 1 in row 2 at column 1,2,3,7,8,9,10,11,12,14,16,18.
This is the example of my target when add random 1 in column 2, 14, 18 of row 2:
tem = np.array([[0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0],
                [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1],
                [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0],
                [0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
                [0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
                [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0]])

Thanks.
Answer: You can use boolean mask to find rows and available columns:
m1 = ~uvv.any(axis=1)  # rows with all zeroes
m2 = ~uvv.any(axis=0)  # columns with all zeroes

rows = np.nonzero(m1)[0]  # find rows to fill
cols = np.nonzero(m2)[0]  # find available columns

for row in rows:
    idx = np.random.choice(cols, np.random.randint(1, 4), replace=False)
    uvv[row, idx] = 1
    cols = np.setdiff1d(cols, idx)

Output:
>>> uvv
array([[0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0],
       [0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
       [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0]])

# rows to fill
>>> rows
array([1])

# before the loop
>>> cols
[ 0  1  2  6  7  8  9 10 11 13 15 17]

# after the loop
[ 0  1  2  6  8  9 10 11 13 15]  # col 7 and 17 are not available now

Comment: If there is one available column but we random between two and three  in order to replace 1 ? How can I fix this when random value excess available column?
Comment: It should not be a big deal. Try to replace `np.random.randint(1, 4)` with `1+np.random.randint(min(3, len(cols)))`. Does it work now?
Answer: Solution:
Explanation is included as comments throughout the code.
# Loop over each column in array
for col_num in range(uvv.shape[1]):

    # Get column and list of non-zero row positions
    col_arr = uvv[:, col_num]
    index_pos = np.where(col_arr!=0)

    # If only zeroes exist in row, proceed
    if len(index_pos[0]) == 0:

        # Get number of times to insert a value (num_inserts)
        # Get row numbers to insert value into (row_inserts)
        num_inserts = random.choice([2,3])
        row_numbers = range(0, len(col_arr)-1)
        row_inserts = random.sample(row_numbers, num_inserts)

        # For each time to insert a value
        for i in range(num_inserts):

            # Insert value into selected row
            uvv[row_inserts[i], col_num] = 1
            print(f"Inserted value in row: {row_inserts[i]}, col: {col_num}")

Answer: Not a NumPy expert, here's a solution that works (certainly there are others which are faster and more elegant).
Used features:

[NumPy]: numpy.where

[NumPy]: numpy.any

[NumPy]: numpy.random.choice

code00.py:
#!/usr/bin/env python

import sys

import numpy as np

def modify(arr, max_row_count=1, max_element_count=3, value=1):
    ret = arr.copy()  # Don't operate on original array
    rows = np.where(~ret.any(axis=1))[0]  # All rows that only have 0s
    for idx, row in enumerate(rows):
        if idx >= max_row_count:
            break
        column_choices = np.where(~ret.any(axis=0))[0]  # All columns that only have 0s
        #print(column_choices)
        columns = np.random.choice(
            column_choices,
            size=min(max_element_count, len(column_choices)),
            replace=False
        )  # Select randomly from (above) columns
        ret[row, columns] = value
    return ret

def main(*argv):
    arr0 = np.array([
        [0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0],
        [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
        [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0],
        [0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
        [0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
        [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1-1, 0, 0, 0]
    ])
    print("Original:\n{:}".format(arr0))
    for i in range(3):
        arr = modify(arr0)
        print("\nModified (variant {:}):\n{:}".format(i + 1, arr))

if __name__ == "__main__":
    print("Python {:s} {:03d}bit on {:s}\n".format(" ".join(elem.strip() for elem in sys.version.split("\n")),
                                                   64 if sys.maxsize > 0x100000000 else 32, sys.platform))
    rc = main(*sys.argv[1:])
    print("\nDone.\n")
    sys.exit(rc)

Output:

(py_pc064_03.08_test0_lancer) [cfati@cfati-5510-0:/mnt/e/Work/Dev/StackExchange/StackOverflow/q077032322]> python ./code00.py
Python 3.8.18 (default, Aug 25 2023, 13:20:30) [GCC 11.4.0] 064bit on linux

Original:
[[0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 1 0]
 [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0]
 [0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0]
 [0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0]
 [0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0]
 [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0]]

Modified (variant 1):
[[0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 1 0]
 [1 0 1 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0]
 [0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0]
 [0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0]
 [0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0]
 [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0]]

Modified (variant 2):
[[0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 1 0]
 [0 0 0 0 0 0 0 0 0 0 0 1 0 0 1 1 0 0]
 [0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0]
 [0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0]
 [0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0]
 [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0]]

Modified (variant 3):
[[0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 1 0]
 [0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 1 0 1]
 [0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0]
 [0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0]
 [0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0]
 [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0]]

Done.


Switching from Nvidia to Radeon graphics card in year 2015

Question: I am going to switch my monitors from an Nvidia graphics card to a Radeon Saphire FLEX series 250x (specifically, this model).
How should I prepare my 14.04 system so that it simply works once the card is installed? you will forgive me for not acting by answers from circa 2012 here because drivers and hardware have come a long way since. It would be wiser for me to act in preparation mode rather than in fire fighting mode.
What might be the series of steps to take for (1) preparing my system, and for (2) making the transition in the OS?
Comment: @Zacharee1 its not as easy as PnP. You need to reconfigure graphic driver then display manager. New ati should be working with fglrx proprietary driver.
Comment: You should be able to just plug and play.
Comment: Are you sure that card is supported?
Comment: @Zacharee1 not from a nVidia - different drivers etc
Comment: @AizuddinZali yeah that makes sense.
Comment: @tim good point, I somehow didn't even check that. Where might that be determined??
Comment: @matt well I cant't see it on the listed supported cards on the wiki - and it's no longer manufactured afaik...
Comment: @Tim, which wiki? [here I see drivers for the r7 200 series](http://support.amd.com/en-us/download/linux) (of which 250x is part according to what I see in the [Saphire offical website](http://www.sapphiretech.com/productdetial.asp?pid=63E4AD88-F755-484B-B594-64CCD763FD4B⟨=eng))
Comment: @matt https://help.ubuntu.com/community/RadeonDriver#Fully_Supported
Comment: The list is not exhaustive so not sure what to make of it. Sometimes I miss Microsoft Windows...
Answer: install fglrx driver using terminal commands
https://help.ubuntu.com/community/BinaryDriverHowto/AMD
Comment: You shall not post an answer referring to other link.
Comment: Its ok, try to improve the answer then you`ll have up vote from me
Comment: Welcome to Ask Ubuntu! Whilst this may theoretically answer the question, [it would be preferable](//meta.stackoverflow.com/q/8259) to include the essential parts of the answer here, and provide the link for reference.
Comment: new to askubuntu..just trying to help..sorry man...@ Aizuddin Zali
Comment: That wiki page is a bit perplexing:
Quote: "If you are switching from another OEM's hardware, NVIDIA for instance, you must uninstall the driver for that hardware before installing the AMD driver." doesn't that leave you headless???!? :)


Webservice call results in WSAStartUp Error after 3 succesfull calls

Question: I have a C# winforms application which functions as a server for some access devices through a .DLL.
User access is determined by sending input to a webservice (set up as a webreference), and returning the results to the devices, however in case of a timeout, the app disconnects all devices, stops the server, and starts up a backgroundworker. The backgroundworker retries the connection to the webservice, and if succesfull, starts up the server again, and reconnects the devices.
This all works very well, but unfortunately, on the third fourth or fifth time, the backgroundworker tries to reconnect to the webservice, the connection fails with an exception "Either the application has not called WSAStartup, or WSAStartup failed" . each following try, gets a simmilar error.
Here is the source for the backgroundworker, its very simple code:
private void backgroundWorkerStopServer_DoWork(object sender, DoWorkEventArgs e)
    {
        System.Threading.Thread.Sleep(2000);
        stopServer();

        NewDoorCheck.Doorcheck ndoorcheck = new NewDoorCheck.Doorcheck();
        ndoorcheck.Timeout = 15000;

        bool disconnected = true;

        while (disconnected)
        {
            try
            {

                ndoorcheck.WebserviceIsUp();

                UpdateLog("Connected web");
                disconnected = false;
                startServer();
            }
            catch (Exception ex)
            {

                UpdateLog(ex.Message);
                UpdateLog(ex.StackTrace);
                UpdateLog("Still Down");
                System.Threading.Thread.Sleep(60000);
            }
        }

As a side note, the webservice works like a charm otherwise.
Answer: I ended up solving this by calling WSAstartup manually in the exception handler, and retrying.
Import of Winsock
class WSAinterop
{
    [StructLayout(LayoutKind.Sequential)]
    internal struct WSAData
    {
        public short wVersion;
        public short wHighVersion;
        [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 257)]
        public string szDescription;
        [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 129)]
        public string szSystemStatus;
        public short iMaxSockets;
        public short iMaxUdpDg;
        public int lpVendorInfo;
    }

    [DllImport("wsock32.dll", CharSet = CharSet.Ansi, SetLastError = true)]
    internal static extern int WSAStartup(
          [In] short wVersionRequested,
          [Out] out WSAData lpWSAData
          );

    [DllImport("wsock32.dll", CharSet = CharSet.Ansi, SetLastError = true)]
    internal static extern int WSACleanup();

    private const int IP_SUCCESS = 0;
    private const short VERSION = 2;
    public static bool SocketInitialize()
    {
        WSAData d;

        return WSAStartup(VERSION, out d) == IP_SUCCESS;
    }

    ///
    /// The main entry point for the application.
    ///
}

And simply use the SocketInitialize() Method.
bool startup = WSAinterop.SocketInitialize();


How can I prevent my outside heat pump coils from icing over?

Question: My outside unit is on the north side of my house and under an area that water drains to. I have put up gutters and placed a small roof above the unit, but still the coils freeze up during winter.  I'm looking for more ideas to help with this freezing problem, and ways to defrost it quicker, like rock salt, defrosters, etc. Would these methods damage the coil?
Comment: uh, keep *what* from freezing?
Comment: I know this is a do-it-yourself forum, but I suggest you do-it-yourself by phoning the contractor who installed the unit, and/or the unit manufacturer and get their advice. Seems to me that they are the key experts who should be able to guide you.
Answer: Heat pump?
Keep salt away from the unit. Salt will attack and totally decompose the fins and will create electrolytic corrosion in the joints between aluminum and copper leading to destruction of the system.
Icing during operation in a damp climate is normal, it's supposed to have a defrost cycle it runs through to remove the ice.
Heat Pump Operation: Heat pumps work on the standard phase change refrigeration cycle. In summer time for AC mode, the inside unit acts as the refrigerant evaporator and the external unit as the condenser. This is reversed in the cool season for heating, the external unit basically cools the outdoors in order to extract heat from the air and gives it up by condensing the refrigerant in the inside unit.
Heat Pump Defrost cycle: Since you're cooling already cool air that contains some water vapor, it's natural for frost to build up. In extremely damp climates, the fins can actually clog. To take care of this ice buildup, the heat pump system uses its shuttle valve to momentarily go into AC mode, shuts off the air circulation fan and extracts some heat from the house to be given up when the refrigerant condenses in the external units coils.
Operational failures that cause extreme icing: Older systems run this defrost cycle off a timer, newer ones have temperature sensors to determine frosting and the heating necessary to clear the coils. Failures in these can stop the defrost cycle from being run.
You can also have the shuttle valve relay fail or the shuttle valve freeze into the heat position which prevents the cycle reversal needed to do the defrost.
For Heat Pump systems that run as flooded evaporator type systems, low freon levels will cause extreme icing of the evaporator. This can cause the internal unit to become a solid block of ice during the AC season and for the external unit to do the same during heating season.
DIY Remedies: You've taken care of one major problem, keeping water from entering due to roof drain-off.
The unit must also be in a location that allows for water to drain away. Ponding allows for excessive water vapor in the atmosphere and is to be avoided. A drainage system that removes this would be a good idea.
So if you've taken care of drainage, it's probably time to have your local HVAC tech come out and give it a through inspection to figure out what's failed.
Comment: Yeah, sounds like your defrost cycle might not be kicking on?
Answer: I have been installing on average 10 new heat pump systems per year for the last 25 years. Every year there seems to be one customer that likes to stand next to their new heat pump when it is 40 degrees Fahrenheit and raining. Yes, when it is heating your home by removing heat from the air outside it will begin to build ice up on the coils. This is normal and will be removed when the system determines the ice needs to be removed. Please back away from your new heat pump and allow it to do its thing!


How can I encrypt a plaintext with given key and iv using AES-128-CTR in python 3.7?

Question: I am trying to use python 3.7.3 to encrypt a given plaintext with a given key and a given iv. I am unfamiliar with python encryption libraries but have looked around for a couple hours trying to figure this out, and I am unable to.
I have tired using the pycryptodome library as I have been unable to use crypto and pycrypto (keep getting errors when I install them, maybe because I am on windows?).
from Crypto.Cipher import AES
from Crypto.Util import Counter

data = b"plaintext"
key = b"5A557AC90890B2ACD59C536FE4279BBC"
iv = b"5A557AC90890B2ACD59C536FE4279BBC"

counter = Counter.new(128, initial_value=iv)
cipher = AES.new(key, AES.MODE_CTR, counter=counter)

enc = cipher.encrypt(data)

print(enc)

My end result is to print out the encrypted string, but currently I am getting various errors such as "not supported between instances of 'bytes' and 'int'"
Answer: Your code does not use Counter correctly. You are trying to use hexidecimal where an integer should be, and even if you converted your iv value to an integer it would be too large.

initial_value (integer) - The initial value of the counter. Default
  value is 1.

So changing the code to the following would work for example:
counter = Counter.new(128, initial_value=1)

If you want to randomize the iv you could do something such as:
iv = int.from_bytes(os.urandom(16), sys.byteorder)
counter = Counter.new(128, initial_value=iv)


What's the best approach in migrating currently C# and VB.net (Windows) developed applications?

Question: I would like to start to "translate" my Windows applications to Ubuntu users. These are mainly CRMs or CRM related programs written in VB.net and C#.
What would be the best language and IDE for these kind of projects in Ubuntu? This is the first time in my life when Googling confused me instead of helping with the decision.
Comment: Note for the Close voters: I don't think, this is an off-topic question on the site. Since developing on Ubuntu and related IDE suggestions are accepted.
Comment: Welcome to Ask Ubuntu! Have you considered Mono? This must have been one of the first hits in Google about C# development in Ubuntu. It should not be too hard to migrate your code to be Mono-compatible. @ close-for-offtopic-voter(s): this is a valid development question in my opinion. Also see [How should we interpret "Development on Ubuntu" in the FAQ?](http://meta.askubuntu.com/questions/5744/how-should-we-interpret-development-on-ubuntu-in-the-faq)
Comment: Why are people downvoting this question?

It is quite valid: Gilad has already made applications on Windows, and is after assistance on how to reproduce them or repackage them in Ubuntu.
Comment: You'll probably be better off asking this on Stack Overflow (http://stackoverflow.com/), a dedicated software development Q&A site similar to AskUbuntu.
Answer: Since your application uses .NET framework, You could use MONO project, which is open-source implementation of Dot net framework. A good IDE for mono is monodevelop. You can install it from Software center.
or using the terminal: sudo apt-get install monodevelop
Comment: Thanks.... Is it .net framework with the same class libraries like in win?
Comment: Yes. at least most of it.
Answer: You can now try visual studio code. Microsoft's Visual Studio Code is an Integrated Development Environment (IDE) with support for Mac, Linux and Windows.


How to angle the Churchill VII to minimize the chance of being damaged?

Question: I've calculated that using the Churchill VII if I angle my tank roughly 32 degrees relative to my target my effective armor will be something around 179mm which is very good in a Tier VI match. What I've noticed however is that there is a weak spot in the inner side of both tracks next to the UFP where even a lower tier tank can score a hit relatively easily.
My question is: how should I angle my tank? In order to protect the hole next to the tracks (is this a bug or intentional?) I have to be angled 0 degrees (no angling) so a tank in front of me can't hit it but in that case I'm not angling at all!
What is the best tactics in case of an 1v1 with another tank when driving the Churchill VII?
Comment: I've never driven the churchill but if it has decent turning rate you can try wiggling to make that weakpoint harder to hit.
Comment: I wouldn't wiggle the turret much as that could possibly screw with *your* aim.
Comment: I was wondering whether front/back or left/right wiggling would help and I think that front/back is better when angled properly. Thanks for the tip.
Comment: Should I wiggle my turret as well? It has the same armor layout as the hull. (best when angled at 32 degrees)
Answer: All tanks have weak spots by design, otherwise everyone would roll only with that one I suppose :)
To protect the hole, you cant do considerably much. Those, who are aware of this weak spot, they will just chase it, and many tanks are faster than Churchill VII.  Wiggling from 0° is useful, you can get the enemy to a bit mess up aiming and only to rely on RNG to hit you on weakspot if you care to close-reopen weakspots fast and you can keep focus on him. Left-right is better, because only top end light tanks have that acceleration that would help reasonably to deflect shells relying on extra reverse speed (+7-15 km/h). Forward-reverse wiggle generated unpredictability for aiming has less efficiency by my experience. A cold-blooded foe can easily stay patient to not reload gun because of missed shot. I would suggest aslo to avoid turret wiggling. It has relatively more weakspot area, and majorly decreases your aiming.
There is no best 1v1 tactic, all are different and unique to win. Depends on enemy player.