Concatenating structure elements

Question: For example
test = struct('one', [1;2;3], 'two', [4;5;6]);

I would like to vertically concatenate the vectors in the struct test. For example, if it were defined as a cell array instead test = {[1;2;3], [4;5;6]}, I could do vertcat(test{:}). However, vertcat(test{:}) returns a struct object if test is a struct.
I would like to have a solution that does not involve creating a temporary cell array using struct2cell.
Answer: What you want to do is to actually use struct2array and then flatten the result.
A = reshape(struct2array(test), [], 1);

%   1
%   2
%   3
%   4
%   5
%   6

Benchmark
As a follow-up, I have performed a little bit of a benchmark comparing the usage of struct2cell to struct2array. We would expect the cell2mat(struct2cell()) method to be slower because 1) it is operating on cell arrays and 2) it uses cell arrays rather than numerical arrays which are notoriously slow. Here is the script I used to perform the tests.

function tests()
    sizes = round(linspace(100, 100000));

    times1 = zeros(size(sizes));
    times2 = zeros(size(sizes));

    for k = 1:numel(sizes)
        sz = sizes(k);
        S = struct('one', rand(sz, 1), 'two', rand(sz, 1));
        times1(k) = timeit(@()cellbased(S));
        times2(k) = timeit(@()arraybased(S));
    end

    figure;
    plot(sizes, cat(1, times1 * 1000, times2 * 1000));
    legend('struct2cell', 'struct2array')
    xlabel('Number of elements in S.a and S.b')
    ylabel('Execution time (ms)')
end

function C = cellbased(S)
    C = cell2mat(struct2cell(S));
end

function C = arraybased(S)
    C = reshape(struct2array(S), [], 1);
end

And the results (R2015b)
Answer: In my case I managed to do it using:
cell2mat(struct2cell(test))

Comment: Why do you have a self-answer where you use `struct2cell` despite explicitly stating in your question that you *don't* want to use `struct2cell`? Also you do realize that this still creates a temporary cell array, right?
Comment: Sorry, to be precise I did not want to assign a temporary variable explicitly with `tmp = struct2cell`. I did not realise it creates a temporary cell array. It was just the solution I found so it was worth posting in case no one had a better answer.
Comment: You can think of it kind of like `mean(rand(1e10,1))`. This is still going to consume all of the memory required to hold the random array even though the end result is a single number. I have added a benchmark to my answer to show the performance difference between these two solutions.

Concatenating structure elements


Ionicons version 5 with angular

Question: How to add ionicons version 5 to angular, with version 4.5 there was a scss available and I can use in that way but now in version 5 ionicons use svgs and don't know how to integrate it with angular.
Current approach
In angular.json
"styles": [
              "./node_modules/ionicons/dist/scss/ionicons.scss",
              "src/app/theme/styles/styles.scss"
            ],

Then in my app.component.ts (I'm using nebular UI)
https://akveo.github.io/nebular/docs/guides/register-icon-pack#register-icon-pack
export class AppComponent implements OnInit {

  constructor(private iconsLibrary: NbIconLibraries, public store$: Store<any>, ) {
    iconsLibrary.registerFontPack('ion', { iconClassPrefix: 'ion' });
    iconsLibrary.registerFontPack('nebular', { iconClassPrefix: 'nb' });
    iconsLibrary.setDefaultPack('nebular');
    // @ts-ignore
    if (window.Cypress) {
      // @ts-ignore
      window.__appStore__ = store$;
    }
  }

  ngOnInit() {
  }
}

I see in issues that for ionic with angular them add
"assets": [
              {
                "glob": "**/*",
                "input": "src/assets",
                "output": "assets"
              },
              {
                "glob": "**/*.svg",
                "input": "node_modules/ionicons/dist/ionicons/svg",
                "output": "./svg"
              }
            ]

but I don't know how to continue
Answer: Step 1: npm install ionicons
Step 2: include ionicons in assets in angular.json
"assets": [
          "src/favicon.ico",
          "src/assets",
          {
            "glob": "**/*",
            "input": "node_modules/ionicons/dist/ionicons",
            "output": "./ionicons"
          },
          {
            "glob": "**/*.js",
            "input": "node_modules/ionicons/dist/",
            "output": "./"
          }
        ],

Step 3: Add script in Index.html

<app-root></app-root>

Step 4: Add schemas: [ CUSTOM_ELEMENTS_SCHEMA ] in app.module.ts
@NgModule({
declarations: [
    AppComponent
  ],
  schemas: [ CUSTOM_ELEMENTS_SCHEMA ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    BrowserAnimationsModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})

if you are using ion-icon in another module add schemas: [ CUSTOM_ELEMENTS_SCHEMA ] so you won't get web component error.
Step 5: Use Regular like
<ion-icon name="heart"></ion-icon>

Answer: Ionicons ver 5 doesn't looks like supporting font icon file like Ionic 4 ,https://github.com/ionic-team/ionicons/tree/4.x#using-the-font-icon anymore.
Comment: i've searched in forums for days, cleaning cache, installing npm, this solution worked like a charm
Answer: You can easily hack the icons.
I created this gist, you can download and it to your project.
Then import the NbIonIcons const in AppComponent and then add it using the Nebular method registerSvgPack from NbIconLibraries (example below)
...
import {NbIonIcons} from './icons';
....
export class AppComponent implements OnInit {

  constructor(private iconsLibrary: NbIconLibraries, public store$: Store<any>, ) {
    iconsLibrary.registerFontPack('ion', { iconClassPrefix: 'ion' });
    iconsLibrary.registerFontPack('nebular', { iconClassPrefix: 'nb' });

    iconsLibrary.registerSvgPack('ionicons', NbIonIcons);

    iconsLibrary.setDefaultPack('nebular');
    // @ts-ignore
    if (window.Cypress) {
      // @ts-ignore
      window.__appStore__ = store$;
    }
  }

  ngOnInit() {
  }
}

At this point you can use you icons as usual.
<nb-icon icon="home-outline" pack="ionicons"></nb-icon>

Keep in mind that you have to update the list if icons are added / removed from package.
Comment: seems like this should work, didnt have time this week to test it. the only annoying thing is the manually part when ionic get update. I will approve it soon ty.
Comment: This is working. However, I am not able to style the icons via nb-icon. Any ideas?
Comment: Maybe you can extend the nbIcon service/directive and use the useClass to provide the new directive. I done a similar devlop on the NbMenu adding the tooltips on it but using the original NbMenuService

Ionicons version 5 with angular


MetroFramework MenuStrip Now Showing in ToolBox

Question:
I installed packages for MetroFramework but there's no MetroMenuStrip and the other tools.
When I search the web I see too much examples about MetroMenuStrip. But nobody has any problem like mine.
I tried with all these package codes :
<code>Install-Package Winform.Metroframework
Install-Package MetroFramework
Install-Package MetroModernUI
Install-Package MetroFramework.Design
</code>
Answer: They dont have the MetroMenuStrip control, You can check the source code
here .May be the control has been removed due to some bugs and issues.


Simplifying an expression involving integrals: $ \xi= (e^\Phi)(\Omega^2)(\Psi^{-1})$

Question: Simplify the following expression:
$$ \xi= (e^\Phi)(\Omega^2)(\Psi^{-1})$$
Where:
$$  \log(\Phi^{-1})=\int\frac{(\cos^{-1}\sqrt{1-x^2})^{-1}}{\ln\left(\sin^{-1}(2x\sqrt{1-x^2})/\pi\right)} dx$$
Note: It is given, that the ' $+C$ ' after evaluation of the indefinite integral here, is $0$. (i.e. Assume $C=0$)

$$\Omega= \int^{\infty}_{-\infty}\cos(x^2)+\sin(x^2)dx$$
$$\Psi= \int^1_x \frac{1}{\sqrt{\frac{1-z^2}{16}}} dz$$

I made this question up while solving some integrals, and just wanted to keep a record of it. Hence I've uploaded it in a Q&A style. To whosoever reading this, I hope you find the question mildly interesting!
Answer: $$\Phi^{-1}=\exp\int\frac{\big(\cos^{-1}\sqrt{1-x^2}\big)^{-1}}{\ln\frac{\big(\sin^{-1}\big(2x\sqrt{1-x^2}\big)\big)}{\pi}}dx$$
The integral itself evaluates to: $$-\ln\left[\ln\left(\frac{2\arccos(x)}{\pi}\right)\right] + C $$
(Ignored the $C$ as stated in the question).
Therefore, it becomes $$ \Phi=\frac{1}{\exp\left(-\ln\left[\ln\left(\frac{2\arccos(x)}{\pi}\right)\right]\right)}=\ln\left(\frac{2\arccos(x)}{\pi}\right)$$
Therefore $$ \exp(\Phi)= \frac{2\arccos(x)}{\pi}$$

On evaluating,
$$\Omega=\sqrt{2\pi}$$Therefore
$$\Omega^2=2\pi$$

On evaluating,$$ \Psi= 4\arccos(x)$$Therefore$$ \Psi^{-1}= \frac{1}{4\arccos(x)}$$

Therefore: $$ \xi= (e^\Phi)(\Omega^2)(\Psi^{-1})=1$$


Responsive vs adaptive vs fixed size video player

Question: I am thinking to create browser plugin/extension to play videos over the webpage but from user experience point of view I am having doubt regarding size of player.
Shall I keep it:

Responsive : so that user can resize as he desires by giving resize option at corners
or Adaptive by giving 2 or 3 fixed aspect ratios like youtube provides
or Single fixed video size
Answer: There's a comprehensive topic on this here:
Fluid Video
With regards to the right and wrongs of UX/UI, my opinion would be the needs of the video to be shown to the user and how visible it would be in an extremely small view port.
Comment: visibility on smaller view port yeah it makes point


Installation of virtualbox-guest-dkms fails

Question: Recently I installed Ubuntu into VirtualBox. The problem was that the resolution was really small and it stayed small even when I enlarge it by going to view → switch to full screen. I searched and found this solution:
sudo apt-get install virtualbox-guest-dkms

which fails with this error message:
File "/usr/share/apport/package-hooks/dkms_packages.py", line 98, in <module>
with apport.fileutils.make_report_file(report) as f: AttributeError: 'module' object has no attribute 'make_report_file'
Error! Bad return status for module build on kernel: 3.19.0-25-generic (x86_64)
Consult /var/lib/dkms/virtualbox-guest/4.3.10/build/make.log for more information

Content of the log file:
DKMS make.log for virtualbox-guest-4.3.10 for kernel 3.19.0-25-generic (x86_64)
Mi 18. Nov 11:15:34 CET 2015
make: Entering directory `/usr/src/linux-headers-3.19.0-25-generic'
  LD      /var/lib/dkms/virtualbox-guest/4.3.10/build/built-in.o
  LD      /var/lib/dkms/virtualbox-guest/4.3.10/build/vboxguest/built-in.o
  CC [M]  /var/lib/dkms/virtualbox-guest/4.3.10/build/vboxguest/VBoxGuest-linux.o
  CC [M]  /var/lib/dkms/virtualbox-guest/4.3.10/build/vboxguest/VBoxGuest.o
/var/lib/dkms/virtualbox-guest/4.3.10/build/vboxguest/VBoxGuest.c: In function 'VBoxGuestCommonGetHandledEventsLocked':
/var/lib/dkms/virtualbox-guest/4.3.10/build/vboxguest/VBoxGuest.c:82:5: warning: ISO C90 forbids mixed declarations and code [-Wdeclaration-after-statement]
     uint32_t u32AllowedGuestCaps = pSession->u32AquiredGuestCaps | (VMMDEV_EVENT_VALID_EVENT_MASK & ~pDevExt->u32AcquireModeGuestCaps);
     ^
/var/lib/dkms/virtualbox-guest/4.3.10/build/vboxguest/VBoxGuest.c:2660:5: warning: ISO C90 forbids mixed declarations and code [-Wdeclaration-after-statement]
     uint32_t fGenFakeEvents = 0;
     ^
/var/lib/dkms/virtualbox-guest/4.3.10/build/vboxguest/VBoxGuest.c: In function 'VBoxGuestCommonIOCtl':
/var/lib/dkms/virtualbox-guest/4.3.10/build/vboxguest/VBoxGuest.c:2807:9: warning: ISO C90 forbids mixed declarations and code [-Wdeclaration-after-statement]
         VBoxGuestHGCMCallInfoTimed *pInfo = (VBoxGuestHGCMCallInfoTimed *)pvData;
         ^
  CC [M]  /var/lib/dkms/virtualbox-guest/4.3.10/build/vboxguest/VBoxGuest2.o
  CC [M]  /var/lib/dkms/virtualbox-guest/4.3.10/build/vboxguest/GenericRequest.o
  CC [M]  /var/lib/dkms/virtualbox-guest/4.3.10/build/vboxguest/HGCMInternal.o
  CC [M]  /var/lib/dkms/virtualbox-guest/4.3.10/build/vboxguest/Init.o
/Init.o
  CC [M]  /var/lib/dkms/virtualbox-guest/4.3.10/build/vboxguest/PhysHeap.o
  CC [M]  /var/lib/dkms/virtualbox-guest/4.3.10/build/vboxguest/SysHlp.o
  CC [M]  /var/lib/dkms/virtualbox-guest/4.3.10/build/vboxguest/VMMDev.o
  CC [M]  /var/lib/dkms/virtualbox-guest/4.3.10/build/vboxguest/r0drv/alloc-r0drv.o
  CC [M]  /var/lib/dkms/virtualbox-guest/4.3.10/build/vboxguest/r0drv/initterm-r0drv.o
  CC [M]  /var/lib/dkms/virtualbox-guest/4.3.10/build/vboxguest/r0drv/memobj-r0drv.o
  CC [M]  /var/lib/dkms/virtualbox-guest/4.3.10/build/vboxguest/r0drv/mpnotification-r0drv.o
  CC [M]  /var/lib/dkms/virtualbox-guest/4.3.10/build/vboxguest/r0drv/powernotification-r0drv.o
  CC [M]  /var/lib/dkms/virtualbox-guest/4.3.10/build/vboxguest/r0drv/linux/alloc-r0drv-linux.o
/var/lib/dkms/virtualbox-guest/4.3.10/build/vboxguest/r0drv/linux/alloc-r0drv-linux.c: In function 'rtR0MemAllocExecVmArea':

/var/lib/dkms/virtualbox-guest/4.3.10/build/vboxguest/r0drv/linux/alloc-r0drv-linux.c:194:9: warning: passing argument 3 of 'map_vm_area' from incompatible pointer type [enabled by default]
         if (!map_vm_area(pVmArea, PAGE_KERNEL_EXEC, &papPagesIterator))
         ^
In file included from ./arch/x86/include/asm/io.h:200:0,
                 from ./arch/x86/include/asm/realmode.h:5,
                 from ./arch/x86/include/asm/acpi.h:33,
                 from ./arch/x86/include/asm/fixmap.h:19,
                 from ./arch/x86/include/asm/apic.h:12,
                 from ./arch/x86/include/asm/smp.h:12,
                 from ./arch/x86/include/asm/mmzone_64.h:10,
                 from ./arch/x86/include/asm/mmzone.h:4,
                 from include/linux/mmzone.h:912,
                 from include/linux/gfp.h:5,
                 from include/linux/slab.h:14,
                 from /var/lib/dkms/virtualbox-guest/4.3.10/build/vboxguest/r0drv/linux/the-linux-kernel.h:72,
                 from /var/lib/dkms/virtualbox-guest/4.3.10/build/vboxguest/r0drv/linux/alloc-r0drv-linux.c:31:
include/linux/vmalloc.h:115:12: note: expected 'struct page **' but argument is of type 'struct page ***'
 extern int map_vm_area(struct vm_struct *area, pgprot_t prot,
            ^
  CC [M]  /var/lib/dkms/virtualbox-guest/4.3.10/build/vboxguest/r0drv/linux/assert-r0drv-linux.o
  CC [M]  /var/lib/dkms/virtualbox-guest/4.3.10/build/vboxguest/r0drv/linux/initterm-r0drv-linux.o
  CC [M]  /var/lib/dkms/virtualbox-guest/4.3.10/build/vboxguest/r0drv/linux/memobj-r0drv-linux.o
  CC [M]  /var/lib/dkms/virtualbox-guest/4.3.10/build/vboxguest/r0drv/linux/memuserkernel-r0drv-linux.o
  CC [M]  /var/lib/dkms/virtualbox-guest/4.3.10/build/vboxguest/r0drv/linux/mp-r0drv-linux.o
  CC [M]  /var/lib/dkms/virtualbox-guest/4.3.10/build/vboxguest/r0drv/linux/mpnotification-r0drv-linux.o
  CC [M]  /var/lib/dkms/virtualbox-guest/4.3.10/build/vboxguest/r0drv/linux/process-r0drv-linux.o
  CC [M]  /var/lib/dkms/virtualbox-guest/4.3.10/build/vboxguest/r0drv/linux/semevent-r0drv-linux.o
  CC [M]  /var/lib/dkms/virtualbox-guest/4.3.10/build/vboxguest/r0drv/linux/semeventmulti-r0drv-linux.o
  CC [M]  /var/lib/dkms/virtualbox-guest/4.3.10/build/vboxguest/r0drv/linux/semfastmutex-r0drv-linux.o
  CC [M]  /var/lib/dkms/virtualbox-guest/4.3.10/build/vboxguest/r0drv/linux/semmutex-r0drv-linux.o
  CC [M]  /var/lib/dkms/virtualbox-guest/4.3.10/build/vboxguest/r0drv/linux/spinlock-r0drv-linux.o
  CC [M]  /var/lib/dkms/virtualbox-guest/4.3.10/build/vboxguest/r0drv/linux/thread-r0drv-linux.o
  CC [M]  /var/lib/dkms/virtualbox-guest/4.3.10/build/vboxguest/r0drv/linux/thread2-r0drv-linux.o
  CC [M]  /var/lib/dkms/virtualbox-guest/4.3.10/build/vboxguest/r0drv/linux/time-r0drv-linux.o
  CC [M]  /var/lib/dkms/virtualbox-guest/4.3.10/build/vboxguest/r0drv/linux/RTLogWriteDebugger-r0drv-linux.o
  CC [M]  /var/lib/dkms/virtualbox-guest/4.3.10/build/vboxguest/r0drv/generic/semspinmutex-r0drv-generic.o
/common/alloc/alloc.o
  CC [M]  /var/lib/dkms/virtualbox-guest/4.3.10/build/vboxguest/common/err/RTErrConvertFromErrno.o
  CC [M]  /var/lib/dkms/virtualbox-guest/4.3.10/build/vboxguest/common/err/RTErrConvertToErrno.o
  CC [M]  /var/lib/dkms/virtualbox-guest/4.3.10/build/vboxguest/common/log/log.o
  CC [M]  /var/lib/dkms/virtualbox-guest/4.3.10/build/vboxguest/common/log/logellipsis.o
  CC [M]  /var/lib/dkms/virtualbox-guest/4.3.10/build/vboxguest/common/log/logrel.o
  CC [M]  /var/lib/dkms/virtualbox-guest/4.3.10/build/vboxguest/common/log/logrelellipsis.o
  CC [M]  /var/lib/dkms/virtualbox-guest/4.3.10/build/vboxguest/common/log/logcom.o
  CC [M]  /var/lib/dkms/virtualbox-guest/4.3.10/build/vboxguest/common/log/logformat.o
  CC [M]  /var/lib/dkms/virtualbox-guest/4.3.10/build/vboxguest/common/misc/RTAssertMsg1Weak.o
  CC [M]  /var/lib/dkms/virtualbox-guest/4.3.10/build/vboxguest/common/misc/RTAssertMsg1Weak.o
  CC [M]  /var/lib/dkms/virtualbox-guest/4.3.10/build/vboxguest/common/misc/RTAssertMsg2.o
  CC [M]  /var/lib/dkms/virtualbox-guest/4.3.10/build/vboxguest/common/misc/RTAssertMsg2Add.o
  CC [M]  /var/lib/dkms/virtualbox-guest/4.3.10/build/vboxguest/common/misc/RTAssertMsg2AddWeak.o
  CC [M]  /var/lib/dkms/virtualbox-guest/4.3.10/build/vboxguest/common/misc/RTAssertMsg2AddWeakV.o
  CC [M]  /var/lib/dkms/virtualbox-guest/4.3.10/build/vboxguest/common/misc/RTAssertMsg2Weak.o
  CC [M]  /var/lib/dkms/virtualbox-guest/4.3.10/build/vboxguest/common/misc/RTAssertMsg2WeakV.o
  CC [M]  /var/lib/dkms/virtualbox-guest/4.3.10/build/vboxguest/common/misc/assert.o
  CC [M]  /var/lib/dkms/virtualbox-guest/4.3.10/build/vboxguest/common/misc/thread.o
  CC [M]  /var/lib/dkms/virtualbox-guest/4.3.10/build/vboxguest/common/string/RTStrCopy.o
  CC [M]  /var/lib/dkms/virtualbox-guest/4.3.10/build/vboxguest/common/string/RTStrCopyP.o
  CC [M]  /var/lib/dkms/virtualbox-guest/4.3.10/build/vboxguest/common/string/RTStrCopyP.o
  CC [M]  /var/lib/dkms/virtualbox-guest/4.3.10/build/vboxguest/common/string/strformat.o
  CC [M]  /var/lib/dkms/virtualbox-guest/4.3.10/build/vboxguest/common/string/strformatrt.o
  CC [M]  /var/lib/dkms/virtualbox-guest/4.3.10/build/vboxguest/common/string/strformattype.o
  CC [M]  /var/lib/dkms/virtualbox-guest/4.3.10/build/vboxguest/common/string/strprintf.o
  CC [M]  /var/lib/dkms/virtualbox-guest/4.3.10/build/vboxguest/common/string/strtonum.o
  CC [M]  /var/lib/dkms/virtualbox-guest/4.3.10/build/vboxguest/common/table/avlpv.o
  CC [M]  /var/lib/dkms/virtualbox-guest/4.3.10/build/vboxguest/common/time/time.o
/var/lib/dkms/virtualbox-guest/4.3.10/build/vboxguest/common/time/time.c: In function 'VBoxGuest_RTTimeFromString':
...
/var/lib/dkms/virtualbox-guest/4.3.10/build/vboxsf/dirops.c:129:29: error: 'struct file' has no member named 'f_dentry'
     sf_g = GET_GLOB_INFO(dir->f_dentry->d_inode->i_sb);
                             ^
/var/lib/dkms/virtualbox-guest/4.3.10/build/vboxsf/vfsmod.h:144:60: note: in definition of macro 'GET_GLOB_INFO'
 # define GET_GLOB_INFO(sb)       ((struct sf_glob_info *) (sb)->s_fs_info)
                                                            ^
/var/lib/dkms/virtualbox-guest/4.3.10/build/vboxsf/dirops.c:135:16: error: 'struct file' has no member named 'f_dentry'
     inode = dir->f_dentry->d_inode;
                ^
make[2]: *** [/var/lib/dkms/virtualbox-guest/4.3.10/build/vboxsf/dirops.o] Error 1
make[1]: *** [/var/lib/dkms/virtualbox-guest/4.3.10/build/vboxsf] Error 2
make: *** [_module_/var/lib/dkms/virtualbox-guest/4.3.10/build] Error 2
make: Leaving directory `/usr/src/linux-headers-3.19.0-25-generic'
~

How can I fix this problem?
Comment: http://askubuntu.com/questions/588943/experiencing-small-resolution-issue-in-ubuntu-14-04-2-with-virtualbox-getting-s
Comment: You can use [pastebin](http://pastebin.com/) to dump the logfile. This helps to keep the question clear.
Answer: There is another way to do this, which I prefer.

Open Terminal
sudo apt-get update && upgrade -y
Once complete run: sudo apt-get install build-essential
On the running VirtualBox window along the top select Devices > Insert Guest addons cd image.
In your terminal navigate to: cd /media/USERNAME/ and run ls to then see what the virtual disc is called in my case it is VBOXADDITIONS_5.0.10_104061 and cd to it.
Now in the folder run sudo sh ./VBoxLinuxAdditions.run
Wait for it to finish
Reboot and Enjoy.

Let me know how you get on.
Comment: Sorry for late reply but I tried your steps but it did not work. After installing (devices->insert guest addons) and after running that batch file, I go the following message in response to those commands:The headers for the current running kernel were no gound, If the following module compilation fails then this could be the reason. And later I found this:
Not installing X Window System drivers
Answer: Finally, I managed to solve the problem. In my case, the problem was that I was running older VirtualBox and after updating it, the command virtualbox-guest-dkms worked and I could switch to full screen mode.


When is the product topology equal to products of open sets in component spaces?

Question: Let $\{X_i\}_{i\in I}$ be a family of topological spaces.  When is the topology of $\prod_i X_i$ equal to $\mathcal{T} = \left\{ \prod_i U_i : U_i \in \mathcal{T}(X_i)\right\}$ where $\mathcal{T}(X_i)$ is the topology on $X_i$, and $U_i$'s in those products are $\neq X_i$ for only finitely many $i$.
My attempt:
The open sets in the product topology are arbitrary unions of sets in the $\mathcal{T}$ described above, by Wikipedia's definition.  So each open set is of the form
$$\bigcup_{j \in J} \prod_{i \in I} U_i^j.$$
But here I'm stuck because $(A\times B) \cup (C\times D) \neq (A\cup C) \times (B \cup D) $ in general.
Comment: Even with closed sets, not every closed set in the product is the product of closed sets. However, the products of open sets form a basis of a topology (the Box-topology) on the product (if the number of nontrivial factors is finite, the Box-topology is the product topology).
Comment: I think there's confusion here between a *basis* for a topology and the topology itself.
Comment: If only one topology is nontrivial then the result holds. By trivial I mean $\tau=\{X,\varnothing\}$. I would guess these are the only cases.
Comment: And if two topologies are non-trivial, then it cannot hold.
Comment: What am I thinking of then?  I've seen something to the effect of the open sets are products of open sets.  Or can this be done with the closed sets only?
Comment: Often times it is enough to prove something on a basis for your topological space, so in many situations you can assume your open set is of this form.
Answer: The set
$$\mathcal{T} = \left\{ \prod_i U_i : U_i \in \mathcal{T}(X_i)\right\}$$
is a topology (assuming $I \neq \varnothing$) if and only if at least one factor $X_i$ is empty, or at most one factor does not carry the indiscrete topology.
If one factor is empty, we have $X = \varnothing$ and $\mathcal{T} = \{\varnothing\}$, so it's a topology.
If at most one factor does carry a topology other than the indiscrete topology,say $X_0$, then up to reordering indices
$$\mathcal{T} = \left\{ U_0 \times \prod_{i\neq 0} X_i : U_0 \in\mathcal{T}(X_0)\right\}$$
which is isomorphic to $\mathcal{T}(X_0)$, hence a topology.
If two spaces have at least two distinct non-empty open sets, say $X_0$ and $X_1$ with distinct non-empty open sets $U_0 \not\subset V_0$ and $U_1 \not \supset V_1$, then
$$\left(U_0\times U_1 \times \prod_{i \neq 0,1}X_i\right) \cup \left(V_0 \times V_1 \times \prod_{i \neq 0,1}X_i\right)$$
is a set that is not of the form $\prod\limits_i U_i$.


In-app purchase ios sending more transactions than needed

Question: Im using in-app purchase in SpriteKit. The first transaction does fine, but when i do the second one my
func paymentQueue(queue: SKPaymentQueue, updatedTransactions transactions: [SKPaymentTransaction])

called 2 times, than 3,4,5
so i do one request but there it adds 100 coins instead of 50...
i gues the problem in that function:
 func buyProduct() {
    print("buy +" + p.productIdentifier)

    var payment = SKMutablePayment(product: p)

    SKPaymentQueue.defaultQueue().addTransactionObserver(self)
    SKPaymentQueue.defaultQueue().addPayment(payment)

}

i also have :
 func productsRequest(request: SKProductsRequest, didReceiveResponse response: SKProductsResponse) {
    var myProduct = response.products
            for product in myProduct {
                list.append(product)
                print("product added")
                print(product.productIdentifier)
                print(product.localizedTitle)

            }
    print("list is \(list)")

}

func paymentQueue(queue: SKPaymentQueue, updatedTransactions transactions: [SKPaymentTransaction]) {
    print(transactions.count)
    for transaction in transactions {
        print(transaction.error)

        switch transaction.transactionState {
        case .Purchased:
            MBProgressHUD.hideAllHUDsForView(self.view, animated: true)
            print("buyed")
            print(p.productIdentifier)
            let prodID = p.productIdentifier

            switch prodID {
            case "com.addCoins" :
                print("increaing coinsCount")
                coinsCount = coinsCount + 50
                let userDefaults = NSUserDefaults.standardUserDefaults()
                userDefaults.setInteger(coinsCount, forKey: "coins")
                userDefaults.synchronize() // don't forget this!!!!
                coinsLabel.text = String(coinsCount)
            default: print("IAD not setuped")
            }

            print("premium added")
            queue.finishTransaction(transaction)
            break
        case .Failed:
            MBProgressHUD.hideAllHUDsForView(self.view, animated: true)
            print("buy error")
            queue.finishTransaction(transaction)
            break
        default: break
        }
    }
}

im calling purchase with:
for product in list {
                        let loadingNotification = MBProgressHUD.showHUDAddedTo(self.view, animated: true)
                        loadingNotification.mode = MBProgressHUDMode.Indeterminate
                        loadingNotification.labelText = "Loading"

                        let prodID = product.productIdentifier
                        if prodID == "com.addCoins" {
                            p = product
                            buyProduct()
                            break
                        }

                    }

Comment: Read the [In-App Purchasing Programming Guide](https://developer.apple.com/library/ios/documentation/NetworkingInternet/Conceptual/StoreKitGuide/Introduction.html#//apple_ref/doc/uid/TP40008267). It tells you how to properly handle all of this.
Answer: At some point you have to tell Apple that a purchase has been carried out and you delivered the goods. Until then, the purchases stay in the transaction queue forever.
Comment: so how could i do it?
Comment: i've tryed to add SKPaymentQueue.defaultQueue().finishTransaction(transaction as SKPaymentTransaction) but nothing changes
Answer: Its bad practice to add
 SKPaymentQueue.defaultQueue().addTransactionObserver(self)

everytime you buy something. You should add the transaction observer at app launch and remove it when your app is closed, as per apples recommended guidelines.
Also you dont need to call synchronise for your userDefaults anymore since iOS 8, yet I still see a lot of people doing it.
In regards to you problem  the code seems to be ok. The only thing I noticed so far is why in the buy function are you adding a SKMutablePayment?
Try changing SKMutablePayment to SKPayment and see if it makes a difference.
  func buyProduct() {
print("buy +" + p.productIdentifier)

var payment = SKPayment(product: p)

SKPaymentQueue.defaultQueue().addTransactionObserver(self) // should not be here
SKPaymentQueue.defaultQueue().addPayment(payment)
}


Delete pointer to 2d array

Question: I have a pointer to a 2d array of Robot class
Robot ***rob;

And below is my code for the constructor. The constructor works fine, but now I am trying to build a destructor to delete this pointer and it keeps on crashing the program!
My question is, how can I delete the pointer to the 2d array of robots?
RobotsWorld::RobotsWorld(int x , int y)
{
    X=x;Y=y; // returns the limitation of the matrix
    rob = new Robot**[x];
    for(int i = 0; i < x; i++)
    {
        rob[i] = new Robot*[y];

        for(int j = 0; j < y; j++)
        {
            rob[i][j] = NULL;
        }
    }
}

Comment: you are doing one of the most dangerous things that you can do with a pointer, setting it to NULL when you are thinking about deleting it; you probably want to adopt the smart pointers and save yourself a lot of troubles.
Comment: you're settings the pointer to null, not deleting it.
Answer: // Code is not tested
for(int i = 0 ; i < x ; ++i)
{
    for(int j = 0 ; j < y ; ++j)
    {
        delete rob[i][j];
    }
    delete[] rob[i];
}
delete[] rob;

By the way, why do you set rob[i][j] = NULL; ?
I think it should be : rob[i][j] = new double;
Comment: i tried doing that , but the program still crashes , when it enters the delete[] rob[i][j];  while the value is null it is cool , otherwise it crash :(

Delete pointer to 2d array


Geometric interpretation of connection forms, torsion forms, curvature forms, etc

Question: I have just begun learning about the connection 1-forms, torsion 2-forms, and curvature 2-forms in the context of Riemannian manifolds.  However, I am finding it hard to relate these notions to any sort of geometric intuition.
How can one interpret these differential forms geometrically?  Or at least, what is the motivation for considering such objects?  What sort of information do they provide?
Edit: I should clarify that I think I have somewhat of an intuition for connections, the curvature tensor, and (to a lesser extent) the torsion tensor.  What I am asking about are the connection forms, torsion forms, and curvature forms.
Comment: I'm treating part of this in my bachelors thesis, focussing on the geometrical intuition. Have a look at: http://enigmage.de/bachelor.pdf
Comment: Relevant: http://mathoverflow.net/questions/61878/geometric-interpretation-of-cartans-structure-equations
Answer: Almost seventeen months later, I think I found the answers I was looking for in Barrett O'Neill's Elementary Differential Geometry.
Since O'Neill explains things better than I can, I'm going to paraphrase excerpts of his text -- nearly quoting verbatim -- modifying some notation and terminology to fit my own (such is differential geometry!).  In short, I make zero claims of originality.
Note: Since the treatment is "elementary," O'Neill works in $\mathbb{R}^3$.
Connection $1$-forms

The power of the Frenet-Serret formulas stems from the fact that they express the derivatives $T', N', B'$ in terms of $T, N, B$ -- and thereby define curvature and torsion.  The connection $1$-forms do the same thing, expressing the covariant derivatives of a local frame in terms of the vector fields themselves.
Let $\{E_i\}$ be a local orthonormal frame.  The definition $$\omega^j_i(X) = \langle \nabla_X E_i, E_j \rangle$$ shows that $\omega^j_i(X)$ is the initial rate at which $E_i$ rotates toward $E_j$ as a point moves in the $X$ direction.
The connection equations $\nabla_{X}E_i = \omega^j_i(X)E_j$ give information about the "rate of rotation" of the local orthonormal frame $\{E_i\}$.

The Cartan Structure Equations in $\mathbb{R}^3$

In $\mathbb{R}^3$, Cartan's first structure equation reads
  $$d\phi^j = \phi^i \wedge \omega^j_i,$$
  where $\{\phi^i\}$ is the dual coframe to $\{E_i\}$.  This equation may be recognized as the dual of the connection equations $\nabla_{X}E_i = \omega^j_i(X)E_j$.
In $\mathbb{R}^3$, Cartan's second structure equation reads
  $$d\omega^j_i = \omega^k_i \wedge \omega^j_k.$$
  These equations show that $\mathbb{R}^3$ is flat.

Surfaces in $\mathbb{R}^3$

Let $M \subset \mathbb{R}^3$ be an isometrically immersed surface.  We let $\{E_1, E_2, N\}$ denote a local orthonormal frame for $\mathbb{R}^3$ that has $N$ normal to $M$.  Thus, if $\{\phi^1, \phi^2, \phi^3\}$ denotes the dual coframe, then $\phi^3|_M = 0$.
Taking $E_i = N$ in the connection equations $\nabla_X E_i = \omega^j_i(X)E_j$  shows that $$-\nabla_XN = \omega^3_1(X)E_1 + \omega^3_2(X)E_2.$$
  By definition, the term on the left-hand side is the shape operator $S(X) = -\nabla_XN$.  Thus, we interpret the connection $1$-forms as follows:

$\omega^2_1$ -- Gives the rate of rotation of $\{E_1, E_2\}$
$\omega^3_1$ and $\omega^3_2$ -- Describes the shape operator

Cartan's second structure equation in $\mathbb{R}^3$ then implies the Gauss-Codazzi equations:
  $$\begin{align*}
d\omega^2_1 & = \omega^3_2 \wedge \omega^3_1 \ \text{ (Gauss equation)} \\
d\omega^3_1 & = \omega^2_1 \wedge \omega^3_2 \ \text{ (Codazzi)} \\
d\omega^3_2 & = \omega^1_2 \wedge \omega^3_1 \ \text{ (Codazzi)}
\end{align*}$$
By analogy with the formula $S(X) \times S(Y) = K\,(X \times Y)$, where $K$ is the Gaussian curvature, one can prove that
  $$\omega^3_1 \wedge \omega^3_2 = K\,\phi^1 \wedge \phi^2.$$
  Together with the Gauss equation, this implies Cartan's second structure equation for $M$:
  $$d\omega^2_1 = -K\,\phi^1 \wedge \phi^2.$$
Answer: For starters, a connection on a manifold is all about parallel transport of tangent vectors. Think about a surface embedded in three dimensional space and a curve on that surface. Fix a point and a vector at this point that is tangent to the surface.
In $\mathbb{R}^3$ there is an intuitive sense of parallel transport of this vector along the curve (which I won't explain, unless you want me to). If you parallel transport a vector along a curve on the surface from a point $p_1$ to a point $p_2$ in this sense, then the vector at point $p_2$ won't necessarily be tangent to the surface anymore.
This means that while there is a canonical way of parallel transport for tangent vectors in $\mathbb{R}^n$, there isn't one for manifolds. This is where the connection comes in: Specifying a connection on a surface (or more generally on a manifold) is the same as saying how to project the vector at the point $p_2$ to the tangent space of the point $p_2$. Or, to rephrase it: How to transport a tangent vector along a curve in a way that the transported vector is still a tangent vector. This kind of transport is then the "parallel transport with respect to the specified connection".
The curvature measures how much the parallel transport on the surface deviates from the parallel transport in the ambient $\mathbb{R}^3$.
Torsion is a little bit more involved: It measures how "tangent vectors rotate" when they are parallel transported.
Let's say you fix a point $p$ and two tangent vectors $\vec{v}$ and $\vec{u}$ at p. What happens if you parallel transport $\vec{v}$ into the direction of $\vec{u}$ of by an  "infinitesimal amount $\epsilon$" and compare this to the result of transporting $\vec{u}$  into the direction of $\vec{v}$ by an "infinitesimal amount $\epsilon$"?
If the torsion is zero, then the tips of  $\vec{v}$ and $\vec{u}$ will touch up to an error of $\epsilon^3$.
It is not that easy to make these intuitive ideas precise and to relate them to the usual definitions, but I can recommend a nice book where this is explained in more detail:

John Baez, Javier Muniain: "Gauge Fields, Knots and Gravity"
Comment: (Re: there isn't one for manifolds) Well, in fact, [there is](http://en.wikipedia.org/wiki/Levi-Civita_connection) (for Riemannian manifolds, I mean)
Comment: Thank you for your answer, though I realize that I might not have been clear.  I've edited the question accordingly.
Answer: Check out Kock's Synthetic Geometry of Manifolds for a nice geometric description of connection forms, curvature forms, and torsion in terms of parallel transport. My mathoverflow answer here gives an explanation of torsion from this point of view.
I'll give a run down for how to intuitively think of the connection form. Let $\nabla$ be a choice of connection (i.e. a parallel transport map) in a bundle $E \to M$. If $x$ and $y$ are infinitesimally close points (to first order, technically) in $M$ and $u$ is in the fibre $E_x$, then we can transport $u$ along the (horizontal lift of) the infinitesimal line segment linking $x$ to $y$ to get an element $\nabla(x,y)u$ in the fibre $E_y$.
In other words, for any pair of infinitesimal neighbours $x, y \in M$ we have a map $$\nabla(x,y): E_x \to E_y.$$
We just require that $\nabla(x,x) = \text{id}_{E_x}$.
If the bundle $E$ has some extra structure, we often want the parallel transport to preserve that structure. For example, for a vector bundle we probably want the maps $\nabla(x,y)$ to be linear, and for a $G$-principal bundle we probably want the maps to be $G$-equivariant. This gives us the notion of a linear connection, and a principal connection, respectively.
Now, lets see where connection forms come in. Say we have a connection $\nabla$ on a (right) $G$-principal bundle $p: P \to M$. We don't need it to be $G$-equivariant, but that would obviously be nice. Anyway, if $u$ and $v$ are infinitesimal neighbours in $P$, then we can project down to $M$ to get a pair of infinitesimal neighbours $p(u)$ and $p(v)$. Let's transport $u$ to the fibre containing $v$ along the corresponding infinitesimal curve to get the element $\nabla(p(u), p(v))u$ which lies in the same fibre as $v$. But the action of $G$ on $P$ is simply transitive, so there is a unique element of $\omega(u,v) \in G$ such that
$$v.\omega(u,v) = \nabla(p(u), p(v))u.$$
The $\omega$ here is just the connection form!
But wait, you might ask, why does $\omega$ take a pair of infinitesimally close points in $P$ as arguments rather than a tangent vector to $P$, and why does it have values in $G$ rather than the lie algebra $\frak{g}$? Well, the answer to the first question should be obvious: if two points in $P$ are infinitesimally close (to first order), they lie on a tangent vector to $P$. The answer to the second question is that $\omega(u,v)$ is always an infinitesimal neighbour of the group identity $e \in G$, so it lies on a tangent vector to $G$ at $e$, and hence an element of the lie algebra $\mathfrak{g}$.
If you draw out a picture of this situation you can see that the connection form is the "vertical part" of the parallel transport on a principal bundle.
It is easy to check that $G$-equivariance of a principal connection (transport map) is equivalent to the usual equivariance of the connection form (with respect to the principal and adjoint action) in this picture.
Now, to interpret the curvature, lets just think about any bundle $\pi: E \to M$ with connection $\nabla$. Let's use the notation $x \sim y$ to indicate that two points are infinitesimal neighbours. If we have three points $x,y,z \in M$ such that $x \sim y$, $y\sim z$ and $z\sim x$. These three define an infinitesimal 2-simplex in $M$. Lets consider the transport around (the boundary of) this simplex:
 $$R(x,y,z) = \nabla(z,x) \circ \nabla(y,z) \circ \nabla(x,y): E_x \to E_x$$
If we transport a point $w \in E_x$ around the simplex, we have no guarantee that we end up back where we started. This is precisely the notion of curvature. The curvature measures the extent to which parallel transport around infinitesimal 2-simplices deviates from the identity.
If $E$ is a vector bundle with a linear connection, then $R(x,y,z): E_x \to E_x$ is linear, as expected. If $E$ is a principal bundle, then we can use the same trick we used for the connection form to define the $\frak{g}$-valued curvature form $\Omega(x,y,z)$ from the the curvature $R$.
Comment: Basically, synthetic differential geometry takes inspiration from algebraic geometry, and takes place in a topos containing infinitesimal objects; The category of smooth manifolds embeds fully faithfully into this topos, so you can reason rigorously about smooth manifolds using infinitesimals like how physicists do. Two points are infinitesimal neighbours to first order if they lie on the same tangent vector, which is just an infinitesimal curve segment in SDG.
Comment: What does it mean (precisely) for two points $x,y \in M$ to be "infinitesimally close" or "close to first order"?


Can I swap parts from a new to old shutoff valve instead of soldering a new sweat valve?

Question: The shutoff valve on my water heater has an extremely slow leak. A couple years ago I disassembled it by removing the handle and changing out either the packing or the rubber washer, or maybe both (can't remember now), which did help, but sometime in the past few months it's started to leak slowly again.
Can I buy a new valve and just swap the circled area, or must I solder a complete sweat fitting. I've never soldered copper pipes before but I'm not afraid to give it a try.
Answer: Possibly, but only if the interior mating surfaces are in good condition.
Answer: You might be able to find a valve with interchangeable parts but I'd replace it with a quarter-turn ball valve. You can either sweat one on which is not a big deal or simply install one with shark bite connections which is easier still. I recently installed one on my hot water heater. I think the quarter-turn ball valve is more reliable and less prone to failure.
Comment: Every answer was good, however I'm just going to sweat a new quarter turn ball valve. I've been waiting for an excuse to learn how to sweat copper pipes anyways.
Answer: I expect it is the stem packing under the top small nut that is leaking. If so a pretty simple ,cheap fix. Turn off the water upstream of this valve. Back-off the small nut to see the stem . Wrap teflon pipe dope around the stem , several wraps , as many as you can get under the nut. Tighten the nut , the teflon is a seal and a lube so the nut can be pretty tight and still turn the stem.You can make it a nicer job by pulling the stem first and polishing with 400 grit, as needed, to remove any corrosion or roughness ; then proceed as above. An old refinery maintenance guy taught me that many decades ago, I have used it on several valves.
Comment: Use graphite or teflon string packing (should be got at any hardware store) rather than pipe dope...


How to execute .bat files using Finalbuilder?

Question: I am using Finalbuilder to build packages. I want to execute <code>.bat</code> using file content iterator. Can I use anything other than file content iterator to execute .bat files?
Answer: FinalBuilder has specific action, called Run DOS Command. And it is used to

...execute any native DOS command or batch file.
Answer: Which version of FinalBuilder are you using?
You can use the Execute Program action. The program file would be cmd.exe, the path to your batch file goes as parameter.
E.g.: cmd.exe /C script.bat


Add Character to field depending on state of check box

Question: I am using access 2007, on a form I have two text boxes and a check box.
I have a field named Quote ID and Qshipnum and then the check box IsShip?.
I currently have the VBA on the checkbox isship? as follows
Private Sub QshipNum_AfterUpdate()

If Me.IsShip_.Value = True Then Me.QshipNum.Value = "S" + Me.QuoteID.Value

End If

End Sub

I would like to make the value of QshipNum S + whatever the quoteID is if the check mark is true. But currently I can't pull the concatenation of the two fields.
What can I do to pull quote ID as well as the S?
Answer: Use & instead of +:
If Me.IsShip_.Value = True Then Me.QshipNum.Value = "S" & Me.QuoteID.Value


How are colors really mixed?

Question: I'm kind of stuck on this one. When following a conventional, high-level shading tutorial, you'll come across these images that are like ambient + diffuse + specular = result, but I can tell that it's not straight addition (otherwise the picture would seem overexposed).

What's the "formula" for mixing two rgb colors?
Answer: With an old-style Phong shader (as in your example), they really are just added together. Each of those things is a contribution to the overall amount of light, so they're just added together, the same way you add together the contribution from each light source.
Your intuition is right that you often end up with overexposed specular highlights with this style of shading. In a modern, physically-based pipeline, it's common to instead use an energy-conserving shader. The contributions of each layer (specular, clear-coat/lacquer, diffuse, subsurface) are still added together, but the amount of light in each layer reduces the input amount of light for the next layer. That is, if the surface is giving a strong specular reflection, it's reflecting most of the light, so less light is available for the diffuse layer. In the same way, any light that's reflected by the diffuse layer reduces the amount of light available for subsurface scattering.
Comment: You're conflating energy conservation, with light additivity, with the film's sensitivity function. You can have an energy conserving bsdf and still get "overexposed" images. The second paragraph of your answer is simply confusing in the context of the question and the "problem" of overexposure mentioned.
Answer: You are somewhat right: the rightmost image is not the sum of the three images to the left of it. It's easiest to see that the rightmost image doesn't even have the ambient contribution on the left-hand side of the central spheroid.
I've done an experiment with two modes of addition of the three images. In the resulting images below, on the LHS, with the label "Addition", is my result, on the RHS is the rightmost image from the OP.

Simple, naive addition — as if the images were in linear RGB space (and retaining the result in this space). Here's the result:

sRGB addition, i.e. the addition where we consider the images being in sRGB space (the default assumption on the web when no color profile is present), and so undo the sRGB gamma before actually adding color values, and apply it back afterwards. This will give the following result:

So, you can see that both ways of adding colors result in a sharp border from the ambient lighting contribution — the leftmost image in the OP, while the rightmost supposed result doesn't have such a border on some sides.
I'm not really sure how the rightmost "Phong Reflection" image was created. It may have been manipulated, e.g. some gamma adjustment or something like that. But in any case, in both ways of addition above the image didn't get overexposed as you supposed it would.
Comment: I thought about it a bit, maybe they multiplied the diffuse, added the rest, averaged it out.
Comment: @AnnoyinC well, in that case the product would be much darker.
Comment: Since the lit areas look identical in your result with addition vs. the reference image, but the shadow areas are darker in the latter, my guess is that they forgot to clamp the diffuse component to nonnegative values before performing the addition.
Comment: @Rahul that might be indeed. But why would they get negative values in the first place? From some dot product?
Comment: Yes, the diffuse component of illumination is $\max(n\cdot l,0)$ where $n$ is the surface normal and $l$ is the unit vector towards the light source. If you forget to do the $\max$, you get negative illumination on surfaces facing away from the light.

How are colors really mixed?


How to return values to a named range instead of using a range's Offset()

Question: Warning to the experts: I am a "pre-beginner" in vba...
I have a workbook that I am using to find attributes of a product based on its name. E.g. cell in named range "Album_Name" with value "My Favorite Things by John Coltrane" should return a value of "John Coltrane" in named range "Musician", a value of "Jazz" in named range "Music_genre" (offset from named range "Album_Name by 78 columns), etc.
I'm currently using this:
Sub UpdateAttributes()

    Dim c As Range
    Dim i As Integer
    Dim vezesQueEncontrouNumero As Integer
    Dim posicaoSegundoNumero As Integer

    For Each c In Range("Album_Name", Range("Album_Name ").End(xlDown))

    vezesQueEncontrouNumero = 0
    posicaoSegundoNumero = -1

    For i = 1 To Len(c)

        If IsNumeric(Mid(c, i + 1, 1)) Then
            vezesQueEncontrouNumero = vezesQueEncontrouNumero + 1
            If (vezesQueEncontrouNumero) = 2 Then
                posicaoSegundoNumero = i
            End If
        End If
    Next
**If InStr(UCase(c.Value), UCase("John Coltrane")) > 0 Then c.Offset(0, 78).Value = "Jazz"**

My question:
As the number of attributes is growing it gets more difficult to "c.Offset" by the correct number of columns. And as sometimes I must add columns in between, it really gets unworkable! Is there a way of putting c.Value in a named range instead of using Offset?
Thank you.

Update
After the help of @Luuklag , @wallyeye , @JvdV and - specially - @nwhaught I've rewrote my vba but still to no avail. I'm still missing something. The vba changes the value of the cell in the same column ("name") and not in the "Genre" or "Artist" column. (I did put "name" at A1, "Genre" at B1 and "Artist" at C1). Somehow the "attribution" of "colNum" isn't working.
    Sub UpdateProductAttributes()

    Dim colNum As Integer
    For colNum = 1 To 100 'or however many populated columns you end up having...
        Select Case Sheet1.Cells(1, colNum) 'Look at the column header
            Case "Genre" 'If you've found the "Genre" column
                genreColumn=colNum 'Give the genreColumn variable the correct value
            Case "Artist"
                artistColumn=colNum
        End Select
    Next

   Dim c As Range
    Dim i As Integer
    Dim vezesQueEncontrouNumero As Integer
    Dim posicaoSegundoNumero As Integer

    For Each c In Range("name", Range("name").End(xlDown))
    vezesQueEncontrouNumero = 0
    posicaoSegundoNumero = -1
        For i = 1 To Len(c)

            If IsNumeric(Mid(c, i + 1, 1)) Then
            vezesQueEncontrouNumero = vezesQueEncontrouNumero + 1

            If (vezesQueEncontrouNumero) = 2 Then
            posicaoSegundoNumero = i

            End If
            End If

    Next i

        If InStr(UCase(c.Value), UCase("Coltrane")) > 0 Then
            c.Offset(0, genreColumn).Value = "Jazz"

            ElseIf InStr(UCase(c.Value), UCase("Brad Spreadsheet")) > 0 Then
            c.Offset(0, genreColumn).Value = "Indie Folk Grunge"

        End If
        Next c
End Sub

What could be wrong?
Comment: When I have to program to specific columns like this, I set up specific column variables, then reference them in code. Depending on how dynamic the columns are, I'll make them constants or assign them by examining the headers at the start of the routine. I.e. colMCat = range.find("music category").column   Just shorthand here, not the specific syntax. As a side note, I hope you are maintaining a list of the cross references in a sheet somewhere, not just putting them in your code.  You are doing great for a pre-beginner!
Comment: use index match, to arrive at the appropriate column.
Comment: Thank you @Luuklag. Could you please provide an example/sample code? I've never used index match...
Comment: Something you could try implement is getting the column number through match as mentioned before. In this example the value has to be present `ColNum = Application.WorksheetFunction.Match(SearchValue, Sheets(1).Range("1:1"), 0)`
Comment: Commenting on edit: you've got your assignments backwards. Rather than colNum = genreColumn, it should be genreColumn=colNum. :-)
Comment: You are offsetting from c, but c won't be column zero. Instead use something like cells(c.row, genreColumn).value = ...
Comment: I would also like to reiterate, you shouldn't have your artists and genre names in code, they should be in a lookup table.  It gets unwieldy very quickly in code, and you cannot easily manipulate them.  I would have them on a second sheet, load them into an array and build a dictionary object.  Something like arrArtists = sheet2.range("a2:b99).value.  Set scpArtists= New scripting.dictionary   ScpArtists.comparemode = textcompare. For lngrow=lbound(arrArtists,1) to ubound(arrArtists,1).  ScpArtists.item(arrartists(lngrow,1))=lngrow. Next lngrow.  Then as you look through your data you can
Comment: Just say if ScpArtists.exists(c.value) then cells(c.row,genreColumn) = arrArtists(ScpArtists.item(c.value),2)
Comment: You have to set a reference to the Microsoft scripting runtime to use the dictionary object.
Comment: Thank you very much for your suggestions @wallyeye . I'm afraid your suggestions are too advanced for my current level of knowledge of vba. But I'll give it a go and try to figure out how to implement them.
Answer: To expand on some of the comments:
Index Match is a pattern that's generally used in in-cell formulas as a more-flexible companion to VLOOKUP.
It works like this: =INDEX(YourTotalRangeOfData,MATCH("YourSearchKey",TheColumnRangeOfYourSearchKey,0),TheNumberOfTheColumnInYourTotalRangeThatYouWantToReturn)
In practice, it looks like this: =INDEX(C3:E11,MATCH("Frantz",B3:B11,0),2)
In cells, Excel will keep track of the changes for you. In code, you'll continue to run into issues with changing column reference numbers.
wallyeye's comment about setting column variables is a good one, and you could do it like this:
Dim genreColumn as Integer
genreColumn = 78

**If InStr(UCase(c.Value), UCase("John Coltrane")) > 0 Then c.Offset(0, genreColumn).Value = "Jazz"**

Even better, in my opinion, would be to have a "setup" section that ran at the beginning of your code. The purpose of the setup section is to set all of your column variables for you. Something like:
Dim colNum as Integer
For colNum = 1 to 100 'or however many populated columns you end up having...
    Select Case Sheet1.Cells(1, colNum) 'Look at the column header
        Case "Genre" 'If you've found the "Genre" column
            genreColumn = colNum 'Give the genreColumn variable the correct value
        Case "Artist"
            artistColumn = colNum
    End Select
Next

Run that at the beginning of your code, and you'll never have to worry about the changing column position again. As long as you have the title of the column correct (which is much easier to check) you'll have the correct number.
Also, to echo what others have said, you're doing great. This doesn't look like the code of a "pre" beginner. :)
Comment: This seems to be an elegant solution @nwhaught!
Comment: I did as you said (or at least I think I did) @nwhaught but it doesn't seem to work. It changes the value of the cell in the same column. Somehow the "attribution" of "colNum" isn't working. I did put "name" at A1, "Genre" at B1 and "Artist" at C1.
Comment: Do some debugging to see what exactly is wrong. Put some breakpoints in the code in the select statement. Ctrl+g will pull up the "immediate window", and with the code paused you can try various things to see what your code is actually doing. For example: "?Sheet1.Cells(colNum, 1).value" will show exactly what's currently being tested in the select statement.
Comment: Oof. I feel silly. I mixed up my rows and columns...should be Cells(1, colNum). Editing my answer to reflect.
Comment: it still doesn't work... Do you think there might be any other problem?
Comment: I just copied the edited answer and tried it with "Genre" in A1 and "Artist" in B1, and did a debug.print genreColumn , which returned 1, and a debug.print artistColumn, which returned 2. That's what I'd expect. What are you seeing in your debugging?


Displaying TabLayout and fragments with ViewPager inside card view

Question: I want to display two fragments in a cardview, i was able to display tablayout but not the fragments, tried everything, help me as this might be simple I guess. I uploaded screenshot as well, as seen from the screenshot tablayout is displayed correctly but not the fragment below it
Code in the Activity.
 ....
     //Creating our pager adapter
            Pager adapter = new Pager(getSupportFragmentManager(), Titles, 2);
    ...
    viewPager = (ViewPager) findViewById(R.id.srviewpager);
            //Adding adapter to pager
            viewPager.setAdapter(adapter);

        final TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
        tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
        tabLayout.setupWithViewPager(viewPager);

..
public class Pager extends FragmentStatePagerAdapter {

        CharSequence Titles[]; // This will Store the Titles of the Tabs which are Going to be passed when ViewPagerAdapter is created
        int NumbOfTabs; // Store the number of tabs, this will also be passed when the ViewPagerAdapter is created
        private static final String TAG = "ViewPagerAdapter";

        // Build a Constructor and assign the passed Values to appropriate values in the class
        public Pager(FragmentManager fm, CharSequence mTitles[], int mNumbOfTabsumb) {
            super(fm);

            this.Titles = mTitles;
            this.NumbOfTabs = mNumbOfTabsumb;

        }

        //Overriding method getItem
        @Override
        public Fragment getItem(int position) {
            //Returning the current tabs
            switch (position) {
                case 0:
                    return new ShippingFragment();

                case 1:
                    return new ReturnsFragment();

            }
            return null;
        }

        // Overriden method getCount to get the number of tabs
        @Override
        public int getCount() {
            return NumbOfTabs;
        }
        @Override
        public CharSequence getPageTitle(int position) {
            return Titles[position];
        }
    }

this is my layout file, contains 3 cardview, the last cardview has to display two fragments, shipping and returns. So far I am able to display only tablayout with two tabs but not the fragments.
     <?xml version="1.0" encoding="utf-8"?>
        <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
            xmlns:cardview="http://schemas.android.com/apk/res-auto"
            xmlns:app="http://schemas.android.com/tools"
            android:layout_width="match_parent"
            android:layout_height="match_parent">

    <android.support.v7.widget.CardView
        android:id="@+id/description_cd"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_margin="8dp"
        cardview:cardCornerRadius="8dp"
        cardview:cardElevation="15dp"
        cardview:cardBackgroundColor="@color/cardview_light_background"
        cardview:contentPadding="2dp"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true">

    </android.support.v7.widget.CardView>

    <android.support.v7.widget.CardView
    android:id="@+id/features_cd"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    cardview:cardCornerRadius="8dp"
    cardview:cardElevation="15dp"
    cardview:cardBackgroundColor="@color/cardview_light_background"
    cardview:contentPadding="2dp"
        android:layout_below="@+id/description_cd"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="false"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="false"
        android:layout_margin="8dp">

    </android.support.v7.widget.CardView>

    <android.support.v7.widget.CardView
    android:id="@+id/sp_cd"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_gravity="center"
    cardview:cardCornerRadius="8dp"
    cardview:cardElevation="15dp"
    cardview:cardBackgroundColor="@color/cardview_light_background"
    cardview:contentPadding="2dp"
        android:layout_below="@+id/features_cd"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="false"
        android:layout_margin="8dp">

    <com.spoorthy.apsaratrendz.thirdpartyviews.RippleView
        android:id="@+id/shipping_payment_rpv"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        cardview:rv_color="@color/green"
        cardview:rv_type="rectangle"
        cardview:rv_rippleDuration="@integer/ripduration_rpv">

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="@string/shippingandreturns"
            android:id="@+id/textViewsp"
            android:layout_alignParentTop="true"
            android:singleLine="true"
            android:textSize="25sp"
            android:textStyle="bold"
            android:background="#FFFFFF"
            android:textColor="#d52e9e"
            android:inputType="text"
            android:padding="1dp"
            android:paddingEnd="1dp"
            android:paddingStart="1dp" />
        <android.support.design.widget.TabLayout
            android:id="@+id/tabs"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            app:tabMode="fixed"
            android:layout_below="@+id/textViewsp"/>
        <android.support.v4.view.ViewPager
        android:id="@+id/srviewpager"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
            android:layout_below="@+id/tabs"/>

    </com.spoorthy.apsaratrendz.thirdpartyviews.RippleView>

    </android.support.v7.widget.CardView>

    </RelativeLayout>

Here are my two fragment layouts
shippingfragment.xml
<?xml version="1.0" encoding="utf-8"?>
<com.spoorthy.apsaratrendz.thirdpartyviews.ReadMoreTextView
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/fragmentText"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textSize="25sp"
        android:textStyle="bold"
        android:text="@string/returns"
        android:layout_margin="4dp"
    android:padding="4dp" />

returnsfragment.xml
<?xml version="1.0" encoding="utf-8"?>
<com.spoorthy.apsaratrendz.thirdpartyviews.ReadMoreTextView
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/fragmentText"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textSize="25sp"
        android:textStyle="bold"
        android:text="@string/returns"
        android:layout_margin="4dp"
    android:padding="4dp" />

And my two fragment java files..
public class ReturnsFragment extends Fragment {

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View v = inflater.inflate(R.layout.returnsfragment, null);

        return v;
    }

}

public class ShippingFragment extends Fragment {

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View v = inflater.inflate(R.layout.shippingfragment, null);

        return v;
    }

}

Comment: what is the problem really
Comment: fragment with text is not showing
Comment: please display you output screen and point what you want to do @Ajax-theMax
Answer: Solved the problem by changing the CardView layout height to 350dp, instead of match_parent.
<android.support.v7.widget.CardView
android:id="@+id/sp_cd"
android:layout_width="match_parent"
android:layout_height="350dp".../>


"Monty hall"-esque marble selection problem driving me insane

Question:
The quiz and explanation is from Brilliant.com course "Exposing Misconceptions".
Summary of the problem:
Two random coins are flipped and put in a bag(without changing orientation).
One person draws a coin, it turns out to be heads.
Therefore, there could've been 3 cases:

heads, heads
heads, tails
tails, heads

among these 3 cases, since the first person took out heads, in 1 case head remains while the other 2 cases tail remains.
Therefore, it is more likely for the remaining coin to be tails (2/3)
The explanation seems to make sense... until it doesn't.
This basically means that one should be able to guess an outcome of a totally independent random function just by observing one of the samples.
To see if the probability of any remaining coin is really likely to be heads(66%) if one coin was tails, I ran the following code (javascript):
https://jsfiddle.net/novh5zc8/1/
function flip() {
    if (Math.random() > 0.5)
        return true // red
    else
        return false // blue
}

let correct = 0;

for (let i = 0; i < 1000; ++i) {
    let x = flip(); // red or blue
    let y = flip(); // red or blue
    if (flip()) { // choose one at random
        if (x) // if one is red, the other is apparently likely to be blue
            correct += y == false ? 1 : 0;
        else // if one is blue, the other is likely to be red
            correct += y == true ? 1 : 0;
    } else { // same as above
        if (y)
            correct += x == false ? 1 : 0;
        else
            correct += x == true ? 1 : 0;
    }
}

alert(correct);

// average outcome: 500 correct guesses (50%)

To no one's surprise, the fact that one random sample being red making the other remainder likely to be blue was incorrect.
However, the logical explanation from Brilliant.com looks very convincing.
Is their explanation correct, and is my code somehow different in architecture?
Or if their explanation is incorrect, what is the logical flaw?
Comment: This is a bit hard to follow...the image you post doesn't even appear to include a question.  And what is the mechanism by which the other person removes a ball?
 Do they take either ball randomly, with equal probability?  Do they seek a red ball?
 Clearly that matters....Why not rewrite the question and add it to the text?  Looks like a simple enough problem...no?
Comment: I note that you reference the Monty Hall problem, but in that case the selection of the exposed object is *not* at all random.  The analogy here would be if the other person prefers to select a red ball, examines both, and selects a red if one is available.  That is very, very different from a random selection.  If the selection was random, then you need to use Bayes' Theorem to recompute the probabilities for the contents.
Comment: As I say, the question can not be answered without knowing how the person is making their choice.  As with the Monty Hall problem, that mechanism is absolutely critical.
Comment: Note:  post edit, it doesn't make sense to put a "flipped coin" into a bag.  Once you put a coin in a bag, it loses its orientation.  Maybe you mean they covered the two coins with a piece of paper or something...or you could just stick with the blue/red balls as described in the image.
Comment: @lulu I apologize for a low quality question - I am not used to asking mathematical questions, I have edited the original question to be more specific. What I'm really asking for is either approval disapproval of the original claim that witnessing that someone pulled a red ball out of a random bag with 2 balls(independent) that was not restored, you can accurately guess what the remaining ball's color is.
Comment: This is the confusing aspect of the Monty Hall problem. The answer is 2/3 if the person who removes the ball gets to look in the bag and select a red one, thereby making a *nonrandom* choice. The answer is 1/2 if the person who removes the ball chooses randomly, *even if the ball he chooses randomly happens to be red*.
Comment: If the person chose the ball randomly, then the answer is $\frac 12$, as each ball is equally likely to be red or blue, independently of the other.  If the person selected the red ball intentionally, then it is $\frac 23$ for the reason given in the link.  the entire point of Monty Hall is that we can use the intent of the other person to derive information.  If the other person has no intent at all, then we can't get information from it.
Comment: Look at it this way:  suppose the other person's intent was to remove a blue ball.  That is, they looked at both balls and would have removed a blue one if there was one.  In that case, the fact that they removed a red one proves that the other one is also red.
Answer: To summarize the discussion in the comments:  the problem can not be answered as stated as we need to know the manner in which the removed red ball was selected.
If the person just took out one of the two randomly, with equal probability, independent of the colors, then the answer is $\frac 12$. Indeed, the probability that a red ball was selected is clearly $\frac 12$ in this scenario so Bayes tells us the a posteriori probability that the orginal contents of the bag were $RB$ or $BR$ is $$\frac {(1/2)\times (1/2)}{1/2}=\frac 12$$
(Informally:  each ball is red or blue with equal probability and independently of the other.  Knowing that a given ball is red tells you nothing about the other).
If, however, the person wanted to select a red ball...examined both balls with the intent of removing a red one...then the answer is $\frac 23$ for the reason given in the link.  Removing a red one rules out $BB$ as the original contents of the bag, but it doesn't distinguish between the other three cases.  It's as if the other looked at the contents and, when you asked them "is there at least one Red ball in there" they said "Yes".
(Informally:  the fact that the person chose not to remove the other ball is evidence that it is blue.  Not proof, but evidence).
Or, if the intent was to select a blue ball, then the fact that a red one was removed proves that the bag must contain $RR$, else the person would have extracted a blue one as they wanted.  So in that case the answer would be $0$.
(Informally, in this case the fact that the person chose not to remove the other ball is proof that it is red).
Other assumptions might well lead to even more possible answers, but I think these are three pretty natural sets of assumptions and, as you see, they yield three different answers.
Answer: A problem that is even more like this problem than the Monty Hall problem is the Boy or Girl Paradox or Two Daughters Problem: "If you know that someone has two children, and one of them is a girl, what is the probability of the other child being a girl?"  In fact, I am fairly confident that this was the inspiration for the problem presented here by Brilliant. com.  Many presentations of the Two Daughters Problem will argue (exactly like Brilliant.com does) that the probability should be $\frac{1}{3}$ rather than the intuitive $\frac{1}{2}$, thus suggesting that humans are not good with probability. And this is of course exactly what Brilliant.com is trying to do here: "See? You really need to take our course on probability to help you get better at thinking with probability!"
Unfortunately, all these three probability problems (Monty Hall, the 2 daughters, and the one presented by Brilliant.com here) suffer from not being clear in the problem statement. And that means that you get different answers depending on exactly what assumptions go into it.
@lulu points out some different scenarios, but frankly, I think the most 'natural' interpretation of what is going on in the scenario with the coins and the bag as described by Brilliant.com is that the other person simply randomly pulled out one of the coins without looking first themselves, and it turned out to be red. And with that assumption, you are absolutely correct: the chance of the other one being red is now simply $\frac{1}{2}$.
Indeed, I think Brilliant.com really screwed up here: to get to the $\frac{1}{3}$ in the original two daughter problem, you would need to know that 'at least one of the two children is a girl' .. and as I explain in my answer here, even that statement is ambiguous: If you are being shown one girl, and know there is some other child, we're back at $\frac{1}{2}$ ... and that's exactly what the scenario as described by Brilliant.com sounds like.
Answer: There is a key difference between the problem and your code, namely the following: The two coins are indistinguishable, in your code however the variables $x$ and $y$ very much are distinguishable. What you modeled in your code is the following problem:
A coin $x$ and a coin $y$ are being flipped. Then one of the coins, w.l.o.g. $x$, is being looked at and turns out to be heads. What is the probability that coin $y$ is heads/tails.
In that problem indeed the probability is 50:50, since the possible outcomes are the following
($x$: heads, $y$: heads),
($x$: heads, $y$: tails),
($x$: tails, $y$: heads),
($x$: tails, $y$: tails)
and after seing $x$ is heads this reduces to
($x$: heads, $y$: heads),
($x$: heads, $y$: tails)
so 50:50.
Note how the fact that $x$ and $y$ are distinguishable means, that there is one more option excluded, reducing them to only two.
In the problem with the coins however it is unclear which of the coins you look at, so there is an additional option remaining after you look at one of the coins.
Comment: To clarify: My answer is to your "summary of the problem", not to what is described in the picture.
Comment: I've come to the conclusion that the original explanation in the screenshot is wrong. The correct calculation of a blue ball probability should've been 1/2 (the first person drew a first ball, and it was red) * 1/2 (the second ball is either blue or red) + 1/2 (the first person drew a second ball, and it was red) * 1/2 (the first ball is either blue or red) = 50%.


Can an electrician with 16th edition rules do work in anybody's home?

Question: I did an elim course taking city and guilds for the 16th edition electrical installation and maintenance. Can I still do work in people's houses without having to give certificates the types of work?
I want to add or move sockets, lighting and install new consumer units. Can I do this without having to get a permit as well?
Comment: @isherwood 16th edition is the UK... 17th is actually the current version - 16th was blue, 17th is red/pinkish... They are actually the Wiring Regulations and a British Standard - first published back in 1887 or 1888 iirc
Comment: You'd want to tell us where you are. What's an "elim course"?
Answer:
You can do work in people's houses, but you must certify your work to the current (Eighteenth) Edition of the Wiring Regulations. This is a legal requirement under part P of the Building Regulations in England. (Wales and Scotland have similar provisions.) The Wiring Regulations require either a Minor Works Certificate, or a Design Installation and Test Certificate for all wiring work.
If you carry out notifiable work such as installing new circuits, working in a kitchen, or installing a new consumer unit, in a dwelling then you must either notify the work to Building Control or be a member of a self-certification scheme such as NICEIC, NAPIT etc.

If you notify the work to Building Control they may require the certificates to be completed by a person with a current qualification. If you wish to apply to be a member of a self-certification scheme they will require you to have current qualifications or to be supervised by a qualified supervisor.
Small jobs which are non-notificable must still be certificated by you to the current Regulations and the certificate supplied to the customer. Forms of certificates are prescribed by the regulations and samples are available from IET.
The above applies to dwellings (including outbuildings and gardens). If you are working in non-domestic buildings then the notification requirement does not apply, but the Electricity at Work Regulations do (they would apply to you as a worker, and to your client as a business) and they would require a person to be competent. Evidence of competence is your qualification. For some work a 16th Edition qualification may remain satisfactory evidence of competence, for others it will not. For example, the Eighteenth Edition requires consideration of surge protection in designing an installation, and requirements for RCDs to all sockets and all concealed wiring even in permitted zones has changed since 16th Edition expired in 2004.
Comment: Have to vote this up as it is the only answer which is referring to the relevant regulations...
Answer: This is going to depend on municipality in the US.   But the short answer is no.   Unless you are a certified electrician you usually cannot work on other people's stuff.
I have passed quite a few local electrical exams to work on my own houses but it is clear in every city I have taken one that this does not give me the right to do work for other people.   And in almost all cases there were limits to the work I was doing - most had a 3 circuit install max.
So you need to ask...
Now changing outlets and doing lighting, you can do these as a handiman but not as an electrician where you would be able to get a permit signed-off.
Comment: This is not the US and "municipality" is not relevant - the regulations in the UK are country-wide and the **only** body that can make changes are the Institute of electrical Engineers - which is why there are 17 editions (each of which have had updates over time).
Comment: Well, the OP failed to state where they were, so let's not jump on people for trying to help...
Comment: Got to upvote the op did not say where they where and @dmore did state that "in the U.S. , others agree should to help reverse the - as I have, 16 regulations sounds like some one that doesn't know anything at all about electrical work but IS referring to the 17 code,,  OOPS The 2017 national electric code the most adopted code on this planet! Or something similar that was adopted in 16.
Comment: I had to upvote. We're here to try and help.
Comment: @J.Raefield I made the comment to Isherwood before the answer was visible - may have been a server timing issue though.
Comment: @solar Mike the NEC is the most adopted electrical code on the planet. Sorry to hurt your feelings but fire departments do not change It & it is not just the USA that uses it (not all US states do) but other countries also use it. How many homes are under your code? In the us alone over 100,000,000 homes and add business and we add another 60,000,000 buildings and that's just on the mainland, an apprentice told me that a couple years back when we're reviewing his class work. This doesn't include the territory's and other countries that use it. Look at all the questions and where they are from.
Comment: @EdBeal biggest is not always best... so many examples...
Comment: @Ed Isn't the National Electric Code developed by the National Fire Protection Association? And the local governments base their codes on that? At least that is what is said on p200 from "Hospitality Facilities Management & Design 3rd ed... Only reference I have to hand...
Comment: @solar mike again you are wrong only 4 states in the IS have not adopted the NEC. So it is a national code as the name states.  Mexico, Columbia, Venezuela, and Costa Rica are other countries that have adopted the code.
Comment: Well I am glad a miss spell made your day we also have main breaker isolation required, our code is used by 5 countries  with major sections used in many others. The NEC code has been around since 1897 it is developed by ANSI / NFPA and is updated every 3 years.
Comment: @SolarMike " in the UK the distribution board has an ELCB that protects the whole installation" whole-house RCDs have been deprecated since 16th Edition and not permitted since 17th Edition


How do I add values to class objects then put them in an array?

Question: I'm trying to embed queries into the variables in the class.Like so:
    class FooBar{
        public $bar;
    }

    $result = array();

    $db = mysqli_connect("127.0.0.1", "foo", "foo", "Farm");
    $sql = "SELECT * FROM `Lot`;";
    $result = mysqli_query($db, $sql);

    while($row = mysqli_fetch_assoc($result)){
        $foo = new FooBar;
        $foo->$bar = $row["cow"];

        array_push($result, $foo);
    }

But when I print the array using print_r($result), I'm just getting this as an output:
Array( )

I was hoping to see the objects stored in the array.
Where did I go wrong? What should I be doing?
Answer: You're reusing the $result variable. It's an an array but you reuse it as a MySQLi resource.
Also $foo->$bar should be $foo->bar.
class FooBar{
    public $bar;
}

$result = array();

$db = mysqli_connect("127.0.0.1", "foo", "foo", "Farm");
$sql = "SELECT * FROM `Lot`;";
$query_result = mysqli_query($db, $sql);

while($row = mysqli_fetch_assoc($query_result)){
    $foo = new FooBar;
    $foo->bar = $row["cow"];

    array_push($result, $foo);
}

var_dump($result);

Comment: (facepalms) I should've paid attention. Thank you :)
Comment: I think PHP should give you a warning for trying to use a MySQLi resource as an array. Make sure you have your error level turned up in development.
Comment: I thought it wouldn't matter because I am storing the returned result in the array, not the MySQL query.


AWS JAVA LAMBDA on Cloudformation

Question: I am trying to create an empty Lambda via CF and I always see this error:  Properties validation failed for resource ldocarchiverLambda with message: #/Code: expected type: JSONObject, found: String
My Lambda looks this way, what is wrong here?
enter image description here
Comment: Please don't post images of code. It's trivial to copy/paste that into the question itself. See the reason here that you will get downvoted for posting images of code: http://idownvotedbecau.se/imageofcode
Answer: When using CloudFormation, please take the time to look at the documentation.
The structure you provide to Code looks like the following:

JSON
{
  "ImageUri" : String,
  "S3Bucket" : String,
  "S3Key" : String,
  "S3ObjectVersion" : String,
  "ZipFile" : String
}

YAML
  ImageUri: String
  S3Bucket: String
  S3Key: String
  S3ObjectVersion: String
  ZipFile: String

You don't provide a direct path to a local file. In your case you need to use the ZipFile property.
Comment: Hi. Zipfile option is not working with Java.
Comment: @Seba OK? So what isn't  working **exactly**? What is the error message or unexpected behavior you get? If  you want help on here you need to provide enough details for someone to help.
Comment: I am just telling that ZipFile property is not working with Java but working for example with Node. There are 2 ways to ref a code: 1. s3 bucket 2. zipfile and inline reference. I was trying to do it this way: Code: ../../target/file.jar. But when I am doing this way, there is an error -Code: expected type: JSONObject, found: String
Comment: That error has nothing to do with Java vs Node, and everything to do with the way you've formatted the CloudFormation template file. If you posted the actual error message, along with the file that is giving you the error now, someone might be able to help.
Answer: Code Property cannot be string. Try:
      Code:
        S3Bucket: my-bucket
        S3Key: function.zip

Comment: I don't want to use S3, is there another method? Also this syntax won't work with Java: Code:
        ZipFile:
Comment: No, there is no another way, just upload your function to s3 before deploying cloudformation
Comment: Using S3 is not a requirement.

AWS JAVA LAMBDA on Cloudformation


How to set up home network w/ fiber from street & unterminated Cat5e in garage

Question: I'm having gigabit Sonic Fiber installed soon in a newly purchased, remodeled house, and I need to figure out how best to configure my networking setup to distribute a wired (& wireless) connection throughout the house.

House has individual Cat5e jacks in several rooms (over 3 levels)
All the cable runs appear to end in the garage, coiled up unterminated in a white box
Fiber install location TBD, but probably into garage, near my unterminated cat5e cables
Previous owner had cable internet, which came into an interior (house) closet via Coax and was distributed wirelessly; same closet has a single Cat5e jack (leading to garage, I presume)

I need to prep cables & get the right equipment so that it's ready to test/use when the fiber installer comes, so I'd love any & all advice/suggestions on the best way to set up my network.
What I want to end up with:

Wired connections to all the rooms with jacks
Ability to connect multiple wired devices in some rooms (via switch plugged into wall?)
Wifi throughout house (3 levels), ideally via hard-wired routers in bridge mode
I do NOT want to use the wifi capability of the Sonic-provided gateway/modem (not least because it won't be powerful enough for the whole house from the garage). I want to use my own wifi devices (likely wired Eeros, unless you have a better suggestion)

My tentative plan:

Fiber drop to transition box to ONT in garage
ONT to Gateway (modem) in garage
Gateway(modem) to Eero (or other router??) - in garage
Eero (router) to Switch (garage)
Terminate & plug cat5e cables into Switch (garage)

In theory this should distribute wired connections to each jack in house, and I can attach additional Eeros and switches to jacks in the house to distribute further.
Questions:

I'm not a fan of putting all of my networking equipment (ONT, gateway, router, switch) in the garage. I'd prefer to have most (if not all) in the house, but I can't think of a way to get a wired connection inside and then back out again to all the cables dangling in the garage.
Does it even matter if I have all my networking equipment in an (insulated) garage? What's the best way to enclose/protect it?
Any suggested improvements or modifications to my plan above? (see attached diagram for tentative plan)

Thanks a million.
Comment: https://www.structuredhomewiring.com
Answer: Without knowing more details, your plan is reasonable. Network equipment in the garage is not ideal, but not terrible, especially if insulated. On the other hand, if you live in a hot climate, the heat in the summer will be terrible for the gear. Cold is much less of a problem, though extreme cold would be.
One minor change is to add a patch panel between the switch and the drops to the rooms. This allows you to punch down all of your cables, rather than terminate them with jacks by hand; punching down is much easier for the novice (and the extra cost is minimal). You then run short cables (you purchase, not make) between the patch panel and switch. See my answer to a similar question for more details about using a patch panel.
Depending on how the house is laid out, and how much slack there is in the unterminated cables, you could take the whole bundle and move it somewhere inside the house. If there's little slack, you may just move them to the other side of the wall they're currently on. All my network and CATV stuff is in the master closet for this reason.
Brand recommendations are off-topic here, so I won't comment about specific routers or equipment. As far as testing the network, you should just need the gateway connected to test the fiber install. The rest is on you and can be done later. A simple network tester (example only, not a recommendation) will verify all your punchdowns are made securely, though that won't verify gigabit speeds.
As for multiple wired devices in one room, yes, a small 4-8 port unmanaged switch will work just fine.
Comment: To test the fiber, just connect a laptop or desktop directly to the gateway and run speedtest. Test the cat5e runs separately, by transferring large files between two computers, for example
Comment: Thank you very much for the suggestions. I'm in San Francisco, so heat is rarely an issue. I'm mostly worried about moisture & dirt. I had considered a patch panel, but wasn't sure. After reading your answer I think I'll get one. I'll also need a larger enclosure to contain all the networking equipment. Unf. not enough cable slack to move indoors.

**Follow-up Q:** to test the fiber, should I just run a patch cord from gateway to each of the patch panel jacks & test 1 room at a time?
Also: how can I verify gigabit speeds in the cable runs?
Thanks!


C# Apply DateTimeKind to a DateTime object

Question: Given that DateTime.Kind is a get-only property, how do we assign DateTimeKind to a DateTime object that's born out of DateTime.Parse()?
<code>var dte = DateTime.Parse("01/01/2018 10:10:00");

Console.WriteLine("{0} | Kind: {1}", dte, dte.Kind.ToString());

// PRINTS: 1/1/2018 10:10:00 AM | Kind: Unspecified

dte = dte.ToLocalTime();

Console.WriteLine("{0} | Kind: {1}", dte, dte.Kind.ToString());

// PRINTS: 1/1/2018 6:10:00 PM | Kind: Local
// OK, the "Kind" is changed to "Local" which is what I'm trying to achieve
// however it also converted the time!!!
</code>
My question is how to apply Utc or Local "Kind" to the object dte without using dte.ToUniversal() or dte.ToLocal() because both method converts (or changes) the time
Comment: Consider passing `DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal` for UTC time or  `DateTimeStyles.AssumeLocal` for local time, to do this during the parsing phase rather than after parsing.
Answer: You should be able to create a new DateTime with the DateTimeKind you want, by using the parsed datetime, and a constructor that takes DateTimeKind, like the following:
msdn.microsoft.com/en-us/library/t882fzc6(v=vs.110).aspx
Comment: After my question was marked as duplicate, I found the answer (almost similar to your answer) from the link provided by Ivan Stoev. Thank you!