asp.net mvc4 EF5 Singleton?

Question: I have a project going on and I'd like to have one unique instance of a class.
I have a 'JobOffer' class, which has a property of type 'OfferStatus' (which is abstract and implements a state pattern). I have 'StateAvailable' and 'StateUnavailable' (or 'open' and 'closed' if you wish).
The 'JobOffer' objects have to be stored in the db.
I'd like to have just one 'StateAvailable' and one 'StateUnavailable', so when I create a new JobOffer I reference to 'StateAvailable' or 'StateUnavailable', and then I could list all the jobOffers which are Open (available) and all that are Closed (unavailable).
I know that I could do this by adding the states in the db in the seed method, and never instantiate a new state.
But I was wondering if it is possible to do a singleton or something to avoid that somebody (I mean controller, model or anything) can create new instances of that class.
public class JobOffer {
public int JobOfferId {get;set;}
public OfferState State {get;set;
public virtual ICollection<Person> People {get;set;}

//And some methods here, which depends on the state
//ie, this.State.myMethod();

Comment: do you have some code of JobOffer , please post it
Comment: Why don't you simply make it a Boolean and call it StateAvailable?  When unavailable it will be false, when available true.
Comment: Yes, I indeed thought of that, but it's for a college project and the teachers stated very clear that it should be a state pattern, just in case it could be scalable. I mean, today we have open and closed states, but maybe tomorrow we can have 'pending' state, or something. So that's why ;)
Comment: One of the worst things to do is to forcibly apply a design pattern when it's not needed. Especially when learning about patterns. The patterns should be applied if you recognize a problem solvable by a known pattern. In your case here, an OfferState enum is more than enough to handle future states. Don't complicate things no matter what some teachers say. They don't code and they don't have to MAINTAIN code for a living :D
Comment: Yes, I kow, but I have to finish the project and send it to them. And they want it to be a state pattern.
I mean, if I don't use a state pattern they **will** take points out of my work. This is for a final exam, so kinda need a nice score :)
Comment: That's the reason I hate school.
Answer: My first thought was to use a boolean. Then you said you have to be able to expand to have more states, so I thought of an enum. Then you said you have this requirement to use a class, so... here's a little something I use when I want an enum with more smarts. You could call it a sort of "enumerating class", I suppose. So, your OfferState class looks like this:
public sealed class OfferState
{
    public bool CanChangeState { get; set; }
    //whatever properties you need

    public static OfferState Available = new OfferState(true);
    public static OfferState Unavailable = new OfferState(true);
    public static OfferState Closed = new OfferState(false);
    //whatever states you need

    public OfferState(bool canChange)
    {
        CanChangeState = canChange;
    }
}

This acts kind of like an enum, but it has properties like a class. So in your logic, you can check state:
if (jobOffer.State == OfferState.Available)
{
    //stuff
}

You can also get properties off it, so you can use it to get information about the state:
jobOffer.ExpiryDate = jobOffer.CreationDate.Add(OfferState.Available.MaxDuration);

And of course, the static nature of the various states will ensure that there's only ever one instance of each.
Comment: Thanks anaximander, but it has to have a different class for each state. I currently have abstract class 'state', 'available' class and 'unavailable' class wich both inherits from 'state'. State defines some methods that each child overrides.
In a way, your idea kind of solve it, however I am forced to use a different class for each state and the jobOffer class needs to have a state (and as the jobOffer have to be stored in the db, EF forces me to make 'state' class persistant). I only want (need) to have one object of every state, not in a class but in the entire system... Any other ideas?
Comment: Huh... this is why using a pattern for the sake of it is bad. You can make your inherited state classes entirely static, I guess; you might not be able to wrap them up in the parent class but then at least you know there would just be the one. Not 100% sure how you'd link them to job offers in a way that EF likes.

asp.net mvc4 EF5 Singleton?


Unable to login Ubuntu 14.04

Question: I'm using Ubuntu 14.04.5 LTS. Laptop was working normally, I did a restart and since then I cannot login. I get to the login screen, enter password, and then this message appears for a second and login page reappears.
speed-dispatcher disabled: edit /etc/default/speed-dispatcher
saned disabled: edit /etc/default/saned
Restoring resolver state

I can access TTY and have tried the following commands:
1.
sudo chown -R $USER:$USER $HOME

2.
sudo apt-get update
sudo apt-get upgrade
sudo apt-get dist-upgrade

3.
sudo apt-get -f install

When the laptop was working I did gksudo gedit /etc/environment, edited and saved the file, closed the text editor and immediately pressed Ctrl+C in the terminal (didn't wait for the process to automatically terminate in the terminal). I'm not sure but this might be related to the login issue.
EDIT: /etc/environment/ originally contained the environment variables I defined, FOO="BAR". I had changed them to export FOO="BAR". Changed just a few, not all. But have reverted the changes after logging to TTY.
Comment: Please edit your question to include the content of your edited /etc/environment file.
Comment: @user535733 Added the info
Answer: Solved it by adding the following line to .profile,
export PATH=$PATH:/sbin

Reference: https://ubuntuforums.org/showthread.php?t=2267058&p=13236758#post13236758

Unable to login Ubuntu 14.04


How to set utf-8 as default encoding for pull request merge conflict extension in azure devops?

Question: How to set utf-8 as default encoding for pull request merge conflict extension in azure devops?
Checked the pull request merge conflict extension and azure devops, didn't found any option to set default encoding. How to set this for a repository?
Comment: Is there any update about this ticket? Feel free to let me know if the answer can give you some help?
Answer: I am afraid that there is no such option can set the default encoding to UTF-8 in Pull Request merge conflict extension.
Currently, the default encoding type is ANSI.
To change the encoding type, we need to manually select the UTF-8 option.

Note: you need to enable the feature: Use Beta Resolver in setting option, then you can manually change the encoding type.

The extension and Azure DevOps doesn't provide the option to change this default behavior.
I can fully understand your requirement. You can report the feature in the Pull Request Merge Conflict Extension Q&A.


Using positional parametrs in bash functions

Question: Here is example, in which $1 does not work.
$ cat ~/myScript
#!/bin/bash
function hello () {
echo "Hello $1"
}
hello
$ ./myScript
 Hello

Comment: You're not passing the parameter to the function.  Change `hello` at the bottom to `hello $1`.
Answer: Think of functions like mini-scripts within a script.  They are ignored by the script until called upon. So, positional parameters are ignored until passed to the function.
They are limited though as to what they can do.  I know that they cannot support if then statements within the function as they are ignored.  And there are some other rules, but you can exit your script from within a function.  If you have checking for errors with parameters those should be performed before the function is called.
You are wanting to pass positional parameters ($1, $2, $3 etc...) into your script.  However, you are expecting the positional parameter to be passed to the function.  Without specifying the parameter when you call the function, the function is not receiving the parameter.  You need to give it the parameter.
Take your script:
#!/bin/bash
function hello () {
echo "Hello $1"
}
hello

Simply by adding a $1 to the line that just says hello by itself will make it so that the parameter is passed to the function.
#!/bin/bash
function hello () {
echo "Hello $1"
}
hello $1

Now calling the script with a parameter will produce the desired output:
$ ./myscript Terrance
Hello Terrance

If you want to add a quick check to it so that it doesn't take blank input after the script, add the following check into your script before the call:
#!/bin/bash
function hello () {
    echo "Hello $1"
}
if [[ $1 != "" ]]; then
    hello $1
    exit
else
    echo "Please input a name.  Example: $0 Terrance"
fi

My example script above does a check of != which means not equal to then the two "" means blank.  So, if parameter 1 is not equal to blank then is true then it runs the function call with the parameter then exits the script after the function is called.  Else it gives my error message.  The positional parameter of $0 is the parameter of the command you just called.
Examples of my script being called:
$ ./myscript
Please input a name.  Example: ./myscript Terrance

$ ./myscript Terrance
Hello Terrance

As you keep scripting you start to learn more tricks and proper commands and how they are used.  Keep on scripting!!
Hope this helps!
Answer: It works, but maybe you do not use it like you should. $1 refers to the first parameter of the function.
function hello () { echo "Hello $1" }

declares a function so that when you call it with parameters, it prints "Hello" and the first parameter:
hello WORLDDD

prints "Hello WORLDDD"
Comment: ctrl + K
or simply click on the button that looks like this:
`{}`
or (it seems in the comments all of this doesn't work) by using the character ` (backquotes)
Comment: Tnx. By the way, how to add this fancy lines with code here. By me everything goes like one body of the text, althogh I divide it line after line..;


Weakly dense C*-algebra in a commutative von Neumann algebra and order convergence

Question: Let $H$ be a Hilbert space and $\mathscr{A}$ a commutative norm-closed unital $*$-subalgebra of $\mathcal{B}(H)$. Let $\mathscr{M}$ be the weak operator closure of $\mathscr{A}$.
Question: For given a projection $P\in\mathscr{M}$, is the following true? $$P=\inf\left\{A\in\mathscr{A}:P\leq A\leq 1\right\}$$
It seems that the infimum must exist and is a projection, but I am not able to show that the resulting projection cannot be strictly bigger than $P$. Also, if the above is true, what happens if $\mathscr{A}$ is non-commutative?
Comment: By $P=\inf U$ do you mean $P\leq A$ for all $A\in U$ and if $Q\leq A$ for all $A\in U$ then $Q\leq P$?
Comment: @SmileyCraft Yes, and if we assume $U$ is norm-bounded, then $\inf U$ is the same as $\lim U$ when we regard $U$ as a decreasing net, in the weak operator topology.
Answer: I think I found a counterexample.
Take $\mathscr{M}=L^{\infty}[0,1]$ and $\mathscr{A}=C[0,1]$.
Let $\mathbb{Q}\cap[0,1]=\left\{r_{n}\right\}_{n=1}^{\infty}$ be an enumeration of rationals in $[0,1]$, and define $$E:=\bigcup_{n=1}^{\infty}\left(r_{n}-\frac{\epsilon}{2^{n}},r_{n}+\frac{\epsilon}{2^{n}}\right)\cap[0,1]$$ for some small $\epsilon>0$ so that $m(E)$ is strictly less than $1$. Clearly, the only continuous function $f:[0,1]\rightarrow[0,1]$ satisfying $\mathbb{1}_{E}\leq f\leq 1$ is $f\equiv1$, but the projection $\mathbb{1}_{E}$ is not equal to $1$.
Comment: Yes, that gives you a counterexample. You might struggle a bit if you want to make it concrete, it's not obvious to me how to choose $\epsilon$, and the order of the enumeration probably makes a difference. It might be easier working with a the complement of a fat cantor set.
Comment: Maybe I overlook something, but the only projections in $\mathscr A$ are $0$ and $1$. If you take $P = \chi_{[0,1/2]}$, then $P$ is not the infimum of as described in the question, since the infimum is $1$.
Comment: @AndréS. If $P$ is the indicator of $[0,1/2]$, then the set described in the question is the set of all continuous functions $f:[0,1]\rightarrow[0,1]$ such that $f(x)=1$ for all $x\in[0,1/2]$. So in this case, $P$ is indeed the infimum of that set. The fact that there is no nontrivial projections in $\mathscr{A}$ does not matter here.
Comment: Ah okay, I had projections in $\mathscr A$ in mind. So is the pointwise infimum of those continuous functions that majorize the indicator, call it $P$, then the infimum in the sense of operators on $L^2([0,1])$ ?
Comment: @AndréS. Yes, and the pointwise infimum as functions on $[0,1]$ is equal to the infimum in the sense of operators in this case, because the pointwise infimum can be obtained by a countable sequence of approximations.


How can I overwrite existing map instead of adding a new one below (OpenLayers)?

Question: I am trying to build a web map with a number of layers that can be toggled on and off. Initially the map gets drawn without any issues, but when I try to toggle off any layer, a new map is added below the existing one (instead of replacing it).
When I toggle off a layer, a javascript refresh() function is called. This function needs to rebuild the list of layers to draw and then call again the function that builds the map. I was hoping this would just replace the existing, but instead a new map gets added below.
...
...

<input type="checkbox" id="layer_1" value="layer_1" checked="checked" onClick="refresh()">Layer_1

<input type="checkbox" id="layer_2" value="layer_2" checked="checked" onClick="refresh()">Layer_2

<input type="checkbox" id="layer_3" value="layer_3" checked="checked" onClick="refresh()">Layer_3
    ...
    ...

...
...

Answer: To cleanly remove the old map you need to call map.setTarget(null) on the previous Map object.
But in your case it might be better to only create a single map and update the layers' visibility.
This way the map / view states like loaded tiles, center and zoom are remembered.

<input type="checkbox" id="input-osm" value="osm" checked="checked">OSM

<input type="checkbox" id="input-image" value="image" checked="checked">Image

Declare the map and layers variables outside the init function so it can be accessed from the refresh function.
var map, layers;

Store your layers in an object and assign to declared layers variable to be able to reference them by name and initialize them with correct visibility:
layers = {
    osm: ol.layer.Tile({
        source: new ol.source.OSM(),
        visible: document.getElementById('input-osm').checked,
    }),
    image: new ol.layer.Image({
        source: wmsSource
        visible: document.getElementById('input-image').checked,
    })
};

Assign map with all layers to previously declared variable:
map = new ol.Map({
    layers: Object.values(layers),
    ...

On user input layers' visibility should be changed according to the checkbox:
function refresh(checkbox) {
    layers[checkbox.value].setVisible(checkbox.checked);
}
document.getElementById('input-osm').addEventListener('change', refresh);
document.getElementById('input-image').addEventListener('change', refresh);

Best of luck.
Comment: Where should I add "map.setTarget(null)" within my code?
Comment: I am confused about your 2nd suggestion. wmsSource is a list a 9 layers in my case. Would it work anyway? And what's the HTML elements with id 'layer-image'?
Comment: I edited my answer, 'layer-image' should be 'input-image', the checkbox input.
Comment: The `map.setTarget(null)` should be called in the first line of your `init` function. But you need to declare the map variable outside that function so you can access the previously created map. And of course the first time it will be undefined, so add a check for when it is undefined.
Comment: I'm afraid I don't understand your code. I have tried it anyway and it doesn't work (it doesn't even draw the layers at the beginning). Thanks for your help anyway.
Comment: I managed to get it working with "map.setTarget(null)". It's true that your other suggestion would be more elegant (if I managed to get it working). Thanks again.
Answer: Firstly! Make some changes to the HTML. refresh(this)
...
<input type="checkbox" id="layer_1" value="layer_1" checked="checked" onClick="refresh(this)">Layer_1
...

javascript
var layersMap;
function onLOAD() {
  var my_layers = "layer_1,layer_2,layer_3";
  init(my_layers.split(","));
}

function init(layerNames) {
  //The bounding box of Lund:lund_address_point
  var extent = [13.1267, 55.677, 13.2601, 55.7597];
  //Initial view
  var view = new ol.View({
    center: ol.proj.transform([13.192927, 55.708944], "EPSG:4326", "EPSG:3857"),
    zoom: 13,
  });
  //Bind the map object to our "map" div and add some extra functionality
  var map = new ol.Map({
    layers: [
      new ol.layer.Tile({
        source: new ol.source.OSM(),
      }),
    ],
    controls: ol.control
      .defaults({
        attributionOptions: /** @type {olx.control.AttributionOptions} */ ({
          collapsible: false,
        }),
      })
      .extend([
        //Extra functionality of the map
        //Control for displaying coordinates
        new ol.control.MousePosition({
          coordinateFormat: ol.coordinate.createStringXY(4),
          projection: "EPSG:4326",
          className: "custom-mouse-position",
          target: document.getElementById("location"),
          undefinedHTML: " ",
        }),
        //Control for displaying a scale line
        new ol.control.ScaleLine({
          target: document.getElementById("scale-line"),
        }),
        //Control for zooming to a defined extent
        new ol.control.ZoomToExtent({
          extent: ol.proj.transform(extent, "EPSG:4326", "EPSG:3857"),
        }),
      ]),
    target: "map",
    view: view,
  });

  layerNames.forEach((layerName) => {
    layersMap[layerName] = generateImageWms(layerName);
    map.addLayer(layersMap[layerName]);
  });
}

function generateImageWms(layerName) {
  return new ol.source.ImageWMS({
    url: "http://localhost:8080/geoserver/Test/wms",
    params: {
      LAYERS: layerName,
    },
    serverType: "geoserver",
  });
}

function refresh(target) {
  layersMap[target.id] && layersMap[target.id].setVisible(target.checked);
}

Comment: I'm afraid this doesn't work. Only the OMS layer appears in the map. So I guess the bit "layerNames.forEach((layerName) => ......." is not doing its job?
Comment: Did you try? Layer is first created and then added to the map by `map.addLayer(layersMap[layerName])`


Set selected option based on URL hash with Javascript

Question: <select id="mySelect">
    <option>Apple</option>
    <option>Orange</option>
    <option>Pineapple</option>
    <option>Banana</option>
</select>

<button onclick="myFunction()">Try it</button>

This script selects "Pineapple" when the button is clicked. I want to do this exact same thing, except it should be selected immediately on refresh. ALSO, rather than using the selectedIndex, I would like to set the selected option based on the URL hash.
So: myname.com/#this
if location.hash == 'this' then set the option with an equal value as selected.
If it's checking for the location.hash, then I shouldn't need to use onload because it will pull the information from the url automatically. I know this is simple, I just don't know JavaScript well enough to get it put together myself.
Answer: You'd generally just listen to the hashchange event
window.addEventListener('hashchange', fn, false);

window.onload = fn; // fire on pageload

function fn() {
    document.getElementById('mySelect').value = window.location.hash.replace('#','');
}

Comment: I tried this like so:

Apple
Orange

It works, except when I reload the page, the option resets back to Apple.
Comment: See the updated code, or place the script tag after the elements in the DOM


How to set double level depth or where clause

Question: My query is currently like this:
    $erwachsene = $search_data['erwachsene'];
            $kinder = $search_data['kinder'];
            $rooms = Room::select('rooms.*')
            ->where('hotel_id', '=', $id)
            ->where('room_status', '=', 1)
            ->where(function($query) use ($erwachsene, $kinder) {
                $query->where("occupancy_adults1", ">=", $erwachsene);
                $query->where("occupancy_childs1", ">=", $kinder);
            })
            ->orWhere(function($query) use ($erwachsene, $kinder) {
                $query->where("occupancy_adults2", ">=", $erwachsene);
                $query->where("occupancy_childs2", ">=", $kinder);
            })
            ->get();

This return query like this:
    SELECT `rooms`.*
    FROM   `rooms`
    WHERE  `hotel_id` = ?
    AND `room_status` = ?
    AND ( `occupancy_adults1` >= ?
    AND `occupancy_childs1` >= ? )
    OR ( `occupancy_adults2` >= ?
    AND `occupancy_childs2` >= ? )

I need to put the last AND and OR clauses under OR group:
SELECT `rooms`.*
    FROM   `rooms`
    WHERE  `hotel_id` = ?
    AND `room_status` = ?
    AND
    (
          ( `occupancy_adults1` >= ? AND `occupancy_childs1` >= ? )
       OR ( `occupancy_adults2` >= ? AND `occupancy_childs2` >= ? )
    )

E.g. one more level parentheses. Is it possible with the Eloquent functions ?
Answer: You must cascade your where calls to get the expected SQL:
// ...
->where(function($query) use ($erwachsene, $kinder) {           // (
    $query->where(function($query) use ($erwachsene, $kinder) { //  (
        $query->where("occupancy_adults1", ">=", $erwachsene);  //    `occupancy_adults1` >= ?
        $query->where("occupancy_childs1", ">=", $kinder);      //   AND `occupancy_childs1` >= ?
    })->orWhere(function($query) use ($erwachsene, $kinder) {   //  ) OR (
        $query->where("occupancy_adults2", ">=", $erwachsene);  //   `occupancy_adults2` >= ?
        $query->where("occupancy_childs2", ">=", $kinder);      //   AND  `occupancy_childs2` >= ?
    });                                                         //  )
});                                                             // )

The first where level will create the outter parenthesis, the second where level will create the OR, and the third will create the inner AND.


Sensor simulator's NetworkOnMainThreadException

Question: I followed this instruction to debug my app on emulator using sensor simulator:
http://code.google.com/p/openintents/wiki/SensorSimulator#How_to_use_the_in_your_application
I completed all steps above, but in my case everything was not as simple as described in instructions. I got NetworkOnMainThreadException trying to connect, register listener etc. So I created async task to solve this problem. Now, I have the following:
connection to simulator:
<code>@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    ...
    sensorManager = SensorManagerSimulator.getSystemService(this, SENSOR_SERVICE);
        this.new ConnectToSimulator().execute();
    }
</code>
onResume() listner's registration:
<code>@Override
public void onResume() {
    super.onResume();
    this.new RegisterToSimulator().execute();
}
</code>
finally my tasks:
<code>class ConnectToSimulator extends AsyncTask<Object, Object, Object> {
    @Override
    protected Object doInBackground(Object... arg0) {
        try{
        sensorManager.connectSimulator();
        }catch(Exception e)
        {
            Log.i("error", e.getMessage());
        }
        return null;
    }
}

class RegisterToSimulator extends AsyncTask<Object, Object, Object> {
    @Override
    protected Object doInBackground(Object... arg0) {
        try{
            sensorManager.registerListener(Compass.this, sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), SensorManager.SENSOR_DELAY_FASTEST);
            sensorManager.registerListener(Compass.this, sensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD), SensorManager.SENSOR_DELAY_FASTEST);
            sensorManager.registerListener(Compass.this, sensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION), SensorManager.SENSOR_DELAY_FASTEST);
        }catch(Exception e)
        {
            Log.i("error", e.getMessage());
        }
        return null;
    }

}
</code>
but even after that, I still receive the error trying to launch app on emulator:

12-15 14:23:28.877: E/AndroidRuntime(3724): FATAL EXCEPTION: main
  12-15 14:23:28.877: E/AndroidRuntime(3724): android.os.NetworkOnMainThreadException
  12-15 14:23:28.877: E/AndroidRuntime(3724):     at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1117)
  12-15 14:23:28.877: E/AndroidRuntime(3724):     at libcore.io.BlockGuardOs.recvfrom(BlockGuardOs.java:163)
  12-15 14:23:28.877: E/AndroidRuntime(3724):     at libcore.io.IoBridge.recvfrom(IoBridge.java:513)
  12-15 14:23:28.877: E/AndroidRuntime(3724):     at java.net.PlainSocketImpl.read(PlainSocketImpl.java:488)
  12-15 14:23:28.877: E/AndroidRuntime(3724):     at java.net.PlainSocketImpl.access$000(PlainSocketImpl.java:46)
  12-15 14:23:28.877: E/AndroidRuntime(3724):     at java.net.PlainSocketImpl$PlainSocketInputStream.read(PlainSocketImpl.java:240)
  12-15 14:23:28.877: E/AndroidRuntime(3724):     at java.io.InputStreamReader.read(InputStreamReader.java:244)
  12-15 14:23:28.877: E/AndroidRuntime(3724):     at java.io.BufferedReader.fillBuf(BufferedReader.java:130)
  12-15 14:23:28.877: E/AndroidRuntime(3724):     at java.io.BufferedReader.readLine(BufferedReader.java:354)
  12-15 14:23:28.877: E/AndroidRuntime(3724):     at org.openintents.sensorsimulator.hardware.SensorSimulatorClient.readSensor(SensorSimulatorClient.java:654)
  12-15 14:23:28.877: E/AndroidRuntime(3724):     at org.openintents.sensorsimulator.hardware.SensorSimulatorClient.readSensor(SensorSimulatorClient.java:571)
  12-15 14:23:28.877: E/AndroidRuntime(3724):     at org.openintents.sensorsimulator.hardware.SensorSimulatorClient.access$1000(SensorSimulatorClient.java:53)
  12-15 14:23:28.877: E/AndroidRuntime(3724):     at org.openintents.sensorsimulator.hardware.SensorSimulatorClient$1.handleMessage(SensorSimulatorClient.java:505)
  12-15 14:23:28.877: E/AndroidRuntime(3724):     at android.os.Handler.dispatchMessage(Handler.java:99)
  12-15 14:23:28.877: E/AndroidRuntime(3724):     at android.os.Looper.loop(Looper.java:137)
  12-15 14:23:28.877: E/AndroidRuntime(3724):     at android.app.ActivityThread.main(ActivityThread.java:5039)
  12-15 14:23:28.877: E/AndroidRuntime(3724):     at java.lang.reflect.Method.invokeNative(Native Method)
  12-15 14:23:28.877: E/AndroidRuntime(3724):     at java.lang.reflect.Method.invoke(Method.java:511)
  12-15 14:23:28.877: E/AndroidRuntime(3724):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
  12-15 14:23:28.877: E/AndroidRuntime(3724):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
  12-15 14:23:28.877: E/AndroidRuntime(3724):     at dalvik.system.NativeStart.main(Native Method)

Can someone clarify why I have so strange error? moreover there is no info in simulator instruction about async task usage necessity, maybe I am doing something wrong. Please help, thanks in advance.
Comment: I'm having the same problem but don't feel like creating an async task and even lowering the target api is worth the effort. I will just use real devices for testing instead of the emulator... too bad the simulator project doesn't seem to be active anymore :(
Answer: Unfortunately this error cannot be bypassed because library is not implemented having
"new" SDK limits.
Simplest solution is to set minSdkVersion in manifest to something before Honeycomb
(e.g. android:minSdkVersion="8").
Reson for this is, although you did connected on background thread, you still created
object on your UI thread, which in return means SensorSimulatorClient will use socket
communication on your UI thread.


How to remove text between numbers in notepad++

Question: I have texts like
3.6. Sam
3.7. Willy

4.1. drake
4.2. nadeem

I need output like
3-6 Sam
3-7 Willy

4-1 drake
4-2 nadeem

I tried replace \d{1}.\d{1}. with \d{1}-\d{1} & later with $1-$2
But I cant retain the number. Can anyone help me with this
Comment: Please check out [column editing](https://www.technipages.com/notepad-column-mode)
Answer: Use the following Regex:
(\d)\.(\d)\.

And replace with:
$1-$2

You were going wrong because you need capture groups around the numbers. (\d) instead of just \d.
And you don't need to specify {1} if it's just one, you can leave that out. Also you put . but that represents any character, not just the period/fullstop, for that you have to escape it with a slash as \..
Answer:
Ctrl+H
Find what: ^(\d+)\.(\d+)\.
Replace with: $1-$2
CHECK Wrap around
CHECK Regular expression
UNCHECK . matches newline
Replace all

Explanation:
^       # beginning of line
  (\d+) # group 1, 1 or more digits
  \.    # a dot
  (\d+) # group 2, 1 or more digits
  \.    # a dot

Screen capture (before):

Screen capture (after):
Answer: Another option is to make use of \K and use a single group in the replacement.
Find what:
\d\K\.(\d)\.

Replace with:
-$1

Explanation

\d Match a single digit (use \d+ to match 1 or more digits)
\K  Reset starting point of the reported match (forget what was matched)
\.(\d)\. Capture a digit in group 1 between matching a dot on the left and right

Regex demo
If all your matches are at the start of the string, you prepend a ^ to the pattern.
Answer: A shortest forum of regex will look like this...
Find what: \.(\d)\.
Replace with: -$1  or  ↝ -\1
Comment: I always worry about using a very short and simple regex, I worry that it will change things in other parts of the file. This answer works for the text given, but suppose the file is huge and one of the lines is `4.1. duke has IP address 22.214.171.124.` then that line would be changed to `4-1 duke has IP address 128-12-3`.
Comment: May be he wanted to change ip addresses too, it depends on the question.... Good point ✔♥♥♥♥


Is Invariance Of Domain (Fundamentally) Equivalent To Every Continuous Bijection $\mathbf{R}^n\to\mathbf{R}^n$ Is Open?

Question: I found this comment

I would also like to point out that invariance of domain and the statement that every continuous bijection from $\mathbf{R}^n$ to $\mathbf{R}^n$ is a homeomorphism are equivalent. Therefore I would not expect there to be a proof that avoids this machinery.

but couldn't prove it myself using fundamental methods, i.e. no algebraic topology.  As far as I can tell, invariance of domain is equivalent to the statement restricted to open balls in $\mathbf{R}^n$.  But from there, I don't see how to prove this using only the statement about continuous bijections and no algebraic topology.  Clearly, the preimage of an open ball is open, but how can I conclude that it's homeomorphic to an open ball?
Comment: Invariance of domain is really the statement that every continuous *injection* $\mathbb{R}^n\to\mathbb{R}^n$ is open.  I don't see any easy way to deduce this from the corresponding statement only about bijections.  I would not take the comment you quoted too seriously.
Comment: Yes, but which direction of the equivalence did you show?  For me it's clear that invariance of domain implies the other thing, but curious, how do I get invariance of domain only from knowing that every continuous bijection $\mathbf{R}^n\to\mathbf{R}^n$ is a homeomorphism?  Here my idea was, given $f:U\to V$ a continuous bijection with $U$ open, to find some family of open balls $\{B_i\}_i$ such that $V=\cup_i B_i$ and $f(B_i)$ is homeomorphic to an open ball so that I can use the preimise...
Comment: Oh. Sorry I was talking about the same. The other one I am not sure. Didn't realise at first that it might be harder. There is already an answer. Let's hope it's correct and helps.
Comment: There are analytical proofs of IDT which avoid AT. For instance, Terry Tao wrote one. But his proof does not use the property that every continuous bijection is a homeomorphism. MSE is full of erroneous claims, I would not take the linked comment seriously.
Answer: Let's call a topological space $X$ domain invariant, if it fullfills the usual condition of the theorem of domain invariance, i.e. if $U, V$ are homeomorphis subsets of $X$, and $U$ is open, then also $V$ is open.
$X$ fullfills (*), if every continuous bijection $f: X \rightarrow X$ is a homeomorphism (sorry, no better notation came up to my mind).
By a standard argument we have:
If X is doamin invariant, T2 and locally compact, then $X$ fullfills (*).
Proof. Let $f: X \rightarrow X$ be a continuous bijection. Of course, it suffices to show that $f$ is open: Let $U$ be open in $X$, $x \in U$. By local compactness pick an open $V$ such that $x \in V \subset \overline{V} \subset U$ and $\overline{V}$ compact. Then $f|\overline{V}: \overline{V} \rightarrow f(\overline{V})$ is continuous, bijective, hence a homeomorphism. Thus, $f|V: V \rightarrow f(V)$ is a homeomorhism, and $ V \cong f(V)$. Since $X$ is domain invariant, $f(V)$ is open. Therefore $f(U)$ is open.
This might be interpreted as "$\Rightarrow$" of the above statement (if $X$ is T2, locally compact).
However, "$\Leftarrow$" is not true in general:
Of course, if $X$ is compact, T2 then $X$ fullfills (*), but need not be domain invariant, as the unit interval shows.
Comment: Well, now I understand what your essential question was. Since my answer does not really answer that, you should probably remove its acceptance in order to get a better answer.
Comment: Thanks a lot for the answer!  So, also for $\mathbf{R}^n$ specifically, there is no fundamental way to show the equivalence?  If so, is the statement from which I took the comment still true, that there is no fundamental (without algebraic topology) proof of (\*)?
Comment: @fweth: I merely answered your question of the title. In order to answer your other question, one could perhaps think of other conditions, which are (easy) to proof for $\mathbb{R}^n$ and provide domain invariance together with (*). I thought about homogenity, but $[0,1]^\omega$ is homogeneous, compact, but not domain invariant. No, sorry, I don't have a concrete proposal.
Comment: No worries!  I also think that even (\*) is hard for $\mathbf{R}^n$.  Someone on IRC said its easy, but didn't provide a proof, so I thought I'd ask here again.  (Tbf, another person on IRC also said there is no easy proof.)


Difference between HTML block elements and CSS display block property

Question: May I know if there is any difference between HTML block elements (Eg.
,
,...) and CSS property display: block?
Since from what I have read they are the same, but why we still need to use display: block for some block level element.
Comment: It's the same. Block elements are block because they have `display: block` as default styles. Nothing more. We can say that `span` with `display: block` is the same as `div` (both with zero semantic value).
Comment: You are starting from a false assertion. We do **not** need to use `display:block` on block level elements **unless** the property is being **reverted** to that state after being changed previously.
Comment: https://developer.mozilla.org/en/docs/Web/HTML/Block-level_elements
Comment: http://dustwell.com/div-span-inline-block.html
Answer: What you call "HTML block elements" are elements who have their display property set to block so there is no difference between a
 and a  with display:block;.
This display property is set by the user agent stylesheet (i.e your browser). You can view these properties in chrome dev tool under "user agent stylesheet".
The only reason I see of using display:block; for a div element is :

your target adience is using some obscur user agent that don't follow web stadards (very unlikely)
you need to override a previous CSS declaration like display:none;
Answer: There is no difference between... because block elements already have default css property display: block.
But we use display: block to show them again, when we hide/remove them from page using display: none.


What would be an algorithm to shut down all lamps?

Question: I found an algorithm problem that I was unable to solve from http://www.ohjelmointiputka.net/postit/tehtava.php?tunnus=muslam. I guess as it requires linear algebra, this might a correct place to ask an algorithm.
We have $n$ lamp to form a circular loop with $n$ on/off switches. At the beginning, some lamps are on, denoted by the bit 1 and some are off, denoted by the bit 0. We have been given an integer $m$. Pressing each switch changes the state of the lamp that correspond the switch and its $m$ nearest lamps in each direction. Find out how many switches one has to press to shut down all the lamps and give a list of the pressed switches.
I tried to think that I need to solve a matrix equation over $\mathbb Z/2\mathbb Z$ but found out that the coefficient matrix I made has no inverse. I thought that I need a coefficient matrix such that $A_{i,j}=1$ if pressing switch $i$ changes the lamp state $j$ and $A_{i,j}=0$ if it does not change.
Here is my code for the case there are six lamps with initial states 101101 and every switch affects to the given lamp and one of its nearest lamps in both directions.
# Generate the zero matrix
def generate_matrix(w, h):
    return [[0 for x in range(w)] for y in range(h)]

# Print matrix
def print_matrix(A):
    for row in range(0,len(A[0])):
        line = ""
        for col in range(0,len(A[0])):
            line += str(A[row][col])
            if col == len(A[0]):
                line += "\n"
        print(line)

# Swap two rows
def swap_rows(A,i,j):
    for k in range(0,len(A[0])):
        temp = A[k][i]
        A[k][i] = A[k][j]
        A[k][j] = temp
    return A

# Add one row to another
def mult_rows(A,i,j):
    for k in range(0,len(A[0])):
        A[k][j] += A[k][i]
    return A

# Distance between two indices
def dist(i,j,n):
    d1 = max(i-j,j-i)
    dist_beg = min(i,j)
    dist_end = n-max(i,j)
    d2 = dist_beg + dist_end
    return min(d1,d2)

# Initialize the coefficient matrix
def gen_coeff_matrix(n,effect_width):
    A = generate_matrix(n,n)
    for i in range(0,n):
        for j in range(0,n):
            if dist(i,j,n) <= effect_width:
                A[i][j] = 1
    return A

# Initialize the unit matrix
def init_unit_matrix(n):
    A = generate_matrix(n,n)
    for i in range(0,n):
        A[i][i] = 1
    return A

# Inverse of the matrix
def inv(M):
    n = len(M[0])
    U = init_unit_matrix(n)
    for column in range(0,n):
        if M[column][column] == 0:
            i = 1
            while M[column+i][column+i] != 0:
                ++i
            swap_rows(A,column,column+i)
            swap_rows(U,column,column+i)
        for c in range(0,n):
            if M[c][column] == 1:
                if c != column:
                    mult_rows(M,c,column)
                    mult_rows(U,c,column)
    return U

A = init_unit_matrix(5)
B = gen_coeff_matrix(6,1)
print_matrix(B)

It gives the matrix
110001
111000
011100
001110
000111
100011

but it is not invertible according to Sage:
sage: F = FiniteField(2)
sage: C = Matrix(F,[[1,1,0,0,0,1],[1,1,1,0,0,0],[0,1,1,1,0,0],[0,0,1,1,1,0],[0,0,0,1,1,1],[1,0,0,0,1,1]])
sage: C
[1 1 0 0 0 1]
[1 1 1 0 0 0]
[0 1 1 1 0 0]
[0 0 1 1 1 0]
[0 0 0 1 1 1]
[1 0 0 0 1 1]
sage: C^(-1)
---------------------------------------------------------------------------
ZeroDivisionError                         Traceback (most recent call last)
<ipython-input-4-48e78ab0a5de> in <module>()
----> 1 C**(-Integer(1))

sage/matrix/matrix0.pyx in sage.matrix.matrix0.Matrix.__pow__ (/usr/lib/sagemath//src/build/cythonized/sage/matrix/matrix0.c:36015)()

sage/structure/element.pyx in sage.structure.element.generic_power_c (/usr/lib/sagemath//src/build/cythonized/sage/structure/element.c:29266)()

sage/matrix/matrix_mod2_dense.pyx in sage.matrix.matrix_mod2_dense.Matrix_mod2_dense.__invert__ (/usr/lib/sagemath//src/build/cythonized/sage/matrix/matrix_mod2_dense.c:7868)()

ZeroDivisionError: Matrix does not have full rank.

I also tried with the following command:
sage: V=Matrix(F,[[1,0,1,1,0,1]])
sage: C\V

ValueError: number of rows of self must equal number of rows of B

Questions: Is this the right way to think about the problem? Is there a mistake in the reasoning how to make the coefficient matrix? Is the just a silly bug in my code?
Comment: Always, when I hear of Problems like this, I think of Ideals with $x_i - x_{i-1}*x_{x+1}$ as generators.
Answer: You are thinking about it in exactly the right way.  Multiplying your matrix by a vector will show what lights are on if you start with the lights all off and flip the switches represented by $1$s in the vector.  Then if you invert the matrix and multiply it by the starting state you will find out how to go from your starting state to all off.  The fact that your matrix is not invertible says there are states that you cannot get to the starting state from.  You can see the matrix is not invertible because the first and fourth lines sum to $[1\ 1\ 1\ 1\ 1\ 1]$ as do the second and fifth and the third and sixth.  You can still do Gaussian elimination to see of your initial state can reach all off.  The problem comes because the number of lights affected is not coprime with the number of lights.  Try it with eight lights instead of six and I believe you will find a working solution.  In your case none of the switches changes the number of lights that are on $\bmod 3$.  As you are starting with four on, you can't get to all off.  The linear algebra is not necessary, but it is a good way to attack it.  An intermediate approach is to try to find by hand a way to turn off a single lamp.  Any given lamp can be turned off by rotating the set of switches you use for the first lamp.  If you have a number of lamps to switch, just collect the list of switches for each lamp, remove duplicates in pairs, and you are done.  You are finding a basis for the vector space here.
Comment: I found another opinion in https://www.quora.com/What-is-the-algorithm-for-solving-lights-out-puzzle-in-minimum-number-of-moves-in-Java : "As mentioned, although the solution is beautiful, it can not guarantee the optimality (minimum no. of non zero values in your solution for the equation)." I haven't found a proof that linear algebra method provides the solution with minimal number of switch presses


Hopf algebras and "unifying" representation theory

Question: We know that representations of a lie algebra $\mathfrak{g}$ can be studied by looking at the representations of the associative algebra $\mathcal{U}(\mathfrak{g})$, the universal enveloping algebra. Ditto for a finite group $G$ and its group algebra $\mathbb{C}[G]$, and for a locally compact group $G$ and $L^1(G)$.
I can't remember where, but I heard a while back that the theory of Hopf algebras is relevant here. Do Hopf algebras somehow help us study the representations of all the associative algebras above, or something? How are Hopf algebras relevant here?
I don't know anything about Hopf algebras except for their definition.
Answer: Universal enveloping algebras $U(\mathfrak{g})$ and group algebras $\mathbb{C}[G]$ are both naturally Hopf algebras. The relevance of the Hopf structure to representation theory is that it tells you how to construct the tensor product of two representations and the dual of a representation. In general, the category of modules over a ring is just an abelian category and has none of this extra structure.


I cant pass variables between loops using PHP and SQL?

Question: In the loops below, PHP doesn't seem to pass the outputted string back out to the loop that contains it for further manipulation, then making the output from this loop nothing at all.
Please help me understand why this is...
<?php

$finalTablePrint = '
                        LTU Activity Report

                          Date Created: ' . date("l jS \of F Y") . '

                            Activity	Department	Hours Spent	Month

';

while ($row = mysql_fetch_assoc($result)) {
    $finalTablePrint .= '
' . $row['activity'] . '
';
    while ($row_1 = mysql_fetch_assoc($result)) {
        if ($row_1['activity'] == $row['activity'] && $row_1['department'] == $row['department']) {
            $finalTablePrint .= '
' . $row['department'] . '	' . '' . $row['hours'] . '	' . $row['month'] . '
';
        }
    }
}

echo $finalTablePrint .='
';

Answer: Note that when you set off your second loop, you are calling the same SQL statement as the original one before it
  while ($row = mysql_fetch_assoc($result)) {   //1st while
while ($row_1 = mysql_fetch_assoc($result)) {    //2nd while

which in turn means that this if statement will allways be true....
 if ($row_1['activity'] == $row['activity'] && $row_1['department'] == $row['department']) {

and this will allways echo:
  $finalTablePrint .= '
'.$row['department'].'	'.''.$row['hours'].'	'.$row['month'].'
';

so you should really remove your 2nd while/if statement... since it achieves nothing at the moment
Comment: Thank you so much! Didn't even click to that issue?!
Comment: Wait doesnt the second loop, loops through all items in the list comparing them to the item from the outside loop?
Comment: no? how can it you are putting identical select statement and running it within itself, how does that achieve unique results to if statement?
Comment: i think i see what you mean, im going to try a different approach using array_unique... thank you for your help! :)
Answer: Because js script at the end navigates you away too quickly you have no chance to see what happened! Remove it until you fix things the way you like it, and make sure that js is doing exactly what you are asking for.


Javascript - Function VS No Function...how does this work?

Question: If I place the following script above the element that the script is searching for, I receive an error:

And of course, to get it working again I need to place it below the element.
Yet if I turn the same thing into a function and place it above the element that the script is searching for, it works perfectly:
function loadnew(){
    document.getElementById('my_iframe').src = "my_file.php";
}

The question is, why does it work if I use a function? I always thought that in order for a script to find something it needed to be placed below the element it's searching for?
Thanks!
Comment: All in all some **very** helpful answers from everyone! Thanks!
Answer: Where it's placed does not matter, the only thing that matters is when it is executed.
If it's executed before there is a element with the id my_iframe it will fail, if there is one it will succeed.
So if you just do a inline script tag and then place your one liner in there it will be executed immediately and if the script tag happens to be before the tag with the id my_iframe nothing is found - getElementById returns null which isn't a normal object and therefore can't have a property src so your code fails.
If you define a function and execute it after a element with the id my_iframe exists it will return a element object and your code runs fine (of curse assuming that element object allows the src property to be set).
Comment: Very true, but some explanation would probably help ;)
Comment: Agreed, but only if the code is in a function.  If it's global, then it executes as soon as it's parsed.
Answer: You need to execute this code when the DOM is ready.
window.onload=function(){
  loadnew()
}

Answer: Javascript code is executed as encountered by the browser's parser1. Which means that if you query an element below your


What are the possible drops for defeating Yeti Zombie?

Question: A Yeti Zombie spawned in Ancient Egypt for me just now, and the game says I should try to defeat it in order to obtain fabulous treasure. I killed it in the game and got a lunch box, containing just one normal key (useful for unlocking). I don't think the prize is THAT awesome. Is that all?
What are the other possibilities for Yeti Zombie drops?
Comment: related: http://gaming.stackexchange.com/questions/128263/what-causes-a-treasure-yeti-to-run-away
Answer: Killing Yetis can drop multiple lunchboxes.
Each lunchbox can contain either keys or diamonds.
http://plantsvszombies.wikia.com/wiki/Treasure_Yeti
Comment: @user1032613 Yeti in Egypt dropping Diamonds.... It sure **sounds** exciting :)
Comment: @spartacus Yes, the trivia section of my link has *In the "You got a Present!" Notification, there is a button called "open all". This is because you can get more than 1 lunch box when you kill a Treasure Yeti.* there is also a image that shows a 2 lb drop.
Comment: I see. It's only diamonds or keys, not that exciting.
Comment: you said multiple lunchboxes, so its possible to get more than 1 per yeti?
Answer: The lunchboxes always contain 1000 coins.
Since gate keys are no longer in the game, and diamonds have been repurposed as a premium currency, this is currently the only thing you get from Yetis.


Pin Apps to Desktop layout

Question: Noobie, Using Ubuntu v. 15.04---Three part question:

I am trying to pin an app or program to the desktop workspace, rather than clogging the "launcher" sidebar. In fact, the Launcher sidebar is so loaded with apps I have to stream down through all the cramped apps located there just to check the one I'd like. Every app I like goes automatically to the sidebar one installed. I have "created new (empty) folders" on the desktop (for Finance/Documents/Business/Legal etc.), and even pinned Firefox (via right-click context menu). I just would like to  access files or apps in a desktop folder vs. from a string of apps along the sidebar...
In fact, can I drag and drop apps from the Launcher sidebar directly ONTO the desktop?? (I tried = no joy)...I like a drag and drop function...
Can I place the Launcher along the bottom of the desktop versus left sidebar?

Thanks...
Answer:
Drag your apps from Dash Menu instead of dragging them from launcher.
Once you have pinned them to the desktop, usually they will be able to launch. Otherwise wou will have to give them special permission for that.

Open the terminal: Ctrl+Alt+T
Run the command:
sudo chmod +x ~/Desktop/*.desktop

Next run the command below:
sudo chown (your user name) ~/Desktop/*.desktop

Read here for info: How to make shortcuts for apps

No, you can't move the launcher to the bottom. Instead you can use Cairo-Dock or Docky software to imitate the launcher.

See answers here: How to change unity side laucher position from left to right ubuntu 14.04 and here: Can I move the Unity launcher?
Comment: where exactly is "Dash Menu?" ("Search Computer?" Ubuntu Software Center?)...will try Terminal (so unnecessary in a DOS-like command setup---should be PNP or GUI)...will review your links as well  Thx
Comment: found Dash (search computer, first upper left icon), tried to drag an app, no joy, flipped right back into dash menu...will try "permissions" next.
Comment: It should drag and drap without any problems even if you don't specify permissions.
Answer:
There's a folder /usr/share/applications where all the shortcuts are stored - copy whichever you want to respective directories on your desktop;
No
That will require a dock app, such as plank (my favorite) or cairo-dock
Comment: Thanks Serg...I tried Cairo-dock, but it disappeared on reboot. What I think I will also do is search the usr/share file,  see what's there, then delete many of the apps in the Launcher bar. As you can probably guess, I am from Windows 7 (hate Windows privacy) but it's a little hard & frustrating adapting to the directory trees and names in Linux.
Comment: @Doc Um . . .it's probably one of those apps that needs to be added to autostart entries; don't remember exactly if that's so:  I've tried it long ago in 13.04 and didn't like it, so haven't continued using it.
Comment: Serg, located file folder, tried drag/drop, failed, says I need permission. I will also try Plank app. Thx
Comment: Yeah, that folder is owned by root user. Um....are you ok with using terminal for just a little bit ?
Comment: Also, try copying, not drag and drop.

Pin Apps to Desktop layout


get all possible strings given multiple strings

Question: I have multiple strings on different lines where I want to get all of the possible permutations without changing the order:
for example:
er r er
er er r

which would give me:
er r er
er er r
er r r
er er er

Is there a way to do this is python?  If this is a duplicate please advise but I was not able to find one.
This is different from questions like Finding all possible permutations of a given string in python where only one string is used
Update [Still does not work]
import itertools

with open(in_file) as f:
    lis = list(f)

print (lis)
print([' '.join(x) for x in itertools.product(*map(set, zip(*map(str.split, lis))))])

[Error]
[['er', 'r', 'er'], ['er', 'er', 'r']]
Traceback (most recent call last):
File "test.py", line 37, in <module>
print([' '.join(x) for x in itertools.product(*map(set, zip(*map(str.split, S))))])
TypeError: descriptor 'split' requires a 'str' object but received a 'list'

Comment: Possible duplicate of [Finding all possible permutations of a given string in python](https://stackoverflow.com/questions/8306654/finding-all-possible-permutations-of-a-given-string-in-python)
Comment: @Kallz but this one only has one string, this I can do... the problem is getting combinations between multiple strings.
Comment: Can you show the data in `in_file`? Note: You are `split()`ing twice, `lis = list(f)` would be sufficient. You could of course just put `f` into the `map()` directly (and move the `print` into the `with` clause). Or you can get rid of the `map()` and just `zip(*lis)`
Comment: @AChampion the in_file is exactly the same as my example
Comment: Then why are you splitting twice?
Comment: @AChamion I can fix that
Comment: @AChampion the output is still the same even without the extra split
Comment: Your error must be incorrect `lis` should be `['er r er', 'er er r']` not the split version you are showing.
Answer: You can zip the splits of these strings and take the cartesion product, e.g.:
>>> import itertools as it
>>> s1, s2 = 'er r er', 'er er r'
>>> {' '.join(x) for x in it.product(*zip(s1.split(), s2.split()))}
{'er er er', 'er er r', 'er r er', 'er r r'}

You can get duplicates so, constructed as a set comprehension.
Updated for an arbitrary number of strings:
>>> import itertools as it
>>> ss = ['er r er', 'er er r', 'ar er r']
>>> {' '.join(x) for x in it.product(*zip(*map(str.split, ss)))}
{'ar er er', 'ar er r', 'ar r er', 'ar r r', 'er er er', 'er er r', 'er r er', 'er r r'}

Note: You could also apply the set to the arguments to product to remove duplicates and it might be quicker depending on the overlaps of the strings, e.g.:
>>> [' '.join(x) for x in it.product(*map(set, zip(*map(str.split, ss))))]
['er r r', 'er r er', 'er er r', 'er er er', 'ar r r', 'ar r er', 'ar er r', 'ar er er']

To read from a file type object:
>>> with open(in_file) as f:
...     lis = list(f)
>>> print([' '.join(x) for x in it.product(*map(set, zip(*map(str.split, lis))))])
['er r r', 'er r er', 'er er r', 'er er er']

Or more compactly:
>>> with open(in_file) as f:
...     print([' '.join(x) for x in it.product(*map(set, zip(*map(str.split, f))))])
['er r r', 'er r er', 'er er r', 'er er er']

Comment: Please do, as it would require an extraordinary feat of inference to work that out from your question. Note: This is quite easy to update for an arbitrary number of strings.
Comment: I would like an example that isn't fixed for two strings as I could have more.  I will update my question.
Comment: I am getting  at , zip is a tuple right?
Comment: `zip()` is a builtin function that takes multiple lists and returns an `iterator` (or `list` py2) of `tuple`s of all the first elements, all the second elements, etc.
Comment: I was thinking something like this: print (' '.join(x for x, _ in itertools.product(S))) I appended my strings to a list hoping that wold help
Comment: and with print({' '.join(x) for x in itertools.product(*zip(*map(str.split, S)))}) I got set(['r', 'er'])
Comment: I would update your question with what you have tried. Showing how `S` is defined, and describe your expected results.
Comment: ok I have put the code and current error up, I got rid of the extra things I was doing.
Comment: See my comment, not sure why you are `split()`ing twice.
Comment: yes, I was trying to make it more obvious but it was unnecessary and I agree with that and produces the same result.  Your updated solution is perfect.  I would also like to than k you for your patience and help on this.  The magic in this solution is the change in format from several strings separated by '\n' to a list of strings (not what I imagined but a working solution) and the use of product from itertools. Thanks again!


Why my right edge of the Box in Compose is vibrating while expanding and collapsing?

Question: Animation is not at all smooth enough, it is just like lagging
Here I am using a simple box, I am expanding its width using animateFloatAsState. Without any animation of its inside element, it is not at all smooth enough. Where I am doing wrong?
Code:
<code>import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.animation.core.*
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color

class TestClassTwo : ComponentActivity() {

    private var isExpandedSavingCard by mutableStateOf(true)

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        setContent {

            val savingCardWeight = remember {
                mutableStateOf(0.50f)
            }
            val animation = animateFloatAsState(
                targetValue = savingCardWeight.value,
                animationSpec = tween(
                    durationMillis = 400,
                    easing = LinearEasing
                )
            )

            Box(modifier = Modifier
                .fillMaxWidth(animation.value)
                .fillMaxHeight(0.5f)
                .clickable {
                    isExpandedSavingCard = !isExpandedSavingCard
                    savingCardWeight.value = if (isExpandedSavingCard) 0.50f else 1f
                }
                .background(color = Color.Blue))
            {

            }

        }
    }
}
</code>
Answer: This is the problem in jetpack compose till now but you can reduce lagging effect by changing two line of code
from
durationMillis = 400,
easing = LinearEasing
To
durationMillis = 2000,
easing = LinearOutSlowInEasing
Note -> durationMillis = 2000 just for increase time of animation you can use any time above 1000 ms


OpenGL apps (Games) disappear after leaving fullscreen

Question: I've been trying to play some linux supported games on ubuntu 12.04 using steam (mostly Dota 2) and I've been having the same problem every time with every game.
As soon as I alt-tab out of fullscreen mode the game just vanishes.
Its still running in the background, it still shows up on the system monitor but I have no way of accessing the game again.
It doesn't show on the task bar, doesn't show on Alt-Tabs... just weird.
Granted, I am a complete linux noob (as in I google absolutely everything I do) so I might be missing something incredibly obvious here... o.O
Comment: I frequently accidentally open the dash while toggling autocast, and I found that sometimes, when you don't see Dota 2, clicking the Steam icon in the sidebar a few times will usually make it reappear.
Comment: As John said, with Steam the game minimizes to the Steam Icon, if you look closely you will see 2 arrows showing that the Steam client ans Dota are both open, clicking on the icon will spread the apps back out and then you can click on Dota's screen to get it back to the front.  other than steam games, I don't know of any others that do this, native games (tuxcart for ex) will have it's own icon that you can click on the get it back
Answer: Go to the steam and reclick the steam icon again this should make you select things that runs on steam well atleast it is for me


How to have a script check for admin privileges', and rerun itself as admin if it doesn't

Question: So I am trying to create a solution for an issue I am having in powershell.
I need to come up with a way to have my script check if it was ran with Administrative Rights. If it wasn't it needs to rerun itself with admin rights.
My situation is special from the other times this has been asked (From all the posts I have checked) as our normal user accounts doesn't have the rights, so I need to enter alternative credentials.
If this helps, Our Administrative Accounts do have an ending identifier in the name if we can filter off this. EX. "John.Doe.A" and the .A indicates this is an Admin account.
Comment: There are lots of examples of auto-elevation scripts all over the web. SO rules:  [Provide MRE](https://stackoverflow.com/help/minimal-reproducible-example) --- [How to ask](https://stackoverflow.com/help/how-to-ask) --- [Don't ask](https://stackoverflow.com/help/dont-ask) --- [Proper Topic](https://stackoverflow.com/help/on-topic) --- [Why not upload images of code/errors?](https://meta.stackoverflow.com/questions/285551/why-not-upload-images-of-code-errors-when-asking-a-question) --- [format your post properly](https://stackoverflow.com/help/formatting). Show what you tried?
Answer: Continuing from my comment.
Your case is not unique. It gets asked a lot here and in many other spots.
'powershell SecretManagement module' auto elevate

Sample hit:
https://petri.com/powershell-secrets-management-how-to-securely-elevate-privileges-in-powershell-scripts

You store needed credentials in the 'Windows Credential Manager', and call from the as needed. MS even provides a new Secrets Module for this kind of use case. See more details via MS Docs on the topic.
Like this:

SecretManagement and SecretStore are Generally Available
https://devblogs.microsoft.com/powershell/secretmanagement-and-secretstore-are-generally-available

and this:

Microsoft.PowerShell.SecretManagement
https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.secretmanagement/?view=ps-modules

<code>Get-Secret
Get-SecretInfo
Get-SecretVault
Register-SecretVault
Remove-Secret
Set-Secret
Set-SecretInfo
Set-SecretVaultDefault
Test-SecretVault
Unregister-SecretVault
</code>
Comment: led me down the right path, it led me to doublecheck into Powershell credentials manager, I didn't look into it before now because it didn't work in a separate use case and ended up leading me to this page "https://blog.expta.com/2017/03/how-to-self-elevate-powershell-script.html"

After some slight modification of how it checks for admin rights (I just did a match for our admin identifier instead of checking if I had the admin group) it worked right out of the gate!
Answer: Use this.
<code>$adminrole = ([Security.Principal.WindowsBuiltInRole] "Administrator")
$wid = ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent())
If (-not $wid.IsInRole($adminrole)) {
    $newProcess = new-object System.Diagnostics.ProcessStartInfo "PowerShell"
    $newProcess.Arguments = $myInvocation.MyCommand.Definition
    $newProcess.Verb = "runas";
    [System.Diagnostics.Process]::Start($newProcess);
    exit
}
</code>
Comment: As it's currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-ask).


AspectJ Injection in Vaadin working only after I Generate the SerialVersionID

Question: Hi I am using Spring 3 + Spring MVC (half of the site) + Vaadin + AspectJ + JPA2 + Spring Security
My problem is that Spring creates all my Repositories and I would like to share those with Vaadin using AspectJ injection with Spring Annotations, when vaadin is started (Admin part of the site)
I have managed to make it all working after a couple days, I can use the @Configurable Spring annotation in my Vaadin Controller so It can get auto injected with my Spring context repositories,
BTW I am using Compile-Time weaving with maven, codehaus plugins and AspectJ eclipse plugin so tomcat can get the necessary libs.
BUT...
It sometimes works sometimes doesn't...
I found that when I add serializable interface to my repos it works, but only If I ask  to generate the serialId and then  run the app (tomcat) right after it, if I make any changes and build it again, injection is gone.
My config and Classes...
part that I think matters of my applicationContext.xml
   .
   .
   Other stuff

    <context:spring-configured />
    <context:component-scan base-package="br.com.gsc" />
    <mvc:annotation-driven />
    <tx:annotation-driven transaction-manager="transactionManager"/>

   .
   .
   Other stuff

here is the Vaadin Servlet
package br.com.gsc.vaadin;

import org.springframework.beans.factory.annotation.Autowire;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Configurable;

import br.com.gsc.model.tableMapping.Person;
import br.com.gsc.repository.objRepos.PersonRepository;

import com.vaadin.Application;
import com.vaadin.ui.Label;
import com.vaadin.ui.Panel;
import com.vaadin.ui.Window;

@Configurable(preConstruction=true,autowire=Autowire.BY_TYPE)
public class VaadinOperatorServlet extends Application {

/**
     *
     */
    private static final long serialVersionUID = -1481084776783567319L;

    @Autowired
    private transient PersonRepository pRepo;

    public void init() {
        createWindow();
    }

    public void createWindow(){
        Window window = new Window();
        Panel p = new Panel();
        Label l = new Label("Teste");
        Label l2 = new Label("");
        Label l3 = new Label("");

        Person person = pRepo.findPersonByID("user");
        l2 = new Label(person.getUsername());
        p.addComponent(l);
        p.addComponent(l2);
        window.addComponent(p);
        setMainWindow(window);
        window.getContent().setSizeFull();
    }
}

My Repo
package br.com.gsc.repository.objRepos;

import java.io.Serializable;
import java.util.List;

import org.springframework.stereotype.Repository;

import br.com.gsc.model.tableMapping.Person;
import br.com.gsc.repository.AbsRepository;
import br.com.gsc.repository.objInterfaces.IPersonRepository;

@Repository
public class PersonRepository extends AbsRepository<Person> implements IPersonRepository,Serializable{

    /**
     *
     */
    private static final long serialVersionUID = -8520715359024018210L;

    @Override
    public void addPerson(Person t) {
        add(t);
    }

    Lot's of other stuff....

}

Web.xml with the servlet routings and other stuff.
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    id="WebApp_ID" version="2.5">
    <display-name>GSC</display-name>
    <welcome-file-list>
        <welcome-file>/intern.html</welcome-file>
    </welcome-file-list>

    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

      <listener>
        <listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
      </listener>

    <context-param>
        <param-name>productionMode</param-name>
        <param-value>false</param-value>
    </context-param>

    <servlet>
        <servlet-name>spring</servlet-name>
        <servlet-class>
            org.springframework.web.servlet.DispatcherServlet
        </servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet>
        <servlet-name>vaadinServlet</servlet-name>
        <servlet-class>com.vaadin.terminal.gwt.server.ApplicationServlet</servlet-class>
        <init-param>
            <param-name>application</param-name>
            <param-value>br.com.gsc.vaadin.VaadinOperatorServlet</param-value>
        </init-param>
        <init-param>
            <description>Application widgetset</description>
            <param-name>widgetset</param-name>
            <param-value>br.com.gsc.vaadin.widgetset.GscWidgetset</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>vaadinServlet</servlet-name>
        <url-pattern>/admin/*</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>vaadinServlet</servlet-name>
        <url-pattern>/oper/*</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
          <servlet-name>vaadinServlet</servlet-name>
          <url-pattern>/VAADIN/*</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>spring</servlet-name>
        <url-pattern>*.html</url-pattern>
    </servlet-mapping>

    <filter>
      <filter-name>openEntityManager</filter-name>
      <filter-class>org.springframework.orm.jpa.support.OpenEntityManagerInViewFilter</filter-class>
    </filter>
    <filter-mapping>
      <filter-name>openEntityManager</filter-name>
      <url-pattern>/*</url-pattern>
    </filter-mapping>

    <filter>
        <filter-name>springSecurityFilterChain</filter-name>
        <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>springSecurityFilterChain</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

    <filter>
        <filter-name>httpMethodFilter</filter-name>
        <filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
    </filter>

    <filter-mapping>
        <filter-name>httpMethodFilter</filter-name>
        <servlet-name>spring</servlet-name>
    </filter-mapping>

</web-app>

Answer: Sounds like a problem we had, where we had correctly configured maven to compile-time weave our @Configurable's, but Eclipse did not do this automatically.
This is a feature of the m2eclipse plugin in eclipse that's lacking I think.
Because you correctly define the spring-aspects jar in the aspects path in the pom file, but eclipse doesn't know to do this as well.
So we had to manually add the AOP facet to your project that contains @Configurables, and then configure it to add the spring-aspects.jar as the aspects path.
Then when eclipse compiles, the aspects are woven, and when you run your tomcat from Eclipse, your tomcat will use woven classes, instead of non-woven classes.
Answer: Well I could not fix it by any means...
I finally used Spring roo to build a maven web app and pasted all my codes and configs there, because I knew Roo worked out of the box with Aspects.
It's now working... but I have no clue why my last project had that issue with DI outside Spring Context.


Replacing site logo with ACF

Question: I'm using Astra theme on WordPress and I'm trying to replace the site logo with an ACF field entry. Having really big difficulties setting the logo at all using Astra's astra_replace_header_logo filter. Trying to start with baby steps and replace the logo with a hardcoded url or attachment ID, but neither seem to be working.
function custom_astra_replace_header_logo($image) {
$custom_logo_nav_id = get_field('logo_nav', 'options', false);
if($custom_logo_nav_id) {

$image[0] = '/wp-content/uploads/2021/05/new-logo.png';
return $image;
}
}

add_filter( 'astra_replace_header_logo', 'custom_astra_replace_header_logo' );

This doesn't seem to have any effect all. I also tried using the attachment ID together with the size. Astra's function suggests returning url should be fine though (https://github.com/brainstormforce/astra/blob/master/inc/extras.php#L260).
Interesingly if I set the $image to be something odd, like just the attachment ID $image = 5412 ; I get a broken image on front-end with src(unknown)
Really don't understand why this isn't working. Anyone have any experience with this? Any help greatly appreciated, thanks.
Answer: According to the source for that function, it ultimately calls wp_get_attachment_image_src
    function astra_replace_header_logo( $image, $attachment_id, $size, $icon ) {

        $custom_logo_id = get_theme_mod( 'custom_logo' );

        if ( ! is_customize_preview() && $custom_logo_id == $attachment_id && 'full' == $size ) {

            $data = wp_get_attachment_image_src( $attachment_id, 'ast-logo-size' );

            if ( false != $data ) {
                $image = $data;
            }
        }

        return apply_filters( 'astra_replace_header_logo', $image );
    }

The function returns false other failure, or an array of:
[
   $url,       // Image URL,
   $width,     // Image width
   $height,    // Image height
   $cropped,   // Was the image cropped
]

Comment: Thanks. It was my understanding that if using $image[0], it would just expect the first value. I actually did try returning `array('url to image', 150, 80, false); ` as well, but I was only able to really affect the size of the original image file, but the src for image never changed. Very weird behavior and I don't quite understand what's happening.
Answer: Figured out what was wrong. Plugin called WP Offload Media which I use to upload media files to AWS automatically, was for some reason rewriting the URL for the logo and it was always using the original Astra site logo. Even though the function was working.
The function works as expected when I disabled Offload Media. Now just need to figure out why that is doing what it's doing :)
This was the function I used in the end:
function custom_astra_replace_header_logo( $image ) {
$custom_logo_nav_id = get_field('logo_nav', 'options');
    if($custom_logo_nav_id == true){

        $image[0] = $custom_logo_nav_id;
        return $image;
    }

    return $image;
}

add_filter( 'astra_replace_header_logo', 'custom_astra_replace_header_logo' );

Replacing site logo with ACF


IIS and VS, How do they work together?

Question: I'm a bit confused.
When I type in my browser a "local" address (of a web site I'm editing on VS), IIS can handle it. How is that so? How can IIS know what's my latest web site version? What's the difference between typing the address in the browser and compiling the web site, and what does localhost has to do with all of that? And last one - is the IIS on my machine accessible to other computers on the net?
Edited the last one..
Thanks a lot.
Answer: localhost is an alias for the loopback address 127.0.0.1. It's not actually hard-coded; you can find it in C:\WINDOWS\system32\drivers\etc\hosts.
Pointing your browser to http://localhost/... will open port 80 on your local machine, which is the port IIS listens on by default. IIS doesn't actually know your website's latest version. It will simply find whatever assemblies and other files it has been directed to use, in whatever state they are in. Compiling will generate new assemblies to match your latest code, and IIS will pick those new assemblies up on the next request that hits the site.
The localhost address isn't accessible from other machines. They will almost certainly have the same alias, pointing to their loopback interface.

IIS and VS, How do they work together?


Pella Door won't lock (3 point lock)

Question: I have several Pella doors in my home with the 3 point locks (top and bottom "shootbolts" and a dead bolt near the handle).  They have been problematic.  The locking mechanism on a couple of rarely used doors would hardly work anymore (very stiff and wouldn't lock anymore).  So I disassembled them, cleaned up the runners and other parts, applied a good lube, reassembled and they worked again. They are a pain to take apart, re-adjust and reassemble.
Recently they started doing the same thing. I though oh no, not again. I didn't initially consider there might have been a new cause.  What could that cause be?
Answer: So I starting looking into the failure of my 3 point door locks and heard a clanking when trying to put them into the locked position. I realized that the "shootbolts" were slamming against the side of the door. Why?  Was there an internal jam?   A broken parts.
Turns out there is a small bottom plate with a hole that receives the shootbolt (pic attached)  It was full of debris!  I cleaned it out and the locks worked fine again.  Easy as that.  But I almost overlooked it because I had a previous mind-set about what was wrong and what the fix was. Sometimes I just make it too hard. Lesson learned:  Look for the easy/simple stuff first.
Answer: Freezing temperatures, wet snow and strong winds managed to cause ice build up in the lower shootbolt hole. May of contributed to the problem after sweeping snow away from doorwall earlier.
Comment: Welcome to [diy.se], please take the [tour]. While this does seem to answer the question, reading through [how to write a good answer](https://diy.stackexchange.com/help/how-to-answer) would give you some tips to improve it.

Pella Door won't lock (3 point lock)


Elementary proof of prime number theorem?

Question: From Wikipedia:
"The prime number theorem is also equivalent to:
$$\lim_{x \rightarrow \infty} \frac{\psi(x)}{x}=1$$
where $$\psi(x) = \sum\limits_{n \leq x} \Lambda(n)$$
is the Chebyshev function.
and where:
$$\Lambda(n) = \begin{cases} \log p & \text{if }n=p^k \text{ for some prime } p \text{ and integer } k \ge 1, \\ 0 & \text{otherwise.} \end{cases}$$
is the von Mangoldt function.
The von Mangoldt function can be calculated as.

Edit 27.1.2018, I rewrote the whole question from here on, trying to use more conventional notation. $n$ stands for row index, and $k$ stands for column index.
Mathematica knows that: $$\log(n)=\lim\limits_{s \rightarrow 1}\zeta(s)\left(1-\frac{1}{n^{s-1}}\right) \; \; \; \; \; \; (1)$$
and it has been proven that for $n>1$ the von Mangoldt function is:
$$\Lambda(n)=\lim\limits_{s \rightarrow 1}\zeta(s)\sum\limits_{d|n} \frac{\mu(d)}{d^{s-1}} \; \; \; \; \; \; (2)$$
The Dirichlet series associated with the von Mangoldt function defined in such away  as above, is the infinite symmetric square matrix $T_1$:
$$T_1=a(GCD(n,k)) \; \; \; \; \; \; (3)$$
which starts:
$$T_1 = \left(   \begin{array}{ccccccc}   +1&+1&+1&+1&+1&+1&+1&\cdots \\ +1&-1&+1&-1&+1&-1&+1 \\ +1&+1&-2&+1&+1&-2&+1 \\ +1&-1&+1&-1&+1&-1&+1 \\ +1&+1&+1&+1&-4&+1&+1 \\ +1&-1&-2&-1&+1&+2&+1 \\ +1&+1&+1&+1&+1&+1&-6 \\ \vdots&&&&&&&\ddots \end{array}   \right)$$
where:
$$a(n) = \sum\limits_{d|n} d \cdot \mu(d) \; \; \; \; \; \; (4)$$
(better known as the Dirichlet inverse of the Euler totient.)
Now by periodicity of the entries in the columns for $m=0,1,2,3,4,5,...$ or $m \in \mathcal ℕ_0$, the column sums satisfy:
$$\sum\limits_{n=1+m}^{n=k+m} T_1(n,k)=\begin{cases}1 & \mbox{ if } k=1\\ 0&\mbox{ if } k>1.\end{cases}  \; \; \; \; \; \; (5)$$
and by periodicity of the entries in the rows, the row sums satisfy:
$$\sum\limits_{k=1+m}^{k=n+m} T_1(n,k)=\begin{cases}1 & \mbox{ if } n=1\\ 0&\mbox{ if } n>1.\end{cases} \; \; \; \; \; \; (6)$$
by symmetry.
Since from $(2)$ for $n>1$:
$$\Lambda(n)=\sum\limits_{k=1}^{k=\infty}\frac{T_1(n,k)}{k} \; \; \; \; \; \; (7)$$
and:
$$\sum\limits_{n=1+m}^{n=k+m} \frac{T_1(n,k)}{k} =\begin{cases}1 & \mbox{ if } k=1\\ 0&\mbox{ if } k>1.\end{cases}  \; \; \; \; \; \; (8)$$
and since the denominator is $k$ in $(8)$ and the length of the period in the $k$-the column is also $k$, we can say that the average contribution to $\Lambda(n)$ from an entry $T_1(n,k)$ for $k>1$ in matrix $T_1$ must be:
$$\sum\limits_{n=1+m}^{n=k+m} \frac{T_1(n,k)}{k} =\begin{cases}1 & \mbox{ if } k=1\\ 0&\mbox{ if } k>1.\end{cases}  \; \; \; \; \; \; (9)$$
Writing:
$$\sum_{n \leq x} \Lambda(n)=\sum_{n \leq x} \sum\limits_{k=1}^{k=\infty}\frac{T_1(n,k)}{k} \; \; \; \; \; \; (10)$$
Combining $(9)$ with the right hand side of $(10)$ and multiplying the denominators $k \cdot k = k^2$ we get:
$$\sum_{n \leq x} \Lambda(n)=\sum_{n \leq x} \sum\limits_{k=1}^{k=\infty}\sum\limits_{n=1+m}^{n=k+m} \frac{T_1(n,k)}{k^2} =\begin{cases} (1+o(1))x & \mbox{ if } k=1\\ (0+o(1))x &\mbox{ if } k>1.\end{cases}  \; \; \; \; \; \; (11)$$
and thereby at least heuristically:
$$\sum_{n \leq x} \Lambda(n) = (1+o(1)) x  \; \; \; \; \; \; (12)$$
$\square$
Associated Mathematica 8 code:
<code>nn = 7
a[n_] := If[n < 1, 0, Sum[d MoebiusMu@d, {d, Divisors[n]}]]
MatrixForm[
 Table[Table[If[k == 1, 0, a[GCD[n, k]]], {k, 1, nn}], {n, 1, nn}]]
MatrixForm[
 Table[Table[
   Sum[If[k == 1, 0, a[GCD[n, k]]], {k, 1, x}], {x, 1, nn}], {n, 1,
   nn}]]
MatrixForm[
 Table[Table[
   Sum[If[k == 1, 0, a[GCD[n, k]]], {k, 1, x}]/x, {x, 1, nn}], {n, 1,
   nn}]]
</code>

Edit 18.2.2018: I will try to add some details.
Starting with matrix $T_1$ defined above, we form the matrix $T_2$, but before that we state again the property of matrix $T_1$, namely:
$$\Lambda(k) = \sum\limits_{n=1}^{n=\infty}\frac{T_1(n,k)}{n}$$
and then matrix $T_2$:
$$T_2(n,k)=\sum\limits_{k=1}^{k=g}T_1(n,k)$$
where:
$$g=1,2,3,4,5,...$$
and:
$$n=1,2,3,4,5,...$$
Matrix $T_2$ in turn has the property:
$$\psi(x)=\sum\limits_{k \leq x} \Lambda(k) = \sum\limits_{n=1}^{n=\infty}\frac{T_2(n,k)}{n}$$
We then form matrix $T_3$:
$$T_3(n,k)=\frac{T_2(n,k)}{n \cdot k}$$
Since for $n>1$:
$$\lim\limits_{k \rightarrow \infty} T_3(n,k) = 0$$
and since:
$$\lim\limits_{k \rightarrow \infty} T_3(1,k) = 1$$
the prime number theorem is true/follows.
$\square$
In case I did not get it entirely right I attach this second program in Mathematica as a verification:
<code>(*start*)
nn = 12;
TableForm[
  A = Table[Table[If[Mod[n, k] == 0, 1, 0], {k, 1, nn}], {n, 1, nn}]];
TableForm[
  B = Table[
    Table[If[Mod[k, n] == 0, MoebiusMu[n]*n, 0], {k, 1, nn}], {n, 1,
     nn}]];
TableForm[T1 = (A.B)];
TableForm[
 T2 = Table[Table[Sum[T1[[n, k]], {k, 1, g}], {g, 1, nn}], {n, 1, nn}]]
TableForm[T3 = Table[Table[T2[[n, k]]/n/k, {k, 1, nn}], {n, 1, nn}]]
(*end*)
</code>
Answer: Such proofs are heuristic. They can be used to demonstrate that a certain result is probably true. Similar arguments can be used to "prove" the twin prime conjecture or show that there are infinitely many Mersenne primes. Such arguments are never rigorous as they do not actually prove anything, they can simply serve as an indication that a particular result could be true. I believe Terence Tao is interested in these so-called heuristic justifications, so you might want read his blog. Also, I remember watching a talk he gave about this area of research on YouTube.
Comment: I unselected this answer because of the changes I made to the question. I made an attempt at a proof.


Networking with Multiple Nics

Question: I have an Ubuntu 12.04 server with 4 Network adapters in it. I need to use each NIC for a separate function. Here is a description of my setup:
etho = 10.234.0.2 netmask = 255.255.255.252 gw = 10.234.0.1 This is on vlan 234
eth1 = 10.235.0.2 netmask = 255.255.255.252 gw = 10.235.0.1 This is on vlan 235
eth2 = 10.236.0.2 netmask = 255.255.255.252 gw = 10.236.0.1 This is on vlan 236
eth3 = 10.237.0.2 netmask = 255.255.255.252 gw = 10.237.0.1 This is on vlan 237

I need to be able to direct traffic to and from the individual IP addresses for separate web services. ie 10.235.0.2 is a website, 10.236.0.2 is a different site, and 10.237.0.2 is a third site. The 1st IP is for management of the server.
I think the issue is a routing issue, but I am new enough to Linux to not have a full understanding of the ins and outs of the routing capabilities.
Here is what is in my /etc/network/interfaces file:
auto lo
iface lo inet loopback

# WWW Management
auto eth0
iface eth0 inet static
address 10.234.0.2
netmask 255.255.255.252
gateway 10.234.0.1
nameseervers 10.230.1.103, 10.230.70.70

# WWW
auto eth1
iface eth1 inet static
address 10.235.0.2
netmask 255.255.255.252
gateway 10.235.0.1

# WTB
#auto eth2
#iface eth2 inet static
#address 10.236.0.2
#netmask 255.255.255.252
#gateway 10.236.0.1

# Moodle
#auto eth3
#iface eth3 inet static
#address 10.237.0.2
#netmask 255.255.255.252
#gateway 10.237.0.1

I have disabled the last two networks just to ease confusion.
Thanks in advance for all of the help and comments and suggestions.
Answer: After doing a normal configuration of just eth0, I came back around and added config for eth1. With just eth0 up, the route table was:
# ip route show
192.168.0.96/27 dev eth0 proto kernel scope link src 192.168.0.126
default via 192.168.0.97 dev eth0 metric 100

But once I brought up eth1, the order of the default route statements determined which interface was always used. As shown below, it happens to choose the eth1 route to the 192.168.1.65 gateway.
# ip route show
192.168.0.96/27 dev eth0 proto kernel scope link src 192.168.0.126
192.168.1.64/27 dev eth1 proto kernel scope link src 192.168.1.93
default via 192.168.1.65 dev eth1 metric 100
default via 192.168.0.97 dev eth0 metric 100

only one gateway statement
The first problem can be the extra 'via 192.168.1.65' default route. It appears there if the eth1 definition in /etc/network/interfaces has a "gateway 192.168.1.65" statement. So remove any extra gateway statement, and bounce the interface:
# ifdown eth1
# ifup eth1
# ip route show
192.168.0.96/27 dev eth0 proto kernel scope link src 192.168.0.126
192.168.1.64/27 dev eth1 proto kernel scope link src 192.168.1.93
default via 192.168.0.97 dev eth0 metric 100

setup new routing table
Create a new, seperate routing table containing a default route appropriate for all traffic flowing out of eth1. The table number here is not important; 101 is simply not the main routing table. Do this with a 'post-up' command on the eth1 configuration in /etc/network/interfaces. Add only one post-up on eth1; Do not add it to any of the eth1: sub-interfaces.
post-up ip route add default via 192.168.1.65 dev eth1 table 101

Bounce eth1. The main routing table is unchanged, and table 101 will contain the via 192.168.1.65 default route if eth1 is up.
# ifdown eth1
# ip route show
192.168.0.96/27 dev eth0 proto kernel scope link src 192.168.0.126
default via 192.168.0.97 dev eth0 metric 100

# ip route show table 101   (ie, table is empty, no output)
# ifup eth1
# ip route show
192.168.0.96/27 dev eth0 proto kernel scope link src 192.168.0.126
192.168.1.64/27 dev eth1 proto kernel scope link src 192.168.1.93
default via 192.168.0.97 dev eth0 metric 100

# ip route show table 101
default via 192.168.1.65 dev eth1

new routing rule
Add a routing rule to use table 101 to select a default route for packets which should go out eth1.
# ip rule add from 192.168.1.64/27 lookup 101
# ip rule show
0:     from all lookup local
32765: from 192.168.1.64/27 lookup 101
32766: from all lookup main
32767: from all lookup default

Add the rule to the /etc/network/interfaces file as well:
post-up ip rule add from 192.168.1.64/27 lookup 101

Now make sure to add cleanup to remove the route and rule when the interface goes down:
post-down ip rule del from 192.168.1.64/27
post-down ip route del default via 192.168.1.65 table 101

[EDIT for ubuntu 16.04+]
Like indicated here and from test I've made from this help, ip route2 have changed his structure of commands.
For making work you will have to adapt just a bit to do in the order how the man ip points.
up ip route add default table 101 dev eth1 via 192.168.1.65
up ip rule add from 192.168.1.64/27 lookup 101
down ip rule del from 192.168.1.64/27
down ip route del default table 101 via 192.168.1.65

Or you will end up after a ifdown - ifup command with a error message @ifdown command(standard message to say that the peripherals is not correctly configured), and @ifup the absence of a route in table 101.
Comment: Nice, but I don't like to use rc.local .. looking for a more elegant final step ..
Comment: It was edited I suppose :) ..
Comment: Is there actually an /etc/interfaces file, or is that a typo?
Comment: @user100464 `/etc/network/interfaces`
Comment: There is a ref to the former in the answer.  I can't edit it.

Networking with Multiple Nics


Passing "this" as an argument - C#

Question: I'm currently playing about with some XNA stuff learning to program AI. Anyway, here's my situation: Class A has a function which takes a reference to an instance of class B, does some stuff to to it, and returns it. Class B contains an instance of Class A, and then calls the function from it.
Example in code:
Class A
{
    B classB;

    public A()
    {
        classB = new B();
    }

    public void Act()
    {
        this = B.Do(ref this);
    }
}

Class B
{
    public A Do(ref A classA)
    {
        //Manipulate
        return classA;
    }
}

I've tried passing a memberwise clone .. but that didn't work, obviously, because "this" is read-only. I've no idea with this. I'm really stuck. Does anybody have any ideas? I'd ideally like to avoid having to pass every single variable in the object as a separate argument, really.
Andy.
Answer: Classes are reference types, so doing
Class B
{
    public void Do(A classA)
    {
        //Manipulate
    }
}

should manipulate the object classA references. Then in A,
Class A
{
    B classB;

    public A()
    {
        classB = new B();
    }

    public void Act()
    {
        B.Do(this);
    }
}

Note: "This does have the side effect that the reference of A that you pass cannot be set to null (it will only set the local variable to null)" - JulianR
Comment: This does have the side effect that the reference of A that you pass cannot be set to null (it will only set the local variable to null), which might have been the original reason why it expects a ref parameter.
Comment: That's a good point. I didn't think that was the OP's intent (it wasn't), but it could have been. I'll edit to point this out.
Answer: Your B.Do() method does it (modifying an A) double by using the ref and a return. Neither is needed to modify classA. And because you target this it won't work anyway. You never assign to this, it makes no sense.
So the Simple answer is
class B
{
   void Do(A anA) { anA.PublicProp = 1; }
}

But the circular referencing does make it a dubious design.
Answer: Is there something specific in //Manipulate that requires you to pass a class reference as ref? And why are you also returning classA as well - that seems to be redundent if you are using ref to begin with.
Comment: The whole thing is for behaviours for simple AI (EG chase, guard, evade etc). I'm wanting to pass the entire AI entity to the behaviours so that I can keep the behaviours separate for all entities (Sort of like a single style sheet for multiple style sheets).

The reason I want to pass the whole object is that some behaviours need certain parts of the object and some don't

As for why I'm returning .. I don't quite know how I came to that decision. I'll remove it.
Comment: Single style sheet for multiple pages rather!
Answer: just remove the ref keyword. you only need ref if you want to change the argument into something else, if you just want to manipulate it, don't use the ref.
I think it would be bad (tricky to understand) if the language allowed you to change this into that, so it disallows what you've tried.
Answer: you cannot use "ref" with "this".
Why do you need the parameter to be passed by reference ?
You only need a "ref" parameter if your function must change which object the caller is refering to. If all you need is to manipulate and/or change the fields of the parameter then you do not need a ref parameter.
Answer: For more clarity, the whole thing is for behaviours for simple AI (EG chase, guard, evade etc). I'm wanting to pass the entire AI entity to the behaviours so that I can keep the behaviours separate for all entities (Sort of like a single style sheet for multiple web pages). The reason I want to pass the whole object is that some behaviours need certain parts of the object and some don't.
As for why I'm returning .. I don't quite know how I came to that decision. I'll remove it
Answer: Thank you very much, Derek E!
I just tested what you said, and it worked fine.
My problem, I think, is that I was thinking that when I passed the argument it made a clone of it and manipulated that instead, like (I think ..) it does in PHP or VB (can't remember which of those I was told it does it in)
Answer: Objects are always passed by reference and not by value. That is why we call classes in C# as reference types. Be careful if you are using structures instead since they are value types. A copy of the structure will be passed rather than the original. If you wish to pass the original then you must add the ref keyword. ref is only useful with objects if you wish to replace a reference to one object with a reference to another object.

Passing "this" as an argument - C#


how to import pymongo in python3 without virtualenv?

Question: I'm new in python and I am starting a new project with mongodb and python3, but when I import pymongo in my script it give me the following error:
ImportError: No module named 'pymongo'

Here is my code:
#!/usr/bin/python3
import sys
from pymongo import MongoClient

Please note that I am running this python script from command line, not from a GUI.
Comment: Did you install `pymongo`? If so, how?
Answer: Python's 'batteries included' doesn't mean all Python modules exist on a system.
Open a terminal and install the pymongo package from Pypi.  The developers suggest:

If you have setuptools installed you should be able to do easy_install pymongo to install PyMongo. Otherwise you can download the project source and do python setup.py install to install.

They also continue

Do not install the "bson" package. PyMongo comes with its own bson package; doing "easy_install bson" installs a third-party package that is incompatible with PyMongo

I add this because if you were to use sudo apt-get- install python3-pymongo you would be required to install four additional packages, two of which would be python3-bson and python3-bson-ext.  I have not used pymongo so I don't know the implication of that.


How to Make Datepicker Comply with WCAG 2.0?

Question: Recently I have received a project to make a webpage comply with WCAG 2.0 Level A. The part that I am running into a problem at the moment is the datepicker component. The datepicker component allows the user to select the date in two ways. One way is to manually type in a date, for example, 04/06/2014. The other way is to select the small image beside it and a calendar would basically pop-up and the user can select the date from there.
While researching over the web, some people have suggested that we do not have to make the image part of the datepicker component accessible since the text-field itself provides an alternative for accessibility. Is this acceptable (First Question)?
If this is the right way to go, how do I make it so that accessibility technology like screen reader would ignore the image icon (Second Question)? I have also tried to research for this issue. Basically, if it was just an image, we could set the "alt" attribute to null. But this image is actually embedded inside an "anchor" tag (which makes the image click-able) therefore this practice is invalid (verified by achecker.ca).

Update: HTML5 Accessibility: aria-hidden and role="presentation" answers the second question

Any thoughts would be helpful. Thank you
Answer: The answer to the first question depends on what the usability reason is for showing a visual calendar? If you are showing it so that users can select a date based on use cases like "first Friday in Month X" or something similar, then simply providing a text input, while making the page at least usable, does not make the page functionally equivalent for screen reader and keyboard-only users and therefore does not pass WCAG 2.
Your answer to the second question that you posted, works for screen readers (in terms of removing the aforementioned functionality) but it now presents a problem to sighted keyboard-only users. You are therefore still not WCAG 2 compliant.
Making date pickers accessible, while difficult, is possible. Are you using the jQuery UI datepicker?


spring Ibatis Mysql ReplicationDriver

Question: i had use the spring3.1 ibatis2.x and mysql5.5.
then i wanna use the replication driver .
my code is:
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
    <property name="driverClassName" value="com.mysql.jdbc.ReplicationDriver" />
    <property name="url" value="jdbc:mysql:replication://192.168.1.160:3306/test,192.168.1.160:3306/test" />
    <property name="username" value="root" />
    <property name="password" value="root" />
.....

then:
Caused by: org.apache.commons.dbcp.SQLNestedException:
Cannot create PoolableConnectionFactory (Must specify at least one slave host to connect to for master/slave replication load-balancing functionality)
at org.apache.commons.dbcp.BasicDataSource.createPoolableConnectionFactory(BasicDataSource.java:1549)
at org.apache.commons.dbcp.BasicDataSource.createDataSource(BasicDataSource.java:1388)
at org.apache.commons.dbcp.BasicDataSource.getConnection(BasicDataSource.java:1044)
at org.springframework.jdbc.datasource.DataSourceUtils.doGetConnection(DataSourceUtils.java:111)
at org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy$TransactionAwareInvocationHandler.invoke(TransactionAwareDataSourceProxy.java:224)
at $Proxy50.getMetaData(Unknown Source)
at org.springframework.jdbc.support.JdbcUtils.extractDatabaseMetaData(JdbcUtils.java:285)
... 50 more

Caused by: java.sql.SQLException: Must specify at least one slave host to connect to for master/slave replication load-balancing functionality
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:910)
at com.mysql.jdbc.NonRegisteringReplicationDriver.connect(NonRegisteringReplicationDriver.java:107)
at org.apache.commons.dbcp.DriverConnectionFactory.createConnection(DriverConnectionFactory.java:38)
at org.apache.commons.dbcp.PoolableConnectionFactory.makeObject(PoolableConnectionFactory.java:582)
at org.apache.commons.dbcp.BasicDataSource.validateConnectionFactory(BasicDataSource.java:1556)
at org.apache.commons.dbcp.BasicDataSource.createPoolableConnectionFactory(BasicDataSource.java:1545)

so how to make the ibatis to support replication
Comment: see here http://stackoverflow.com/questions/5834046/using-mysql-replication-master-slave-with-mybatis
Answer: Try this
<property name="url" value="jdbc:mysql:replication://192.168.1.160:3306,192.168.1.160:3306/test" />

The format is : master,slave1,slave2
Don't why you taking same server for load balancing.

spring Ibatis Mysql ReplicationDriver