Google Foobar Level 4 - Graph Problem

Question: So, I have been solving problems in Google Foobar for the past two weeks or so ans has reached Level 4. The first problem is as stated below and I have come up with a solution which is able to pass all test cases except one. I have been stuck on it for the past 3 days and hasn't been able to made any progress so far. Can someone help me by pointing me in the right direction.
Here's the problem statement:
Running with Bunnies
You and your rescued bunny prisoners need to get out of this collapsing death trap of a space station - and fast! Unfortunately, some of the bunnies have been weakened by their long imprisonment and can't run very fast. Their friends are trying to help them, but this escape would go a lot faster if you also pitched in. The defensive bulkhead doors have begun to close, and if you don't make it through in time, you'll be trapped! You need to grab as many bunnies as you can and get through the bulkheads before they close.
The time it takes to move from your starting point to all of the bunnies and to the bulkhead will be given to you in a square matrix of integers. Each row will tell you the time it takes to get to the start, first bunny, second bunny, ..., last bunny, and the bulkhead in that order. The order of the rows follows the same pattern (start, each bunny, bulkhead). The bunnies can jump into your arms, so picking them up is instantaneous, and arriving at the bulkhead at the same time as it seals still allows for a successful, if dramatic, escape. (Don't worry, any bunnies you don't pick up will be able to escape with you since they no longer have to carry the ones you did pick up.) You can revisit different spots if you wish, and moving to the bulkhead doesn't mean you have to immediately leave - you can move to and from the bulkhead to pick up additional bunnies if time permits.
In addition to spending time traveling between bunnies, some paths interact with the space station's security checkpoints and add time back to the clock. Adding time to the clock will delay the closing of the bulkhead doors, and if the time goes back up to 0 or a positive number after the doors have already closed, it triggers the bulkhead to reopen. Therefore, it might be possible to walk in a circle and keep gaining time: that is, each time a path is traversed, the same amount of time is used or added.
Write a function of the form solution(times, time_limit) to calculate the most bunnies you can pick up and which bunnies they are, while still escaping through the bulkhead before the doors close for good. If there are multiple sets of bunnies of the same size, return the set of bunnies with the lowest prisoner IDs (as indexes) in sorted order. The bunnies are represented as a sorted list by prisoner ID, with the first bunny being 0. There are at most 5 bunnies, and time_limit is a non-negative integer that is at most 999.
For instance, in the case of
[
[0, 2, 2, 2, -1],  # 0 = Start
[9, 0, 2, 2, -1],  # 1 = Bunny 0
[9, 3, 0, 2, -1],  # 2 = Bunny 1
[9, 3, 2, 0, -1],  # 3 = Bunny 2
[9, 3, 2, 2,  0],  # 4 = Bulkhead
]
and a time limit of 1, the five inner array rows designate the starting point, bunny 0, bunny 1, bunny 2, and the bulkhead door exit respectively. You could take the path:

Start End Delta Time Status
-   0     -    1 Bulkhead initially open
0   4    -1    2
4   2     2    0
2   4    -1    1
4   3     2   -1 Bulkhead closes
3   4    -1    0 Bulkhead reopens; you and the bunnies exit
With this solution, you would pick up bunnies 1 and 2. This is the best combination for this space station hallway, so the answer is [1, 2].
Solution
There are two parts of the solution that I have come up with:

Negative Cycle - if there is any negative cycle in the graph then we can just loop it as many times as required and pick all the bunnies. I am doing this by Floyd Warshall algorithm as well as getting all the shortest pair paths which can be used in case there is no negative cycle

DFS - In case there is no negative cycle, I simply start from the start point and try to get all the permutations of the order in which we can travel the graph and then check if the solution is correct at the end point.
<code>    static int size;
    static List < Integer > ans;
    public static int[] solution(int[][] times, int times_limit) {
        // Your code here
        int n = times.length;
        if (n <= 2 || (n != times[0].length)) {
            return new int[] {};
        }
        boolean negCycle = check(times, n);
        if (negCycle) {
            int[] ans = new int[n - 2];
            for (int i = 0; i < n - 2; i++) {
                ans[i] = i + 1;
            }
            return ans;
        } else {
            size = 0;
            ans = new ArrayList < >();
            boolean[] visited = new boolean[n];
            visited[0] = true;
            for (int i = 1; i < n - 1; i++) {
                dfs(i, times_limit - times[0][i], times, new ArrayList < >(), visited);
            }
            if (ans.size() == 0) {
                return new int[] {};
            }
            int[] ret = new int[ans.size()];
            for (int i = 0; i < ret.length; i++) {
                ret[i] = ans.get(i);
            }
            Arrays.sort(ret);
            return ret;
        }
    }

    public static void dfs(int u, int time, int[][] times, List < Integer > list, boolean[] visited) {

        int n = times.length;
        if (time <= -999 || (u == n - 1 && time < 0) || (size == n - 2)) {
            return;
        }
        if (time >= 0 && u == n - 1) {
            if (list.size() > size) {
                ans = new ArrayList < >(list);
                size = list.size();
            }
            return;
        }
        if (visited[u]) {
            return;
        }
        visited[u] = true;
        list.add(u - 1);
        for (int v = 1; v < n; ++v) {
            if (v == u) {
                continue;
            }
            dfs(v, time - times[u][v], times, list, visited);
        }
        list.remove(list.size() - 1);
        visited[u] = false;
    }

    public static boolean check(int[][] times, int n) {
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                for (int k = 0; k < n; k++) {
                    if (times[i][k] + times[k][j] < times[i][j]) {
                        times[i][j] = times[i][k] + times[k][j];
                    }
                }
            }
        }
        for (int i = 0; i < n; i++) {
            if (times[i][i] < 0) {
                return true;
            }
        }
        return false;
    }
} ```

</code>

Please let me know if there's something wrong in my methodology.
Comment: I don't have the patience to look at your code, but could help you by showing you [a solution that passed all the tests](https://github.com/franklinvp/foobar/blob/master/foobar2020/solutionProblem4.py). Maybe by comparing them you can see what yours might be missing.
Answer: I found the issue in my code. It was a very stupid mistake from my end. It was not passing the test case where there was a negative cycle in the graph because I was passing the result based on 1 as index starting instead of 0.
The original return value was being made by this:
<code>for (int i = 0; i < n - 2; i++) {
      ans[i] = i + 1; // Extra one here
}

While it should be:
for (int i = 0; i < n - 2; i++) {
      ans[i] = i;
}
</code>

Google Foobar Level 4 - Graph Problem


Using Multisim to Measure Thevenin Resistance

Question: Using probes, it is easy to find the Thevenin voltage, and Norton Current of a circuit. We could simply divide Vth / In = Rth, but is there a way to find Rth through a simulation?
Answer: When you ask this kind of question, it's usually single-ended (shared ground, single signal wire in or out of a circuit.) So, the simplified behavioral idea is something like this:

simulate this circuit – Schematic created using CircuitLab
Where you have a shared ground and just want to test, say, the signal input pin to find out its input resistance. (Or, you can direct it to the signal output pin to find out its output resistance, I suppose.)
AC Analysis
Most Spice programs will support AC Analysis using the .AC card. If you do this, then you can implement the following:

simulate this circuit
AC Analysis is usually performed over some range of frequencies that you specify. So use a range that is meaningful to you and also make sure that the value of the capacitor, \$C_1\$, presents a tiny impedance compared to what you expect to measure at the lowest frequency in your range. (I've simply supplied some value, but not a particular value, for illustration purposes.)
The capacitor is needed in order to allow the circuit under test to find it's own DC operating point, which you do NOT want to mess with. So the capacitor acts to isolate the testing from the circuit under test.
Most Spice programs I know about allow you to specify a standard voltage value for the AC source shown above. This is usually just "1" and represents the default \$1\:\text{V}\$. (If you use a different value, you need to be aware of that difference because it matters.) You then measure the current in the AC test voltage source. Dividing that current into \$1\:\text{V}\$ provides the observed resistance.
Transient Analysis
Another way you can do this is, is to try using the Transient Analysis mode of Spice using the .TRAN card. A very similar schematic is used:

simulate this circuit
Now, in the above case I've decided to use \$10\:\mu\text{V}\$ as the peak voltage (which is NOT the RMS voltage, keep in mind) and have chosen to use \$1\:\text{kHz}\$ as the signal frequency. So here, you get to pick a particular frequency for testing. It will help you with that specific frequency and no other frequency. So keep that in mind.
And again, you want \$C_1\$ to present a tiny impedance compared to what you expect to measure at that given frequency.
If you divide the RMS voltage of the source by the RMS current of the source, then you'll have your value.
(Make sure that you do NOT do the .TRAN run using the UIC, though. You want to allow Spice to perform the ITS step it needs to find the DC operating point.)
Using the .MEAS Card
LTspice, for example, supports a .MEAS card which can be quite handy to use with the transient analysis mode.
For example, suppose the voltage source is V1 and its signal node is also called V1. Then the following work well:
.meas TRAN SRCV RMS V(V1)
.meas TRAN SRCI RMS I(V1)
.meas TRAN RTH PARAM SRCV/SRCI

LTspice will complete the analysis and provide, in its "Spice Error Log" report, the following kinds of information:
srcv: RMS(v(v1))=7.06862e-006 FROM 0 TO 0.02
srci: RMS(i(v1))=7.06859e-009 FROM 0 TO 0.02
rth: srcv/srci=1000

As you can see, it has worked out that the impedance is \$1\:\text{k}\Omega\$, which is correct for the case I ran (for \$20\:\text{ms}\$, as you can see, which is fine enough for a \$1\:\text{kHz}\$ signal.)
Summary
It's important that you ensure that Spice produces enough data points for your need.  So, for example, if you are using a \$1\:\text{kHz}\$ signal and transient analysis then you will want lots of data points for each cycle so that it can produce better numbers for you. The same thing is true for AC analysis. Lots of data points are important. So don't be shy about asking for them. It helps get you better numbers.
Also, you don't want to disturb the DC operating point of whatever it is that you are measuring. So the use of an AC signal through a capacitor is a pretty good way to achieve this, even with simple DC circuits including only one resistor. (It "just works.")
Note that the only limitation is your imagination! There are a number of ways to go about getting what you want. You just have to think for a moment. But usually not long. For example, suppose that the input is differential instead of single-ended? How might you modify any of the above to achieve that measurement? You should be able to come up with a couple of different ways, now.
Example
I pulled out an old circuit I had considered for a \$9\:\text{V}\$ battery-driven headphone amplifier, years ago. I just found it by doing a quick search on my disk. After adding the above .MEAS commands to it and providing an appropriate input source, the schematic looks like this:

Simple analysis suggests that the input resistance is about:
$$22\:\text{k}\Omega\:\mid\mid\:22\:\text{k}\Omega\:\mid\mid\:18\:\text{k}\Omega\approx 6827.59\:\Omega$$
(This assumes that the (-) input of the opamp can be taken to be a "virtual voltage reference.")
Here's the result of the LTspice analysis:
srcv: RMS(v(vi))=7.06978e-006 FROM 0 TO 0.02
srci: RMS(i(vi))=1.03558e-009 FROM 0 TO 0.02
rth: srcv/srci=6826.91

Good enough for horseshoes, anyway! ;)
Answer: I don't have Multisim, but assuming it's an advanced circuit analysis program it maybe can calculate how steeply some quantity depends on the values of the components.
You connect a current source to the terminals terminals for which you want the Rth. Then you simply let the program calculate how steeply the voltage between the terminals depends on the current. That's dV/dI and it is directly the wanted Rth
You can also insert an AC current source and calculate with an custom expression Vpp/Ipp if that's available.
The third possibility is to simulate at the same time your circuit and a device which measures the Rth.


How can I get one villager to plant both carrots and wheat?

Question: I am setting up an auto farm using villagers i only want one villager that will plant wheat and carrots.
Answer: What you could do is constantly replace the existing wheat planting villager with another one which plants carrots with the <code>/execute</code> command:
Villager #1 is "Rudolf", #2 is "Jelinek":
<code>/execute @e[name=Rudolf] ~ ~ ~ summon Villager#2 ~ ~ ~
</code>
Connected to a comparator:
<code>/kill @e[name=Rudolf]
</code>
A few seconds later:
<code>/execute @e[name=Jelinek] ~ ~ ~ summon Villager#1 ~ ~ ~
</code>
Then (comparator):
<code>/kill @e[name=Jelinek]
</code>
Comment: I know how you chose that names.
Comment: Villagers don't drop items in their inventory when they die, making this method incredibly lossy. Also, you are spawning them with empty inventories, so they'll just go and start planting whatever they find. Assuming you actually manage to spawn a Farmer villager, which is a 1 in 4 chance with your command.
Comment: Forget the last part, I just noticed that any brown-robed villager can farm.


"The following are equivalent" for only two statements

Question: I often see "The following are equivalent" in theorems that proceed to only have two statements, (a) and (b) be equivalent to each other.
When is this appropriate to do rather than say "if and only if"?
Comment: I struggled to find a tag for this since it's not subject area specific.
Answer: I can think of a couple cases:

The sentence would be too long or complicated to parse if you wrote "[condition] if and only if [condition]"
You want to explicitly label the two conditions (a) and (b) so you can reference them in the proof.
Comment: +1. Considerations of layout and/or convenience within the proof *or within a later proof* would make one prefer this presentation. It looks and reads better to refer to "(b) of Lemma 3" than to say "the righthand side of Lemma 3" or "RHS of Lemma 3". All that said, yes sometimes it looks a little funny to read "the following are equivalent" only to find that what follows are just two propositions.


iATs in ESR version 5.21.3 for Joomla

Question: iATs in ESR version 5.21.3 for Joomla
Does the latest ESR CiviCRM 5.21.3 for Joomla support the latest iATs 1.7.2 for Joomla?
Thank you!
Jamie
Answer: The iATS extension is not CMS specific. If you're running into issues you can post in the issue queue: https://github.com/iATSPayments/com.iatspayments.civicrm
and we can try help you out there.

iATs in ESR version 5.21.3 for Joomla


Protecting RDP connections, full remote control

Question: In my workplace people are connecting with their PCs (with Windows on them) through basic RDP when they work from home. The only precaution taken is changing default 3389 port to a diffrent one and using strong password. This seems like a bad idea. There is no option to configure simple VPN to gain access to files because employees need to remotely use software that utilizes physical HASP keys- avaliable only on their computers. What is the correct approach in this situation?
Answer: Yes, RDP per se isn't secure enough to use over the Internet.
There is no option to configure simple VPN - why not? You should definitely use VPN to secure RDP access: set up a central VPN gateway, VPN clients and remove the port forwarding mappings from your NAT router.
Product recommendations are off-topic here however, but you could try on Software Recommendations.
Comment: I didn't think of that. Setting up VPN and THEN using RDP with local addressing makes sense. By central VPN gateway you mean configuring it through local server with Windows 2019 Server and adding Remote Access -> Direct Access and VPN (RAS) role or software like OpenVPN? Or something completely else and I'm mixing stuff up?
Comment: Yes, you can install a gateway on one of your servers (less recommended), on a dedicated server, or use a hardware appliance - most business-grade routers have VPN functionality.
Comment: everything is clear now, thank you very much for help
Answer: Changing the RDP port is security through obscurity, and not really viable when there are only 65535 TCP ports to scan.
Using a VPN and then hopping through that to connect over RDP is pretty standard. As mentioned, you can often set this up on a enterprise, or even SMB, router.

However, another solution is to use a Remote Desktop Gateway server. It uses a special protocol which essentially acts as an HTTPS tunnel/proxy (with a secured UDP performance protocol also). It is supported by nearly all RDP clients I know of. Although primarily designed with a VDI solution in mind, it can also be used very easily for normal workstations.
There are a number of different providers for this, you may want to go to Software Recommendations for different options.
The protocol allows complex policies as to when to allow logons, for how long, which PCs, what device redirection, etc. Not all provider support all of these.
The benefit of this over a VPN is that you have far more control over what is going once a user has connected to your network, and they never directly route their device onto your network, so you are far less vulnerable to anything they have on their private devices.
Comment: We really *don't recommend any products here* to avoid advocacy and spam. Also, it very much standard to control your users' VPN connections so that they can't do what they shouldn't.
Comment: VPN has far less control over it, as mentioned. Sorry wasn't aware this was "product recommendation" as it's a standard Microsoft RDP feature
Comment: @Zac67 Is it OK if I mention RDG servers without mentioning a specific supplier? As there are other companies that do it
Comment: Yes, that's fine as long as there are several actual products covering that. :-)
Comment: Yes Parallels RAS supports it


What does "Shahdaroba" mean?

Question: Asking about the title of Roy Orbison's 1963 song "Shahdaroba." It seems to have some tenuous Middle Eastern derivation (the song begins "Where the Nile flows...").
You might be familiar with this song from the season three finale of "Mad Men."
Answer: The closest literal Arabic translation might use two words "jahad' and 'aroba', however the word shahdaroba means the future is better than the past.
Comment: Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer).

What does "Shahdaroba" mean?


What is the difference between a Nagios plugin and a Nagios local check?

Question: I see both terms used, local check and plugin, and to me it seems that they both accomplish the same thing, they extend Nagios to perform other checks. Is there any difference between them? If I want to implement a custom check should I write a plugin or a local check?
Comment: I've not heard/seen "local check" in 10 years of using Nagios. If you want to write a plugin, first search to see if someone else has already written it. Often, it's been done.
Comment: what do you have in mind exactly? Some checks can be executed from the nagios server directly, others are executed by the remote (monitored) hosts and their results are sent back to the nagios server (using nrpe, the nagios remote executor protocol). Yet other checks are passive and are sent to the nagios server only if something happens (using ncsa, for instance). So it all depends on what you require. I have not used nagios core in a long time, but it used to have quite thorough documentation
Answer: A local check is done by a plugin. A remote check is also done by a plugin, mostly over NRPE.
Here http://sites.box293.com/nagios/guides/nrpe/installing-nrpe-client-agent/unix-linux can you find some documentation about how to install and use NRPE agents on both Linux and Windows.
if you want to implement a custom check, you need to write a plugin, that you can use locally by just executing the plugin or remotely by executing it over NRPE from the Nagios server with check_nrpe.


Just realized I have msvc++ 2008 redistributable package installed.Why and when?

Question: In my windows xp, why suddenly I have msvc++ 2008 redistributable package installed?

THe installation date is the same as my qt sdk and virtualbox. Is it possible
because of either ? Or anything else?
Comment: A lot of stuff requires the MSVC++ 2008 redistributable. That's why it's redistributable :)
Answer: From the download page:

The Microsoft Visual C++ 2008 SP1
  Redistributable Package (x86) installs
  runtime components of Visual C++
  Libraries required to run applications
  developed with Visual C++ SP1 on a
  computer that does not have Visual C++
  2008 SP1 installed.
This package installs runtime
  components of C Runtime (CRT),
  Standard C++, ATL, MFC, OpenMP and
  MSDIA libraries. For libraries that
  support side-by-side deployment model
  (CRT, SCL, ATL, MFC, OpenMP) they are
  installed into the native assembly
  cache, also called WinSxS folder, on
  versions of Windows operating system
  that support side-by-side assemblies.

Since VirtualBox requires Visual Studio 2003 or 2005 for the build instructions, I'm assuming they are from VirtualBox.
Comment: Since is build using VS , its safe to guess that the redistributable came from the installer of Virtual Box
Answer: Qt sdk doesnot require Visual C++ 2008 redistributable.
It is required for "applications" developed with Visual C++ SP1, to run on a computer that does not have Visual C++ 2008 SP1 installed.
So usually when an application developed with VS is deployed ,they bundle redistributable with the installer.
So my answer would be Virtual Box
Answer: MSVC++ is the Visual C++ 2008 redistributable, and my guess is that it was installed with either the Qt SDK or VirtualBox.


Gimp selection vanished

Question: I have been using GIMP for many years and suddenly the selection outline - dashed line has stopped working.
it does make the selection and I can cut away the invisible selection but I cannot see it.
I toggled it in the view menu and under preferences... nothing.
Also if I convert the selection to a path and try and stroke it, nothing appears
Comment: [Check preferences](https://imgur.com/a/v0QPjRI), reset if necessary. Last resort might be a totally clean reinstall of GIMP. Other than that, tech support is generally off-topic here. Sorry about that.  Might depend on your setup/OS/version/maybe a corrupt installation, who knows!
Answer: If you are on OSX Big Sur, this is a known problem.
You can check your selection with the QuickMask or the Selection editor.
Not that when you do Select ➤ To path and the Edit ➤ Stroke path only one half of the path is drawn since the other half/side lies outside the selection. If the path is thin (1px) there is not much left.

Gimp selection vanished


How do I track down a leak?

Question: During rain, you can feel a small drip on your feet on the passenger side of my 97 Subaru Legacy. How do I find the source of the leak?
Answer: Get a friend to spray water on the windshield and surrounding areas while you are inside the car doors closed with a flashlight looking under the dash. Don't spray the water forcibly at the windshield try to make it like a rain shower. You can make a simple stand out of pump pipe holding a shower head to do the same thing if you don't have an assistant.
Comment: Also note traces that water left from previous times it leaked. Usually water could be from ventilation or if your windscreen frame has rusted under the window sealing.

How do I track down a leak?


Recommended time to show an interstitial before it closes itself?

Question: What would be an optimal amount of time to show an interstitial before it closes automatically? Bearing in mind both the information is succesfully conveyed and the frustration of the user is minimized.
Comment: Can you give us a specific example of the context where you're showing an interestitial message? If you can post a screenshot and/or the text of the message itself, that would be ideal. (There might be good general-purpose guidelines, but I'm hoping to head off answers that start "It depends..." and rhyme with "tl;dr." ;-))
Comment: .2 - .8 seconds :)
Comment: I assume whether or not the interstitial should time out at all isn't something to be considered?  For example, if the message is "you are leaving xyz.com" then you may want to wait until the user gives the manual OK, especially if secure data is being transferred.
Comment: @Evan thanks for the insight. We already ruled that out, but it is something to bear in mind.
Answer: As shorter time as it takes for the information you're displaying on the page to be consumed - an image with a simple message? 5 seconds. Two paragraphs? 3 minutes.
A very subjective question, which only you can answer.


What is smartcast?

Question:
Possible Duplicate:
Smartly using smart casting

when I browse to League of Legends forums I see a lot of guys playing with "Smartcast". What is this? Can someone explain me this and how can I use it?
Thanks!!
Max
Answer: Source (League of Legends wiki)

Smart cast automatically casts the selected ability at (or towards)
  the current mouse cursor position as if you had first pressed the
  ability button and then left-clicked at the target position. Smart
  cast works for self-buff abilities, targeted abilities,
  ground-targeted abilities and skillshots. Smart casting a support buff
  ability (an ability that can be cast on self e.g. a shield or a heal)
  when the cursor is on an invalid target will self-cast the ability
  instead. Note that you can use self-casting to self-cast support buff
  abilities regardless of cursor location. Using smart cast can be
  invaluable because it reduces the time delay between activating and
  casting by cutting the user input in half; activate vs activate and
  click.   Remember that smart casting means you don't get the targeting
  graphic, which can make it harder to accurately aim skillshots. They
  will fire instantly, instead of showing the skillshot for fine tuning
  the shot. However, there is an option to turn range indicators on,
  which will show the targeting graphic while the ability key is
  depressed. This can also be helpful because the ability can then be
  canceled by right-clicking.

Long story short, abilities that normally would require to press the shortcut button (Q,W,E,R) is launched immediatly, without the display of targeting graphics (skillshot arrows or range indicators).
You can easily set all abilities to smartcast by going to the keybindings menu and looking up options such as "Smartcast ability 1, ability 2 etc." and switching them to your normal ability keys - Q,W,E,R.
Some examples are:

Morgana's dark binding gives an aiming arrow, so it's not a smartcast
Urgot's Acid Hunter launches the projectile directly at your cursor
as soon as you press "Q", and is a built in smartcast.
Karthus' Lay Waste places a delayed blast at your cursor without any mouse clicks or indicators, and is thus a smartcast.

*Note: After some not-too-old patch, you can see the aim-helpers on (manually set) smartcast abilities while you are holding down the ability key.
Answer: smartcasted skills are used right away the moment you press the skill key without the need to click the mouse additionally
you can use it either with shift+skillkey or change the key in the key bindings
Answer: Smart cast allows your champion to use a spell just by clicking on the skill button.
Whomever your mouse is highlighting the spell will be cast on.
Where ever your mouse is pointing your skill will be cast on that spot.
Skill shots will go in the direction of your mouse.
Note* If you want self heal spells to cast on yourself with smart casting, you need to bind your keys to Smart Cast + Self Cast

What is smartcast?


Is it possible to include C++ libraries in C programs?

Question: I'm working with a contractor who develops a library for us in C++. I would like to know if it is possible to use that library in a C program.
I am using Gcc as my compiler.
Comment: You need to write some wrapper in `C++` that exposes a `C` interface using `extern "C"`. So no, not directly, but yes, it is possible, in some limited way.
Comment: @BoBTFish that + compiling main with g++
Comment: Alternatively, upgrade to C++ as your main language. Most C code will work just fine, and the world will be a better place.
Comment: @BЈовић yes, it is obviously problematic to *compile* C++ object files into a C program. But you can link to a (dynamic) C++ library just fine, provided it exposes a C interface
Comment: @BЈовић what, why? Why would that be necessary if you're just linking to another library which exposes an interface declared with `extern "C"`?
Comment: @jalf For example this : http://stackoverflow.com/a/329195/476681
Comment: @jalf See also this : http://stackoverflow.com/q/7397302/476681
Answer: Yes, it is possible. However, as BoBTFish says in a comment above, you (or the contractor) must design a C interface for the C++ library:

write a header file that compiles in both C and C++, and that declares some extern "C" functions. The interfaces of these functions must be valid in C, which in C++ terms means they use only POD types (for example no references) and don't throw exceptions. You can declare non-POD C++ classes as incomplete types and use pointers to them, so commonly each non-static member function is wrapped by a function that takes the pointer that will become this as its first parameter.
implement the functions in C++ to call the C++ library
compile the library and the wrapper as C++
compile your program as C (you can #include the header wherever needed)
link it all together with g++ so that the C++ components can link against libstdc++.

I suppose you might argue that since the program is linked with g++, it's by definition a C++ program that uses a C library (that happens to contain main) rather than a C program that uses a C++ library. Personally I wouldn't bother arguing that, the important point is that none of your existing C code changes.
Example:
lib.h
#ifdef __cplusplus
extern "C"
#endif
int foo();

lib.cpp
#include "lib.h"
#include <vector>
#include <iostream>

int foo() {
    try {
        std::vector<int> v;
        v.push_back(1);
        v.push_back(1);
        std::cout << "C++ seems to exist\n";
        return v.size();
    } catch (...) {
        return -1;
    }
}

main.c
#include "lib.h"
#include <stdio.h>

int main() {
    printf("%d\n", foo());
}

build
g++ lib.cpp -c -olib.o
gcc main.c -c -omain.o
g++ main.o lib.o -omain

The following also works instead of the third line, if you do want to make an arbitrary distinction between using gcc to link and using g++:
gcc main.o lib.o -llibstdc++ -omain

However, I am not certain that gcc -libstdc++ will work as well as g++ for all possible code that could be in lib.cpp. I just tested it for this example, and of course there's a lot of C++ that I haven't used.
Comment: @BЈовић: I've now included a `gcc` command-line that works for my example code. But since the restriction is arbitrary and has nothing to do with the question, I'm not going to research whether it always works or whether there are any cases that need more than just `-llibstdc++`. The man page for `g++` is the same as the man page for `gcc`, and it says that `gcc` is the GNU C and C++ compiler. I don't know who told you otherwise, or what situation you have in mind where it makes sense to avoid `g++`.
Comment: @BЈовић: no, the question is how to use GCC (well, the questioner specifically says "Gcc", so I guess that's neither GCC nor `gcc` but some nomenclature of their own) to link a C++ library into a program written in C. You've invented an artificial restriction. `g++` is part of GCC.
Comment: -1, since it is not possible to link a c++ library using gcc, and you said it is possible to do it. I change my mind if you prove it wrong.
Comment: The last thing: c and c++ are different languages. That means that gcc and g++ have to follow different rules. I am not against g++, but some times  it is not possible to switch from gcc to g++ (big project,or some other weird reason).
Comment: @SteveJessop Worth pointing out in this context, the language in the C++ standard about mixed C and C++ permits (but does not require) an implementation to require `main` to be compiled as C++ if there is any C++ code anywhere in the program.  I cannot remember whether GCC requires this on any current OS.
Comment: @BЈовић: what would you accept as proof? Note that I specified using `g++` to link, which is part of GCC but is not identical in behavior to calling the `gcc` program. I don't remember what argument(s) `gcc` needs in order to make it behave the same as `g++`. IIRC it's the same program but it checks its own `argv[0]`, so it might be there is no set of arguments that makes it *exactly* the same.
Comment: The question is how to link a c++ library using gcc. Your answer tells it is possible, and then you want to use g++. I'd like to see how exactly can I link a c++ library using gcc (and not g++).
Comment: gcc and g++ are different programs. The first is for C, and the second for C++. You know it, so I am not really sure what is not clear. If somebody says they use gcc, I do not assume one of GCC tools. Again, your edit uses g++ to link both libraries (c and c++). So, I'd like to see how it is possible to link a c++ library using gcc. You, BoBTFish, keltar and apparently more people know how, since you said it is possible.
Comment: Oh, I suppose there's the special case where C++ doesn't work on the target platform at all. In that case step 1 and step 3 of my "build script" are both problematic. Clearly you can't use C++ code in a C program (or for that matter in any program) if you don't have a working C++ compiler. If that's the restriction that the questioner is trying to state then it's game over. The library needs to be in a language the target supports, so either rewrite it or else get a C++ compiler working for the target and try again :-)
Comment: @BЈовић: I don't think they follow different rules at link time (the names have been mangled differently, but that happens earlier). `extern "C"` was specifically designed to (a) let you write a header in C++ to bind against a C library, which is the more common use but also (b) let you write, in C++, a library that behaves exactly as a C library.
Comment: @SteveJessop On ELF systems, there is no meaningful difference between the `ld` invocation generated by using `g++` to link, and the `ld` invocation generated by using `gcc` to link, as long as `-lstdc++` is placed after all object files in the latter case.  There may be a meaningful difference on OSes that use less featureful object file formats.
Answer: This little dynamic library (g++) and program (gcc) compiles and links perfectly:
Header library.h
#ifdef __cplusplus
extern "C" {
#endif

typedef struct TagPerson {} Person;
extern Person* person_create(const char* name);
extern void person_destroy(Person* p);
extern const char* person_name(Person* p);
extern Person* person_exception(Person* p);

#ifdef __cplusplus
}
#endif

C++ Source library.cc
compiled with g++ -shared -fpic library.cc -o libLibrary.so
#include <iostream>
#include <string>
#include <stdexcept>
#include "library.h"

namespace Library {

class Person
{
    public:
    Person(const std::string& name)
    :   m_name(name)
    {
        std::cout << m_name << std::endl;
    }

    const std::string name() const { return m_name; }
    void exception() { throw std::runtime_error(""); }

    private:
    std::string m_name;
};

} // namespace N

extern "C" {

#define PERSON(P) ((Library::Person*)(P))

extern Person* person_create(const char* name) {
    try {
        return (Person*)(new Library::Person(name));
    }
    catch(...) {
        // Error Procession;
    }
    return 0;
}

extern void person_destroy(Person* p) {
    delete PERSON(p);
}

extern const char* person_name(Person* p) {
    return PERSON(p)->name().c_str();
}

extern Person* person_exception(Person* p) {
    try {
        PERSON(p)->exception();
    }
    catch(...) {
        std::cerr << "Exception" << std::endl;
    }
    return 0;
}

} // extern "C"

C Source main.c
compiled with gcc main.c  -lLibrary -o Test
#include <stdio.h>
#include "library.h"

int main()
{
    Person* p = person_create("Jaco Pastorius");
    printf("%s\n", person_name(p));
    person_exception(p);
    person_destroy(p);
    return 0;
}

Comment: I must say I am not sure how that works. However, you have an UB. C standard specify that the program execution starts in main, but your program starts before by the initialization of global objects (which you included with iostream).
Comment: @BЈовић Please notice, it is an dynamic library hiding the c++ part.
Answer: No, it is not possible. One thing that is certanly going to miss are exception handling functions. You have to compile the main using c++ compiler.
If you really want to develop in c, and use a c++ library, you can develop a c library, and compile main with g++.

Even if compiling succeeds, linking will fail at the end. See :
Why can't I link a mixed C/C++ static library that has a C interface using gcc?
And it is not only exception functionality missing. There are lots of other things, which can be easily solved by using g++ to link everything.
As I said above, the solution is to call some function from main and link it with g++ :
#include "my_c_main.h"

int main(int argc, char* argv[])
{
  return run_my_c_main( argc, argv );
}

Comment: @SteveJessop I am not. The question is about gcc - not g++. I said OP needs to use g++ if he wants to link c++ libraries. There are no ways around it.
Comment: Well, it would require something like `-lstdc++`, but i wouldn't be so quick with 'not possible' claims (i use it and it works). Although not actually remember, exceptions and RTTI are likely to be disabled in my builds. After all, a lot of libraries are written in C++ but expose interface to external programs via C functions.
Comment: @keltar Feel free to add an answer, as I'd really like to see how exactly you did it. As far as I know, without using g++, it is not possible to link c++ libraries.
Comment: It's entirely possible, it just takes effort.
Comment: @BЈовић second answer already states that, no need to add more. But yes, i use `gcc` to link my C code with ODE and squirrel - both C++ libraries with `extern "C"` interface. And adding `-lstdc++` is enough for me - both with GNU toolchain and with xmingw.
Comment: @BЈовић the OP said nothing about wanting to use a *static* library, did he? If you make up enough additional requirements, then *anything* can become impossible.
Comment: @jalf static or dynamic c++ library - doesn't matter. Did you ask because I linked a question where they tried to link static c++ library?
Comment: @BЈовић I ask because it *does* matter, and because your answer is incorrect.
Answer: What exactly is the issue? Do you already have a delivered library in the "wrong" language or is it that your contractor wants to develop the library in C++ but you need it to link from C?
In the former case, assuming you specified things correctly you should make it your contractor's problem but if you didn't or if that's not possible you'll need to write an interface as Steve Jessop suggests above.
In the latter case, it's really not an issue: the contractor will need to ensure that she provides the code in a form that is callable from C and safe/secure/stable to call in that manner. The internal code that does the work can really be anything at all providing she wraps it up for you in the correct manner. If you're planning on building the library yourself, you will need them to provide suitable build scripts that invoke the compiler in the right manner. I guess there's a potential maintenance issue if your in-house programmers can't cope with C++ but that's an issue to do with recruitment/employment not the technical details of how it works.


unable to connect mobile broadband ubuntu 12.10

Question: i recently installed ubuntu 12.10 on my desktop. now the mobile connection was not working, which i later found out to be a bug in modem manger so i downgraded it to v0.5.2 but still the problem persists. whenever i try connecting, the mobile broadband option gets automatically disabled.
i have a bsnl EVDO connection, which i had to manually configure as the device was not automatically detected at first.
Answer: first be sure to have all info about your contract with provider, than click on network button on top of the screen, and select : edit connections.
when that window is opened select: mobile broadband.
next click on add.
then select your device or select any if not on list.
select your country, provider and contract type in next steps, than just create. also check on that network menu (after clicking on network button on top of screen) that:
first- networking is enabled (checked)
also- mobilebroadband is enabled (checked)
after creating, unplug and plug device back in, after few seconds, click network button, and click on that created network when you see it on the list. if not work this, leave me comment i will see what could be.
Comment: thnx, for the response. i configured my connection the same way, but that is working :(
Comment: did you get connection now?
Comment: currently m using my connection on windows. as of ubuntu, it is not working even after the restart..


IBMMQDotnetClient deat letter queue .net6

Question: I had a problem in implementation of dead letter queue in IBM MQ in .net6.
I am using IBMMQDotnetClient library from nuGet. The problem is that when we face to any message which is not successfully commited, the message from queue continues in while(true).
I want to get the message to dead letter queue and continue to next messages from the queue.
how can I use dead letter queue for this issue in .net6 project ?
Comment: If I remember correctly, you have to handle poison messages on your on in plain MQ .NET API. I highly recommend to use the MQ .NET **XMS** API, which handles poison messages out of the box if the queue is configured correctly, see [Poison messages in XMS](https://www.ibm.com/docs/en/ibm-mq/9.3?topic=consumers-poison-messages-in-xms).
Comment: do you have an example of code for you claim ? can you share here ?
Comment: Follow the link to the IBM MQ documentation from my first comment. In the IBM MQ XMS documentation chapters you find more example code.
Answer: When you use XMS you get the IBM MQ XMS library handling of backout threshold and backout.
See https://www.ibm.com/docs/en/ibm-mq/latest?topic=consumers-poison-messages-in-xms
You need to set BOTHRESH and BOQUEUE for your queue. This will be an MQ admin job. Then when read attempts for any message exceed the threshold the message is requeued to the backout queue. If the requeuing fails for any reason, the message is removed from the input queue and either requeued to the dead-letter queue, or discarded.
The only code change needed is to signal when a message can't be processed. You will need to transaction enable the session.
sessionWMQ = connectionWMQ.CreateSession(true, AcknowledgeMode.SessionTransacted);

commit good messages
sessionWMQ.Commit();

rollback (and signal a read failure) bad messages
sessionWMQ.Rollback();

To get you started there is a set of XMS samples that don't have transactions enabled at https://github.com/ibm-messaging/mq-dev-patterns/tree/master/dotnet
Comment: Thank you a lot, I am evaluating the codes in the link. as soon as I come to a solution with this I will resolve the issue putting a tick by the name of you.


Tag rename request: [roller-coaster-xxx] -> [rollercoaster-xxx]

Question: The official name is RollerCoaster Tycoon X. See here, Wikipedia, Steam, iOS. You name it. There is no space between Roller and Coaster.
Answer: I've created tags with the correct spelling and merged them with the old tags as synonyms, so that they will be correct from now on, along with being corrected on any existing questions, for all versions of Rollercoaster Tycoon.
Answer: Did a quick look up of the the tag roller-coaster-tycoon and got the following feedback:

It appears there have been a few questions tagged using 'roller-coaster' as opposed to 'rollercoaster'. While "roller-coaster" still comes up as the suggested tag if you type "rollercoaster" into the tag field, I would suggest "rollercoaster-tycoon" as the main tag, with "roller-coaster-tycoon" as a synonym.
What ever decision should be applied to all 4 tags, to keep uniformity.


Can you save fingerprint from fingerprint sensor usually found in laptops and smartphone?

Question: Is it possible to save a jpg of fingerprint, right now fingerprint sensors found in laptops and mobiles are used to unlock them.
Comment: Biometric fingerprint sensors don't work based of a direct image of your fingerprint.  How and what happens differ from OS to OS.
Comment: Computers never store passwords. You store a one way mathematical transformation called a hash. When you enter a password it is hashed and compared to the stored hash. When you read in the paper that 1 million passwords have been stolen be aware it is roughly 2 million years to crack them all (two years per password).
Comment: i dont think i said to extract stored data and reproduce a finger print. Instead. get data from the sensor, raw data and print it.
Answer:
You will not be able to see your fingerprint since the fingerprint
  that you add will be stored only in the backend. It is used to compare
  with the stored fingerprint when you try to unlock with fingerprint.
And moreover fingerprint will not be stored as image format. During
  unlocking your fingerprint image sent for extraction in the IC chip.
The extraction takes place by image processing, and extracted details
  are stored as templates.
So the template of your default fingerprint is compared with the
  fingerprint that you give during unlocking. If matched, your screen is
  unlocked.
Templates are not even part of the OS, so its impossible to retrieve
  the fingerprint image. Templates will be stored only in ICs.

So basically you can't export your fingerprint as picture. In high-end devices, fingerprint data will be encrypted and can't be exported.
Source: Quora.com
Comment: To add, patterns are almost always the ones stored even in an insecure system as otherwise matching fingerprints when you have ever-so-slightly dirty fingers, dirty sensor, or even aligning it a different angle will not produce a match. While insecure system's you could extract the pattern, it wouldn't be useful to you as it wouldn't be in the image format. Some fingerprint scanners (NOT like smartphone or laptop ones) work *optically* and can produce a picture of the print if requested in software.
Comment: I didn't say to extract finger prints from stored and encrypted data / templates. But instead directly from the sensors.
Comment: In PC, tablet or smartphone, fingerprint sensor is just work as a scanner. The data won't be stored in there.
Comment: So can you use the scanner to get the fingerprint, it doesn't matter if it gets stored or not?


Amazon links in Amazon app

Question: Is it possible to configure Amazon app so that all the amazon.co.uk links open in the App (or at least ask if I prefer the browser or the app)?
Answer: It's up to the app to register an intent filter for URLs it can understand. When the app does this, and you click an appropriate link, the chooser asks you which you want to open.
If you've previously had a chooser for Amazon links, and accidentally selected to always use a web browser, you can undo this by going into the device Settings, then Apps. Select the browser from the list, and then click Clear defaults.
If you've never had a chooser for Amazon links, then the app can't respond to them. It's possible to use a third-party app to act as an intermediary, so that you open the Amazon links in that app, and it forwards them to the Amazon app, but if the Amazon app doesn't understand the URL you're using, the results are unpredictable: it might crash, or simply open to the main screen. You'll have to contact the developer through their official support channels to ask them to add this feature.
Comment: I am not sure if I ever had the choice. Is there a way to check it without removing all the other settings?
Comment: Not easily. An "package explorer" app such as Stanley can export an app's manifest so you can find all of its intent filters, but you need to understand the format to interpret it.
Answer: There is no way to force open URLs through an app if it doesn't show up in the popup menu to choose an app. AFAIK there is a filter in applications called the intent filter that is hard coded into the applications code by the developer. The filter is triggered when certain URLs are pressed.
If Amazon hasn't done this you cannot get it to open amazon.co.uk URLs without manually  adding it to the apps code.

Amazon links in Amazon app


Using port 80 for non http

Question: Is it possible to use port 80 for non http traffic ? For example I'm making a small script that will communicate with a friends computer through the internet, however they must port forward it to get past the router. Is there a problem with using port 80 in the script so it will be let through automatically ? Is there some part of this i don't understand that will not let non http data through ? Please explain :)
Answer: there is no problem doing that. in fact, skype's default behaviour is to use port 80 and port 443 to transport voice!
Answer: There are a lot of ISPs that actually block port 80, so you might want to try a different port if you are having a problem (still needs to be forwarded)
The firewall on the computer also needs to be set to allow the incoming traffic.
Answer: This will work fine, but your friend may still need to setup port forwarding
If your friend's PC is the one listening on Port 80, he will need to setup port forwarding.  Otherwise, how would the router/NAT know which computer in the house to bridge the connection to?
But if your friend's PC is the one making the outbound connection, then likely no port forwarding is needed at all on his end.
In other words, port forwarding (for TCP) is only for inbound connections.  The router/NAT will automatically setup a port mapping scheme for outbound connections (as it does it with all web traffic).

Using port 80 for non http


How to construct a model to predict the value of a time series $y_t$ that depends from other time series $\bar{X}_t$?

Question: I would like to know what are the standard approach to construct a model to predict the value of a time series $y_t$ that depends from other time series $\bar{X}_t$. I use to see around that for this kind of task there is a large amount of models but all autoregressive in a way.
I'm thinking about, for example VAR, SARIMAX, RNN, LSTM.
I'm looking for a model, or at least an approach, where there is no my lagged target variable as predictors. Does anyone has some references ?
Answer: A time series forecast model based upon lagged variables of that time series is commonly called auto-correlation. A time series forecast model based upon other series is called cross-correlation in the time-series literature. A general forecast that uses any number of lagged time series (including the lagged series itself) is called vector auto regression.
Any of the other ML and AI approaches can use non-linear methods to achieve the modelling and draw from an infinite amount of factors other than lagged time series. In finance, it's common to use factor based investing, for example (like fundamental value data). In Machine Learning, we are interested in finding those features (feature selection) that best model the time series outcome.


What are the differences between search problems, optimization problems, and decision problems?

Question: How do we differentiate these classes of problems?
Comment: We expect you to do some basic research before asking a question here. Even looking up the definitions of those classes will tell you what the differences between them are.
Answer: A decision problem has this form:

Input: $x$
Output: "Yes" if $\phi(x)$ holds, "No" otherwise

A search problem has this form:

Input $x$
Output: $y$ such that $\psi(x,y)$ holds, if such a $y$ exists. "No" otherwise.

Finally, an optimization problem has this form:

Input $x$
Output: $y$ such that $f(x,y)$ is the minimum possible, i.e. $f(x,y) = \min_{y'} f(x,y')$

Here $\phi$ and $\psi$ are some boolean properties, and $f$ is some natural number function of $x$ and $y$.
Answer: In a search problem you are looking for something.
In an optimization problem you want to find the best way to do something.
In a decision problem you are trying to decide whether something is true.
I suspect the reason you asked this question is that optimization or decision problems might be implementable in terms of a search problem. For example, if you are trying to decide whether a graph has some property, you might have to traverse (search) it.
Answer: Decision problem
Input is a question where the output is yes or no. Output is yes or no from the algorithm.
Search problem
This problem usually has several parts: Building a corpus, doing inserts and doing lookups. A common problem is to organize the data so that lookups can be done fast.
Optimization problem
Provided a constraint, for example x + y < 10, optimize some formula for example x*y and find its maximum or minimum value.
Comment: This answer conflates "search problems" with a specific problem in "information retrieval."   Search is a far more general concept (for example, when we ask a robot to navigate to a particular part of the room, or to solve a jigsaw puzzle, we are posing a search problem).


Passing a class object as an argument in C++

Question: Suppose I had a class named foo containing mostly data and class bar that's used to display the data. So if I have object instance of foo named foobar, how would I pass it into bar::display()? Something like void bar::display(foobar &test)?
Answer: Yes, almost. Or, if possible, use a const reference to signal that the method is not going to modify the object passed as an argument.
<code>class A;

class B
{
    // ...
    void some_method(const A& obj)
    {
        obj.do_something();
    }
    // ...
};
</code>
Answer: <code>#include <iostream>

class Foo
{
    int m_a[2];

    public:
    Foo(int a=10, int b=20) ;
    void accessFooData() const;

};

Foo::Foo( int a, int b )
{
    m_a[0] = a;
    m_a[1] = b;
}

void Foo::accessFooData() const
{
    std::cout << "\n Foo Data:\t" << m_a[0] << "\t" << m_a[1] << std::endl;
}

class Bar
{
    public:
    Bar( const Foo& obj );
};

Bar::Bar( const Foo& obj )
{
    obj.accessFooData();
   // i ) Since you are receiving a const reference, you can access only const member functions of obj.
   // ii) Just having an obj instance, doesn't mean you have access to everything from here i.e., in this scope. It depends on the access specifiers. For example, m_a array cannot be accessed here since it is private.
}

int main( void )
{
    Foo objOne;
    Bar objTwo( objOne ) ;
    return 0 ;
}
</code>
Hope this helps.
Answer: so there are two way of passing class object(it is what you are asking) as a function argument
i) Either pass the copy of object to the function, in this way if there is any change done by the function in the object will not be reflected in the original object
ii) Pass the base address of the object as a argument to the function.In thsi method if there are any changes done in the  object by the calling function, they will be reflected in the orignal object too.
for example have a look at this link, it clearly demonstrate the usage of pass by value and pass by reference is clearly demonstrated in Jim Brissom answer.


Dealing with Dates of Birth in Predictor

Question: I have a predictor variable of type factor which contains the date of birth.
From your experience (when dealing with logistic regression), what is the best way of treating date of birth (or similar types)?
As a continuos variable or maybe or maybe as a categorical variable which stores different age segments?
Comment: Date of birth is intrinsically important for calculating what is allowed or expected in society (can you drive a car legally, do you qualify for a pension?), so for such purposes it should remain human-readable. Often date of birth is important in giving age, for which the needed precision may mean hours or days (for new-borns) or the allowed precision may just be years (for older people). Either way, converting date of birth to number of days or years since time origin seems most usual for statistical analysis.
Comment: @NickCox It is slightly paradoxical but your examples would seem to argue *against* using number of days since time origin, e.g. you are either of driving age or you are not, this is intrinsically binary.
Comment: No paradox. I am distinguishing (a) social and (b) statistical purposes for which (a) human-readable dates such as "7 May 2013" are needed and (b) fully quantitative dates are needed, e.g. if 1 Jan 1960 = 0, then 7 May 2013 = 19485.  Sorry that was not clear to you.
Answer: Depends on what you're trying to model. In general you're losing information by binning a continuous predictor, but there are situations where it makes sense, e.g. as a proxy for 'minor' vs 'of legal age' or "of working age" vs "retired".  It can sometimes also be a useful way to informally check the predictor's relation to the response in logistic regression.  And if you have plenty of degrees of freedom to spare, & are lazy, it saves you checking the nature of the relation to the response.


How to remove all cell formatting

Question: How can all formatting be removed from a sheet in Numbers so each cell only contains the text, with links no longer clickable?
Comment: have you tried exporting to CSV and then importing it right back in? CSV is *text only*
Comment: The exported CSV is correctly formatted. This is about using Numbers with some enhancements disabled.
Answer: If you just want to remove hyperlinks, this post (the first result of this Google search) should help. Summarized below:

Select all cells using ⌘+A (or Edit -> Select All)
Copy cells using ⌘+C ( or Edit -> Copy)
Paste and Match Style using ⌘+⌥+ ⇧ +V (or Edit -> Paste and Match Style)

This will remove all hyperlinks, however it will keep formatting like Bold, Italics, etc. If you want all formatting to be gone, use the suggestion from Steve Chambers to export to CSV and import from CSV, as the CSV Format is just plain text and doesn't save any formatting.

File -> Export to -> CSV...
Select the CSV you just exported in Finder and right click -> Open With -> Numbers

This will completely open a new Numbers document without formatting, unless you have Numbers set to automatically detect hyperlinks. If you do not want hyperlinks to be detected:

Open Numbers preferences using ⌘+, (or Numbers -> Preferences...)
Go to the Auto-Correction tab and uncheck "Automatically detect links" under the Formatting section
Comment: I've got the Autodetect link off, but it still converts them, and adds header styling, on import from CSV. It may be that email addresses are treated differently than URLs. Could a blank template be set as the default?
Comment: The link removal process does work.
Comment: The CSV option will remove the formulas, if any, in addition to formatting.

How to remove all cell formatting


Let $A\in M_n(\Bbb{C})$ such that $\text{Im}(A)\cap\text{Ker}(A)=\theta$

Question: The actual question looks like-
Let $A\in M_n(\Bbb{C})$ such that
$\text{Im}(A)\cap
 \text{Ker}(A)=\{\theta\}$, where $\text{Im}(A)=\{AX
\mid X\in\Bbb{C^n}\}$ and $\text{Ker}(A)=\{X\in\Bbb{C}^n\mid AX=\theta$}, then prove that there exists non-singular matrices $P$ and $D$ of orders $n\times n$ and $\text{rank}(A)\times\text{rank}(A)$ respectively such that $$ A=P
 \begin{pmatrix} D & 0 \\ 0 & 0 \\ \end{pmatrix} P^{-1} $$
Can anybody suggest me a proper solution to that question?
Thanks for assistance in advance.
Answer: You can consider a basis of $\mathbb{C}^n$ using the decomposition $\mathbb{C}^n = Im(A) \oplus Ker(A)$.


Applications in Ubuntu

Question: I am using Internet on a 3G prepaid Sim using data device ZTE MF190.I want to know about some applications can be used in my Desktop for making calls and sending and receiving text SMS using my Desktop only in Ubuntu 14.04 or Ubuntu 16.04.How can I do it in a easy way?
Comment: This might have what you're looking for http://askubuntu.com/questions/145772/desktop-sms-client-in-ubuntu
Answer: If you want to send/receive sms using your prepaid number via Broadband Modem in Ubuntu, there is modem-manager-gui application available.
We can install modem-manager-gui using ubuntu software manager or via command line using :
sudo apt install modem-manager-gui
modem manager gui
Limitation :

This application work with my edge/umts/hspa modem, but doesn't work
with my cdma/evdo modem.
No 'call' menu.

Summary from their website :
Modem Manager GUI is frontend for ModemManager daemon able to control specific modem functions.
Main features:

GTK3 interface
Send and receive SMS messages with messages concatenation.
Send USSD request and receive answer in system encoding.
Get modem and SIM information (Device info, Operator name, Mode, IMEI, IMSI/ESN, Signal level)
Scan available mobile networks
Control data transmission process and set session traffic and time limits

Applications in Ubuntu


Prefab won't change to custom shader

Question: I am writing here as I have encountered a problem with Unity. I have written my own surface shader and want to use it for a prefab. However, when I drag and drop the shader to the prefab in the editor, it recognizes it but it doesn't change the prefab. The prefab is a prefab for some objects which stays pink. What's the problem? The shader works, and I know that as I have tried to drag and drop the shader directly to some of the objects. In addition to that, I have also tried to create a material an drag and drop the shader that and then drag and drop the material to the prefab. That didn't work either.
Comment: Shader, Material, and Texture are different things.
Answer: Make sure the game isn't running and drag your prefab into a scene and select it in the Hierarchy.  There should be details in the Inspector that will allow you to apply your shader.
First, find the part of the prefab that contains a renderer (probably a MeshRenderer).  Under that component, there will be a "Materials" list which should have a size you can adjust and then elements to select the materials you'd like.
When your materials are set, there will be drop-down menus to select which shaders those materials are using; this is where you select the shader you want.
Finally, as with any adjustments to prefabs, you must click the "Apply" button in the upper right on the Inspector.  If you make changes while the game is running or without clicking "Apply", the changes will not be saved to the prefab.

Prefab won't change to custom shader


GRIB1 to CSV on linux

Question: Is there any easy way to convert GRIB1 files to CSV in Linux? I've seen that supposedly GRIB2 can readily be converted to CSV, and I've tried to convert the Grib1 files to Grib2 using grib1to2 but its a nightmare as the documentation and software is no good. Is there any other way to get a CSV or any other easily readable format out of GRIB1?
Answer: There is probably a cleaner approach, but the following should work for you under Linux. Using CDO (Climate Data Operators), you could convert your GRIB file to NetCDF:
cdo -f nc copy input.grb2 output.nc

You could then convert your NetCDF to plain text using ncdump, e.g.:
ncdump output.nc

You will probably want to review some examples about ncdump to ensure that you export the parts (and region) of the NetCDF file that you want.
You can install the relevant packages on linux (e.g. Ubuntu as follows)
sudo apt-get install cdo nco netcdf-bin

Comment: Thank you. However I get this error:

`Error (operatorInqModID) : operator missing! input.grib is a file on disk!`
Comment: insert `copy` in cdo (see update above)

GRIB1 to CSV on linux


Calling a method in an ASP.NET application from a Windows application

Question: Other than using a web service, is there anyway to call a method in a web app from a windows application? Both run on the same machine.
I basically want to schedule a job to run a windows app which updates some file (for a bayesian spam filter), then I want to notify the web app to reload that file.
I know this can be done in other ways but I'm curious to know whether it's possible anyway.
Answer: You can make your windows app connect to the web app and do a GET in a page that responds by reloading your file, I don't think it is strictly necessary to use a web service. This way you can also make it happen from a web browser.
Answer: A Web Service is the "right" way if you want them to communicate directly.  However, I've found it easier in some situations to coordinate via database records.  For example, my web app has bulk email capability.  To make it work, the web app just leaves a database record behind specifying the email to be sent.  The WinApp scans periodically for these records and, when it finds one with an "unprocessed" status, it takes the appropriate action.  This works like a charm for me in a very high volume environment.
You cannot quite do this in the other direction only because web apps don't generally sit around in a timing loop (there are ways around this but they aren't worth the effort). Thus, you'll require some type of initiating action to let the web app know when to reload the file.  To do this, you could use the following code to do a GET on a page:
<code>WebRequest wrContent = WebRequest.Create("http://www.yourUrl.com/yourpage.aspx");
Stream objStream = wrContent.GetResponse().GetResponseStream();
// I don't think you'll need the stream Reader but I include it for completeness
StreamReader objStreamReader = new StreamReader(objStream);
</code>
You'll then reload the file in the PageLoad method whenever this page is opened.
Answer: How is the web application loading the file? If you were using a dependency on the Cache object, then simply updating the file will invalidate the Cache entry, causing your code to reload that entry when it is found to be null (or based on the "invalidated" event).
Otherwise, I don't know how you would notify the application to update the file.
Comment: I have no idea why certain downvotes happen. In this case, I can only guess someone didn't like "otherwise, I don't know how".
Answer: An ASP.NET application only exists as an instance to serve a request. This is why web services are an easy way to handle this - the application has been instantiated to serve the service request. If you could be sure the instance existed and got a handle to it, you could use remoting. But without having a concrete handle to an instance of the application, you can't invoke the method directly.
There's plenty of other ways to communicate. You could use a database or some other kind of list which both applications poll and update periodically. There are plenty of asynchronous MQ solutions out there.
Answer: So you'll create a page in your webapp specifically for this purpose. Use a Get request and pass in a url parameter. Then in the page_load event check for this paremter. if it exists then do your processing. By passing in the parameter you'll prevent accidental page loads that will cause the file to be uploaded and processed when you don't want it to be.
From the windows app make the url Get request by using the .Net HttpWebRequest. Example here: http://www.codeproject.com/KB/webservices/HttpWebRequest_Response.aspx


Intuitive meaning of Double Commutant Theorem

Question: Is there any intuitive explanation of the Double Commutant Theorem for Von Neumann Algebras? By intuitive I mean in terms of Quantum Mechanics. For example, duality of states and observables in the case of the Gelfand-Naimark Theorem. http://en.wikipedia.org/wiki/Von_Neumann_bicommutant_theorem
Comment: May be worth to add link to theorem or say what is it about .... then you will get my + 1 :)
Comment: @a.chernov done!
Comment: It seems that what you want (as supplied by Nik Weaver) is an intuitive *description* rather than an intuitive *explanation*. I zmean, what is an intuiive explanation of something being WOT-closed?
Comment: @YemonChoi that there is a fair number elements in the topology for a particular purpose?
Answer: Okay, here's an explanation in terms of quantum mechanics. Let ${\cal A}$ be a family of observables, modeled as self-adjoint operators on some Hilbert space, and let ${\cal U}$ be the group of all unitary transformations that leave every observable in ${\cal A}$ invariant. You can consider ${\cal U}$ to be a kind of symmetry group. Mathematically it is the set of unitaries in the first commutant ${\cal A}'$ of ${\cal A}$, and the set of all observables left invariant by ${\cal U}$ is the double commutant of ${\cal A}$. So the double commutant theorem says that the set of all observables left invariant by every transformation that leaves every observable in ${\cal A}$ invariant, is the self-adjoint part of the von Neumann algebra generated by ${\cal A}$.
Comment: How about "an explanation of the intuitive meaning"?
Comment: This is a nice description, but I don't really see how it's an *explanation*...
Answer: Weak closure is more universal than norm closure. Commutative C* algebra is an algebra of continuous functions on spectrum, which could be any compact space. Von Neumann algebras deal with measure, and measure space is universal - the interval [0,1] with Lebesgue measure (provided measure of a point equals to 0).
Check the V.A.Rokhlin theorem:
https://en.wikipedia.org/wiki/Standard_probability_space


piezo stereo preamp

Question: I have found several projects on piezo preamps but I cant find anything that can run 2 piezo inputs to make it stereo and uses potentiometer to control volume gain etc.
What I found is "Collin's Lab: DIY Contact Mic" from make magazine website that uses an MPF102.

 1. Can I just make 2 of them and make them share 1 ground?
 2. Which component do I add/change to have a volume gain with a potentiometer?
 3. Is it possible to have a "balance" from left and right inputs using sliding pot?
 4. Can I use a 3.7v rechargeable battery instead of a 9 volt? I was thinking of salvaging parts from an old powerbank.
Answer:
Common GND , +9V and 10uF decoupling capacitor do well in stereo version
It would be useful not to add the output impedance of the preamp, so replace the 1.5kOhm resistor with the volume pot. Use logarithmic pot. 2200Ohm should be ok. Connect 4.7uF cap to the slider and the low volume end connector of the pot to +9V
Balance pot can be a 4700 ohm lin pot between the outputs, connect the slider to GND. The higher is the pot resistance, the less you lose the total volume, but the wider is the dead "no effect" area in the middle. Experiment. NOTE: It is good to change the 4,7uF capacitor to bigger value, say 47uF because this simple balance control increases the loading and causes attenuation at bass frequencies. This is negative loudness: when the balance control decreases the volume, low frequencies get more attenuation. This can be good - lower volume makes the sound less bassy and preserves some hearability in the total mix.
The preamp should be totally redesigned for low supply voltage to be sure. Simulate or do a test circuit. I have done no calculations, but I'm afraid of increased distortion. Piezo mics in guitars or percussion instruments  can give hefty peak voltages and low supply voltage possibly does not provide enough room for the signal voltages to swing.
Answer: Sure, you can make two circuits with a shared power source.
To change your volume, I wouldn't recommend modifying the existing circuit, I suggest connecting an op-amp amplifier with volume control after the preamp.
To control the balance, you can then modify the volume of individual channels.
To power the circuit with a 3.7v battery, you can use a step-up converter together with a charging circuit.
Hope that helps!
Comment: so to clarify.. shared power supply, both piezo would also share 1 common ground and would also share output as stereo?

piezo stereo preamp


Is it true that $n^r(X_n-X)\xrightarrow{d}Z$ implies $X_n\xrightarrow{d}X$?

Question: I see that without this last requirement $n^r(X_n-X)$ would blow up in probability, how to prove this formally? By contradiction maybe? Like assuming it doesn't converge in probability and hence finding a subsequence such that $\mathbb{P}(|X_n-X|>\varepsilon)>\Delta$ for all $k$, and then showing that this implies $n^r(X_n-X)$ to go to infinity in probability?
Comment: What happened to [this question](https://math.stackexchange.com/q/2974774/36150) of yours? Seems that they are kind of related, aren't they? Moreover, I have the impression that you are confusing "convergence in probability" and "convergence in distribution"...
Answer: It's overkill, but it follows trivially from the Skorokhod representation theorem.  Otherwise you can use a uniform integrability argument to show the characteristic function of $X_n$ converges to that of $X$, where the uniformity comes from the uniform tightness implied by your convergence in distribution to $Z$.
Answer: It is true for $r\gt 0$, but not necessarily for $r\gt 0$. Indeed, for each positive $\varepsilon$,
$$
\Pr\{\left\lvert X_n-X\right\rvert \gt \varepsilon\}=\Pr\{n^r\left\lvert X_n-X\right\rvert \gt n^r\varepsilon\}.
$$
A real number $R$ which is a continuity point of the cumulative distribution function (c.d.f.) of $Z$. Then for all $n$ such that $n^r\varepsilon\geqslant R$, the following inequality holds:
$$
\Pr\{\left\lvert X_n-X\right\rvert \gt \varepsilon\} \leqslant \Pr\{n^r\left\lvert X_n-X\right\rvert \gt R\}
$$
and using the convergence in distribution of $n^r\left\lvert X_n-X\right\rvert$ to $Z$ combined with the fact that $R$ is a continuity point of the c.d.f. of $Z$, we derive that for each $R$ being a continuity point of the c.d.f. of $Z$,
$$
\limsup_{n\to +\infty}\Pr\{\left\lvert X_n-X\right\rvert \gt \varepsilon\} \leqslant \Pr\{Z \gt R\}.
$$
As $R$ can be chosen as large as wished, we deduce that $X_n\to X$ in probability. Since convergence in probability implies weak convergence, we are done.


How the data transmission of the non-ir-filter-cam works

Question: How does the transmission of the raspi non-ir-filter-cam work? Can I get a forth value "ir" in a pixel (r,g,b,ir)? Or is an ir pixel just white? In the end I want to have a python script that has a list of pixels with ir pixels, in, for example, a jpeg format.
Comment: You should clarify where you expect to find these pixels, beyond the very ambiguous "data transmission".  Is it in a jpeg image created by `raspistill` or some other app?   Some particular library interface?
Comment: Yep. Jpeg created by raspistill in python @goldilocks
Comment: I got asked a similar question in [issue #137](https://github.com/waveform80/picamera/issues/137) of picamera. TL;DR: you can't do this - the IR "information" winds up mixed into the red, green, and blue channels and there's no way to separate it out again but see that ticket for a pretty graph showing why!
Comment: @Dave Jones Huh. Looks very complicated. Too complicated for the little little project I wanted to do.
Comment: I wanted to have glasses so you can see IR as red and every other color (althought ir is no color thanks to @goldilocks answer) compressed. (the color range would be compressed)... Extend the senses! :)
Comment: goldilocks answer is absolutely correct; the graph in that issue simply goes to demonstrate *why* it's correct by showing the response curves of a typical Bayer filter, and the fact that with the usual IR/UV filter removed there's no longer a simple one-to-one mapping between wavelength of light and colour in the resulting image. You can certainly use an IR-pass filter to take IR-only images with the camera, but you can't capture both visible and IR wavelengths and expect to separate them afterwards.
Comment: Yeah. Of course. I just wanted to tell you what I needed this for. @Dave Jones
Comment: @DaveJones Thanks for the link.  I think large parts of my answer were far from "absolutely correct", lol, but you prompted me to do some more reading/pondering/editing and hopefully they are closer to that now.
Answer: The no filter camera, is basically what is says. There is no Infra-red filter applied before the CMOS, so IR light can pass into the sensor, the standard camera removes this IR light from BEFORE it hits the CMOS.
Capturing IR as you would like to may not work as expected. You cannot capture IR data, for example TV remote control pulses or something, the frame rate is just tooooo low! Remotes operate in khz cycles and what looks like a light to us are actually hundreds of pulses in milliseconds.
If you build your own IR transmitter, the fastest speed you might be able to achieve if 30, 60 or 120 baud! (that is 1 bit per frame, given no frames are lost!) You could divide the image into 4 areas, giving you 4 times more speed but calibration will be a pain in the back!
To detect if IR was shone into the sensor, there is no extra parameters, no. As far as the CMOS is concerned this is just bright light, you may be able to extract it using OpenCV? Or some custom JPEG parser or something.
If you need data transmitting you should use a IR kit and hook it up to the GPIO.

The NoIR filter is usefull in low light applications, light night time with the use of IR cannons, that illuminate the environment without the naked eye seeing this. Like a basic night vision light.
Comment: I'm so sad that I can't upvote. :(
Comment: I'm so sad nobody is up voting you, even though there's allot of activity here. Glad you found your answer anyway, hope to see you around.
Answer: There is no such thing as IR pixel values, at least, not in the sense of a fourth channel independent from RGB.
The NoIR camera is the regular camera with a filter removed.  Presumably this was marketed in response to occasionally successful efforts made by people to remove it after market.
I'll give you my understanding of how a color image is produced by the camera, thanks in part to Dave Jone's comment above.
The camera uses a CMOS sensor array. Although these sensors, one per image pixel, are not uniformly sensitive to all frequencies of light, they do not detect wavelength in any precise way; they measure  intensity.  Color is produced by filtering the light in a very fine grid (a Bayer filter) over the sensors such that each one ends up representing one of three bands (red, blue, or green).  Subsequent to this, each pixel has values for the other two bands added by software which (in its simplest form) interpolates them from neighbouring sensors. Pretty clever.
The Bayer filter, however, does not always perfectly balance color intensity because of the significance of non-visible IR and UV light, which affects the CMOS sensors.  Hence the role of the IR filter, which is actually an IR/UV filter, though the IR is more of a factor because of the bandwidth sensitivity of the sensors (see the graph in the discussion linked by Dave, and note that the Bayer band blocked the least by the IR filter is the middle one, green).
If you look at a collection of images from the NoIR camera, you'll notice ones that were taken in normal light look washed out because of the added contribution to the blue and red sensors, which is half of the total (50% of a Bayer filter is green, in keeping with the proportion of red/green/blue photoreceptors in the human eye).
Photos taken in very low light tend to look grayscale, presumably because of amplification of the interpolated RGB pixel values.
However, the NoIR camera can also be used with a filter that comes with it to produce false color images similar to those familar from more dedicated IR sensors.  In the case of the raspicam this is sometimes done with NDIV, where the pixel intensity (taken from that wikipedia article) is:
<code>(NIR - VIS) / (NIR + VIS)
</code>
Here NIR is light in the near infrared range and VIS is in the visible range.  These ranges overlap, since the visible spectrum is about half and half "near infrared" and "near ultraviolet".  The external blue filter used gets rid of much of the latter, and using this formula (where the two values extend from 0 to infinity) will produce a value ranging from -1 to 1, where the intensity is a measure of near infrared in the absence of near ultra-violet, and that range has corresponding false color values.  This is used in plant photography because plants will absorb a part of the spectrum that actually corresponds to our visible light, but scatter the lower part of near infrared (i.e., that below the visible spectrum).1

ir pixels, in, for example, a jpeg format

JPEG images use up to three values to represent the color of a pixel; I think these are usually YCbCr values that are translatable into RGB (JPEGs may also contain greyscale).  Three values are suited to representing colors we recognize since colors are a product of the distribution of three types of cone cells in the human eye, each sensitive to a specific band of visible light (the red, the green, and the blue).  Which takes us back to the physical Bayer filter.  Which does not have a dedicated IR component.
Some other image formats do include a fourth value, alpha, which is a measure of transparency.  For hopefully obvious reasons, this is non-nonsensical in photography (nor is it part of a color), although you can take a photograph and subsequently make part of it transparent and store this in a (non-jpeg) format which includes alpha values.

1. The Foundation has their own discussion of this explaining the purpose of the blue filter.  This kind of plant oriented photography does not necessarily use false color NDIV, but there are some examples of such here.
Comment: Very much good information. Thanks! (sorry, I can't upvote since I only have 8 rep)
Comment: Yea up voting seems to be a myth on here recently... virtual upvote +1


Why is it considered best practice to use a subdomain for the SAP "Send From" email address?

Question: I'm having a hard time finding a concrete answer to this.  Every Marketing Cloud implementation that I've worked on had an email address as something like email.marketing.companyname.com as the "authenticated" send-from email address in SAP (Sender Authentication Package) as well as in the "Sender Profile".  I've read that it's not considered best practice to use the root company website domain (@companyname.com).  Is there any reason to this?
Answer: This isn't actually Marketing Cloud related nor isn't it always even a best practice method, but the reason why it's usually done this way comes down to the Email authentication method known as DKIM (DomainKeys Identified Email) and Email validation protocol known as SPF (Sender Policy Framework) which are the most common methods which govern the deliverability of Emails.
To give you a quick overview, DKIM lets a domain associate its name with an email message by adding a signature to it. Verification by recipient Email provider or service is done by using signer's public key published in the DNS.
Essentially meaning if the key is wrong or missing, the Email might be spoofed, edited or come from untrustworthy source.  Email providers will generally block these emails or mark them as spam.
The domain that you need to provide for the SAP will always need to be an unused one, which is the reason you cannot use the company domain for it in 99.99% of cases.
That being said, many Marketing Cloud clients actually do use their company Email when sending out Emails from Marketing Cloud, but this is done via Private Domain add-on.
Once purchased, you can use that Private Domain for a specific functionality in Marketing Cloud, including as a Sender Profile address. However noting that this feature does not ever include the option for Link and Image wrappings.
Salesforce will be generating a zone file which the company domain holder will use to add DKIM key and SPF manually to the DNS. The authentication after adding the keys and notifying Salesforce Deliverability Team will generally take less than 24h and this way the company domain will show up under authenticated domains in your Marketing Cloud.

DKIM explained
SPF explained
Marketing Cloud Private Domains
Answer: Typically it has to do with deliverability and abiding by best practice regarding SPF records. A SPF record is a DNS entry that authorizes a specific IP address to sending mail from that domain. The SPF record for @companyname.com is most trusted when it has two or fewer authorized email senders. If it starts to get too many, some spam filters may see this as suspicious.
The IT Ops folks at @companyname.com probably want to allow only one or two SPF entries for their email at the top level domain, and that's typically restricted to the company mail servers, like Exchange.
However, they can create a subdomain and enter a SPF record for a different email system. This aids the subscriber in knowing that there's a relationship between the top level domain and the new subdomain, and it also provides an insulated domain so that any activities that might blacklist one server have less of a chance of affecting the other. Deliverability takes into account IP address as well as domain, but every inbox provider weighs them differently.
Comment: Thanks @Matt.  You've been super helpful with some my questions.  I got thrown into supporting deliverability concerns when I have next to no experience with deliverability (only really Marketing Cloud implementations).  Salesforce has a team dedicated to handling deliverability and since I'm with a different company now (not Salesforce anymore), we do not have a Deliverability Consultant.  Thanks again!
Answer: Yes, there is a good reason - security and deliverability.
1) If you use the corporate domain, you are authenticating SFMC to send as an authenticated sender for your corporate domain, which is less distinguishable as Marketing Communication. InfoSec departments feel less comfortable allowing a Cloud platform to email as a corporate domain  for reasons that such Comms and monitoring fall outside their control i.e. someone could maliciously spoof and email send from SFMC as though the CEO and communicate anything. InfoSec typically keep corporate Comms internally managed, controlled and monitored
2) If you were ever to blacklist your deliverability, then you are likely to also impact your corporate sending
3) DNS, I believe it's not possible to have corporate email and cloud email services pointed in the same DNS file
Best practice is to either use a subdomain, or specific marketing domain.
Subdomain doesn't have to be email.company.com - though most of the time this is what Salesforce recommend. I've suggested alternatives :
Comms.company.com
Mktg.company.com
e.company.com
If you register a domain, then you can technically have anything (if the domain is available). However the familiarity and customer experience is less with a domain  than a subdomain as any person can register and own domain e.g. mktg-company.com


If I rez Rasmin Bridger after an ICE, does the Runner have to pay its bit immediately?

Question: If I rez Rasmin Bridger after the Runner has passed a piece of ICE, does he get to pay its bit immediatly, or does it take effect only after the following ICE?
Comment: you switched your accepted answer. Any reason why? Did you find an official source that corroborated the new accepted answer?
Comment: @user1873: Thomas' answer used your same source, reading it differently. I re-read them both and decided his interpretation was more likely right.
Comment: my source included the PDF chart that shows when you can Rez an upgrade, and when Rasmin Bridger triggers. How does that chart square with what you believe is the correct interpretation?
Answer: I think it only takes effect on the following ICE. While I also have not seen any official ruling on this card, it hinges on several different rules. When does Rasmin Bridger's ability trigger?

After Runner passes each piece of ice on this fort, Runner must pay 1 or end the run.

From this chart, step 32, the ICE is passed and this is where the effect triggers if Rasmin Bridger had already been rezzed. If he had not been rezzed, the next opportunity to rez him would be after the runner decides to jack out or not (step 35).
The rulebook only mentions that a Rezzing a Corporation Card can occur (among other times):

during a run while the Runner approaches a piece of ice and while the Runner passes a piece of ice;

The rules don't really clarify the timing of while. The closest thing regarding timing is the Run Protocol - Overview section. It seems to indicate that Upgrades must be rezzed during the approach or just after the runner doesn't jack out.

If the Runner passes all of the pieces of ice (or if there is no ice to be passed in the first place), he or she gets one last chance to jack out. If the Runner doesn't jack out, we have one last opportunity to rez any of the nodes and upgrades inside the fort, and unless these end the run, the run is considered successful, and the Runner accesses the appropriate cards.
Answer: I don't know of an official ruling on this, but I believe that they will pay a bit.  You can rez Rasmin Bridger "during a run while the Runner approaches a piece of ice and while the Runner passes a piece of ice" (one of the times the rules lists as the Corp being allowed to rez cards) and since the runner is still passing the piece of ice, they will have to pay a bit /after/ passing.


Four different pwm using PIC 18f45k80

Question: In a 4 phase dc motor control application, I have to excite the coil using Mosfet with the pwm of 12.5 Hz with the train of pulses of 12 khz on each phase. So I am in a position to create 4 different pwms each with the above mentioned frequencies. I have planned to use Pic 18f45k80 which has four CCP modules. But these modules use only two timers TIMER 2 and TIMER 4 for PWM. So I could create only 2 different pwm at a time. Is there a way to create 4 pwms using PIC 18f45k80 with using CCP modules? I like to create a pwm waveform like the image that I have added.
Comment: If all of the PWMs need to be at 12 kHz, what's the problem?
Comment: Each pwm must start nearly at the end of other pwm. how to do it?
Answer: Section 19.4 of the datasheet discusses PWM operation. In reality, the PWM functionality uses only Timer 2. This timer controls the period (frequency) as explained by equation 19-1:
PWM Period = [(PR2) + 1] • 4 • TOSC • (TMR2 Prescale Value)
Thus, so long as the frequency is common to all 4 outputs, you are all set there. Then, you can set each duty cycle independently using the CCPRxL and CCPxCON registers where x is equal to 1, 2, 3, or 4 depending on which duty cycle you want to set. Equation 19-2 explains how to calculate the duty cycle:
PWM Duty Cycle = (CCPR4L:CCP4CON<5:4>) • TOSC • (TMR2 Prescale Value)
Now, when timer 2 equals one of the 10 bit values in CCPRxL and CCPxCON, that particular pin will toggle. Then, when timer 2 matches the value in PR2, all pins will toggle back to the original state.
Comment: The pwm for each phase must start nearly at the end of the other. Could you please tell me, Can I achieve the waveform like the above using CCP modules in Pic !8f45k80.
Comment: Oh, I see now. The picture helps. In that case, I wouldn't use the PWM. I would use the Compare mode of the CCP module (Section 19.3). When the cycle starts, turn on MOSFET 1. Set the CCPRx register so that it will match the timer when the phases need to to switch. Then, rather than having an output pin change, just have it trigger the software interrupt. In the interrupt routine, turn off the current FET, turn on the next FET, and reset the timer. If this is what you are looking for, I will edit my answer.

Four different pwm using PIC 18f45k80


Is it illegal to have a product delivered to a different ZIP code to pay less sales tax?

Question: Me and my friends were chatting in dinner in California. Some were complaining about the high sales tax rate in our state. One suggested that if any of us had an Oregon address, we could have our stuff shipped there, then shipped to our residences so that we could take advantage of Oregon's 0% sales tax. We were split on the legality of this idea: some argued that it is a textbook example of tax evasion while others claimed that this does not raise any legal issues. Which side is right here?
Comment: @NateEldredge: The thing is, there are a ton of tax *avoidance* strategies that are perfectly legal and effective. It's not always obvious to the public where the tax code draws the line between avoidance and evasion.
Comment: Questions like this always remind me of https://xkcd.com/1494/
Comment: [Tax *avoidance*](https://en.wikipedia.org/wiki/Tax_avoidance) isn't illegal. *evasion* is when you owe money and don't pay it. The questions is, would they *owe* money? - Bought on the net to be shipped to OG, by my friend, to my friend. Then I come and take it back to CA. Then what? - "evading more than $1 million of sales taxes on six paintings that *he* bought last fall." - You've got better friends then me if they're willing to be participant in tax fraud, that I'd assume they'd then be more on the hook for it than you if they're the buyer.
Comment: Oregonian lore: Folks from Vancouver, WA commonly do this, usually justified by working in Portland, OR. Rumor is that you should buy cars on the side where you live, for tax purposes; the IRS is wise to the *avoidance* tactic when it comes to titled/deeded property.
Comment: @Corbin Every state DMV I've dealt with verifies sales/use tax payment, if applicable, when registering the plate. This is where it's collected in a person-to-person used car sale. California's DMV collects use tax when you move your already-owned car into the state. Also, in some states, cars/boats/planes/homes aren't subject to sales tax, or subject to a different tax, as they are subject to property taxes. Oregon, for example, has no sales tax but a 0.5% vehicle privilege tax.
Comment: @Kevin [Indeed.](https://www.nytimes.com/2014/04/13/business/buyers-find-tax-break-on-art-let-it-hang-awhile-in-portland.html)
Comment: @Kevin And [indeed](https://matthewjcheung.medium.com/legally-avoiding-car-sales-tax-37ee84adca79).
Comment: [xkcd 1494 explained](https://www.explainxkcd.com/wiki/index.php/1494:_Insurance).
Answer: You need to pay tax on it. From CA FAQ on use tax.  -

Generally, if sales tax would apply when you buy physical merchandise in California, use tax applies when you make a similar purchase without tax from a business located outside the state.

For these purchases, the buyer is required to pay use tax separately.
I see comments about bags of chips bought on a trip off of state. If the dollars are big enough this gets enforced,

Ex-Tyco Chief Is Indicted In Tax Case
By Alex Berenson and Carol Vogel
June 5, 2002
L. Dennis Kozlowski, former chairman and chief executive of Tyco International, was indicted yesterday by a grand jury in Manhattan on charges of evading more than $1 million of sales taxes on six paintings that he bought last fall.
Mr. Kozlowski bought the paintings, which included a Renoir and a Monet, for $13.1 million for his 13-room apartment at 950 Fifth Avenue. To avoid paying New York sales taxes, prosecutors said, he shipped empty crates to Tyco's headquarters in Exeter, N.H., and transported paintings back and forth from New Hampshire to Manhattan.

He went to jail.
Comment: **Comments have been [moved to chat](https://chat.stackexchange.com/rooms/148808/discussion-on-answer-by-george-white-is-it-illegal-to-have-a-product-delivered-t); please do not continue the discussion here.** Before posting a comment below this one, please review the [purposes of comments](/help/privileges/comment). Comments that do not request clarification or suggest improvements usually belong as an [answer](/help/how-to-answer), on [meta], or in [chat]. Comments continuing discussion may be removed.
Comment: The state of Texas used to have a Use Tax form Texas residents had to fill out when they bought something online, from a retailer that didn't have physical store locations in Texas.  Back then, Amazon had no physical stores in Texas.  I did file a couple of those returns once I found out I was a scofflaw.  Then Amazon (and other online retailers) started gathering sales tax from the customer.