text:
Q: ATmega328p sine wave generator, frequency capping at 1200Hz
I'm currently implementing sinewave generator on ATmega328p (16MHz). My project is mostly based on this article https://makezine.com/projects/make-35/advanced-arduino-sound-synthesis/.
In brief, I have two timers. First one (pwm_timer) counts up from 0 to 255 and sets output pin based on value in OCR2A register, which is creating PWM signal. Second timer (sample_timer) uses interrupt (ISR) to change value of OCR2A. ISR occurs when timer value is the same as value in OCR1A register, after that, timer is set to zero.
So this is my code:
#include <avr/io.h>
#include <avr/interrupt.h>
#include <math.h>

/******** Sine wave parameters ********/
#define PI2 6.283185 // 2*PI saves calculation later
#define AMP 127 // Scaling factor for sine wave
#define OFFSET 128 // Offset shifts wave to all >0 values

/******** Lookup table ********/
#define LENGTH 256 // Length of the wave lookup table
uint8_t wave[LENGTH]; // Storage for waveform
static uint8_t index = 0; // Points to each table entry

/******** Functions ********/
static inline void populate_lookup_table(void);
static inline void setup_pwm_timer(void);
static inline void setup_sample_timer(void);

int main(void)
{
    populate_lookup_table();
    setup_pwm_timer();
    setup_sample_timer();

    while(1)
    {
        asm("NOP");
        asm("NOP");
        asm("NOP");
        asm("NOP");
        asm("NOP");
        asm("NOP");
        asm("NOP");
        asm("NOP");
    }
}

ISR(TIMER1_COMPA_vect) // Called when TCNT1 == OCR1A
{
     OCR2A = wave[++index]; // Update the PWM output
}

static inline void setup_pwm_timer()
{
    TCCR2A = 0;
    TCCR2B = 0;

    TCCR2A |= _BV(WGM21) | _BV(WGM20); // Set fast PWM mode
    TCCR2A |= _BV(COM2A1); // Clear OC2A on Compare Match, set at BOTTOM
    TCCR2B |= _BV(CS20); // No prescaling
    OCR2A = 127; // Initial value
    DDRB |= _BV(PB3); // OC2A as output (pin 11)
}

static inline void setup_sample_timer()
{
    TCCR1A = 0;
    TCCR1B = 0;
    TIMSK1 = 0;

    TCCR1B |= _BV(WGM12); // Set up in count-till-clear mode (CTC)
    TCCR1B |= _BV(CS10); // No prescaling
    TIMSK1 |= _BV(OCIE1A); // Enable output-compare interrupt
    OCR1A = 40; // Set frequency
    sei(); // Set global interrupt flag
}

static inline void populate_lookup_table()
{
    // Populate the waveform table with a sine wave
    int i;
    for (i=0; i<LENGTH; i++) // Step across wave table
    {
        float v = (AMP*sin((PI2/LENGTH)*i)); // Compute value
        wave[i] = (int)(v+OFFSET); // Store value as integer
    }
}

In theory, output signal frequency should be equal to this formula 16Mhz / (LOOKUP_TABLE_LENGTH * OCR1A). So for OCR1A = 100 we should obtain 625Hz sine wave. And this is true until ~1200Hz (OCR1A = 52). After that, regardless of value of OCR1A - output frequency stays the same. The question is why?
I think the problem lies in the execution time of ISR.
Is there any way to speed it up, maybe optimize the code? Maybe I should write it in assembly?
I know I can ramp up frequency by decreasing length of look up table but I really want to stay with 256 samples.
Side note.
I realize that adding some asm("NOP") into main loop increase frequency a little (1250Hz). Maybe this while(1) is quilty too?

Result of the code above.

Photo showing that sampling frequency is right (16000000 / 256 = 62500).
My microcontroller is "Arduino Nano3". IDE - Atmel Studio.
Thank you for your time.
Updates:

*

*I check frequency by using DSO Shell and speaker with spectrum analyzer.

*Decreasing value of resistance and capacitance add few hertz but it is negligible.

*Disassembly reveals that ISR is not simply MOV instruction.

    40: {
1f.92                PUSH R1        Push register on stack
0f.92                PUSH R0        Push register on stack
0f.b6                IN R0,0x3F     In from I/O location
0f.92                PUSH R0        Push register on stack
11.24                CLR R1     Clear Register
8f.93                PUSH R24       Push register on stack
ef.93                PUSH R30       Push register on stack
ff.93                PUSH R31       Push register on stack
    41:      OCR2A = wave[++index]; // Update the PWM output
e0.91.00.01          LDS R30,0x0100     Load direct from data space
ef.5f                SUBI R30,0xFF      Subtract immediate
e0.93.00.01          STS 0x0100,R30     Store direct to data space
f0.e0                LDI R31,0x00       Load immediate
ef.5f                SUBI R30,0xFF      Subtract immediate
fe.4f                SBCI R31,0xFE      Subtract immediate with carry
80.81                LDD R24,Z+0        Load indirect with displacement
80.93.b3.00          STS 0x00B3,R24     Store direct to data space
    42: }
ff.91                POP R31        Pop register from stack
ef.91                POP R30        Pop register from stack
8f.91                POP R24        Pop register from stack
0f.90                POP R0     Pop register from stack
0f.be                OUT 0x3F,R0        Out to I/O location
0f.90                POP R0     Pop register from stack
1f.90                POP R1     Pop register from stack
18.95                RETI       Interrupt return

A: For 1200hz and a 256 lookup table you have 16000000/(256*1200) = 52 cycles between interrupts.
If you count the steps in the interrupt ASM code you're at the rock bottom limit if not below.
In the main loop there is a jump that needs two cycles, if you add nop's the jump will occur less often , that's why you have the tiny improvement.
You can move the interrupt code into the main loop to spare some cycles ( down to three times less) because PUSH's and POP's are slower. Then use nop's to obtain the desired frequency. Disable any interrupt.
There is also one big limitation that is still there , how can you update a 256 step PWM after only 52 cycles? Even if you don't want to reduce the look-up table length many writings to PWM are actually ignored.
Since there is nothing you can do except the value update you might improvise a resistor DAC on the digital port.

A: Besides what @Dorian says, note that you are operating the PWM timer and the sampling timer at the same frequency. You have one PWM cycle every 256 CPU cycles. If you change the PWM duty cycle more frequently than every 256 CPU cycles, in fast PWM mode you will get glitches/distortions in the output.
To mitigate the problems, in a first step you could add a low-pass (RC) filter at the PWM output to create a sine-like signal of x Hz from a 50% PWM of x Hz, obviating the lookup table. Or use a higher frequency low-pass and reduce the lookup table to, say 4 or 8 entries, reducing the ISR frequency to 4 or 8x the output frequency (instead of 256x) and letting the filter smooth out the transitions between the steps.
As an alternative, you could look into the ATtiny2/4/85 chips which offer a "real" fast PWM off a timer running at up to 64MHz.


text:
Q: How do I verify a number is from a specific country, specific network company, and specific regional code I want to write a code that verifies a number is from a specific country. Let's say I just want to take numbers from the USA so that means the code will start with +1, and specific area or state so let's say 423 or from a specific network company. I need help with this

A: I would normally recommend
Googles libphonenumber
which I use myself, but as it's PHP this is their referred PHP clone
libphonenumber-for-php

redpajama_set_name: RedPajamaStackExchange


text:
Q: How I can remove repetition when dealing with incompatible types in an if/else? I have a method decode_message that has 2 implementations, one is for BufReader<Read> the other is BufReader<Read + Seek>. Specialisation is enabled.
if is_stdin {
    let mut reader = BufReader::with_capacity(1000, io::stdin());
    decode_message(reader)
} else {
    let filename = &args[1];
    let mut reader = BufReader::with_capacity(1000, File::open(filename).unwrap());
    decode_message(reader)
};

The code above works, but it is annoying that I have to repeat decode_message in each branch.

A: As far as your question shows, specialization is not the culprit, it's just the use of monomorphisms: the reader bindings defined in the two conditional scopes, given the definition of BufReader::new, will be different and cannot be assigned to the same binding. Each time a run-time condition leads to the divergence of value types, such as in this case, they will also lead to code routines that cannot be shared among them.
Of course, there is an exception to this: trait objects have their concrete type erased, and so a binding reader: BufReader<Box<Read>>, or even reader: Box<BufRead>, could hold any of the two readers in the conditional statements. However, the resulting code would likely not perform better, since it would induce a runtime cost from method resolution, and prevent some ahead-of-time optimizations.
Therefore, there is hardly a better way to do that than what you already have.
In fact, a good pattern here has already been applied in your example: you can use monomorphic functions to contain the remaining logic that diverged from monomorphism, until it converges to the same type. With it, you only have to repeat a decode_message() call instead of everything in it.


text:
Q: Typescript DefinitelyTyped compilation error TS1005 I believe I have the correct setup, but am struggling to get tsc to compile.
My repo branch is https://github.com/inosion/sample-atom-typescript-package/tree/add_react
I have the latest version(s) of typescript - but am not sure what I am doing wrong - node_modules/@types/prop-types/index.d.ts(12,46): error TS1005: ';' expected. etc
    ✔ ~/projects/internal/github.com/inosion/sample-atom-typescript-package [master|✚ 3]
    18:34 $ grep dependencies -A 10 package.json
      "dependencies": {
        "typescript": "2.3",
        "@types/atom":"*",
        "@types/react":"*",
        "@types/react-native":"*"
      }
    }
    ✔ ~/projects/internal/github.com/inosion/sample-atom-typescript-package [master|✚ 3]
    18:34 $ tsc --version
    Version 2.7.2
    ✔ ~/projects/internal/github.com/inosion/sample-atom-typescript-package [master|✚ 3]
    18:34 $ apm clean
    ✔ ~/projects/internal/github.com/inosion/sample-atom-typescript-package [master|✚ 3]
    18:34 $ tsc --project .
    node_modules/@types/prop-types/index.d.ts(12,46): error TS1005: ';' expected.
    node_modules/@types/prop-types/index.d.ts(12,75): error TS1005: ';' expected.
    node_modules/@types/prop-types/index.d.ts(12,99): error TS1005: ';' expected.
    node_modules/@types/prop-types/index.d.ts(14,54): error TS1005: ';' expected.
    node_modules/@types/prop-types/index.d.ts(14,78): error TS1005: ';' expected.
    node_modules/@types/prop-types/index.d.ts(14,81): error TS1109: Expression expected.
    node_modules/@types/prop-types/index.d.ts(14,97): error TS1109: Expression expected.
    node_modules/@types/prop-types/index.d.ts(14,122): error TS1005: ';' expected.
    node_modules/@types/prop-types/index.d.ts(14,130): error TS1128: Declaration or statement expected.
    node_modules/@types/prop-types/index.d.ts(14,138): error TS1005: ',' expected.
    node_modules/@types/prop-types/index.d.ts(27,48): error TS1005: ';' expected.
    node_modules/@types/prop-types/index.d.ts(27,49): error TS1109: Expression expected.
    node_modules/@types/prop-types/index.d.ts(27,50): error TS1109: Expression expected.
    node_modules/@types/prop-types/index.d.ts(27,68): error TS1005: '(' expected.
    node_modules/@types/prop-types/index.d.ts(27,69): error TS1005: ')' expected.
    node_modules/@types/prop-types/index.d.ts(29,30): error TS1005: ';' expected.
    node_modules/@types/prop-types/index.d.ts(29,54): error TS1005: ';' expected.
    node_modules/@types/prop-types/index.d.ts(29,57): error TS1109: Expression expected.
    node_modules/@types/react/index.d.ts(2293,27): error TS1005: ';' expected.
    node_modules/@types/react/index.d.ts(2294,14): error TS1005: ':' expected.
    node_modules/@types/react/index.d.ts(2294,28): error TS1005: ';' expected.
    node_modules/@types/react/index.d.ts(2295,9): error TS1109: Expression expected.
    node_modules/@types/react/index.d.ts(2296,9): error TS1005: '(' expected.
    node_modules/@types/react/index.d.ts(2297,9): error TS1005: '(' expected.
    node_modules/@types/react/index.d.ts(2298,5): error TS1005: '(' expected.
    node_modules/@types/react/index.d.ts(2298,12): error TS1005: ')' expected.
    node_modules/@types/react/index.d.ts(2310,49): error TS1005: ';' expected.
    node_modules/@types/react/index.d.ts(2310,76): error TS1005: ';' expected.
    node_modules/@types/react/index.d.ts(2310,99): error TS1005: ';' expected.
    node_modules/@types/react/index.d.ts(2311,13): error TS1128: Declaration or statement expected.
    node_modules/@types/react/index.d.ts(2312,13): error TS1005: '(' expected.
    node_modules/@types/react/index.d.ts(2312,17): error TS1005: ',' expected.
    node_modules/@types/react/index.d.ts(2312,44): error TS1005: ',' expected.
    node_modules/@types/react/index.d.ts(2312,45): error TS1005: ':' expected.
    node_modules/@types/react/index.d.ts(2314,17): error TS1005: '(' expected.
    node_modules/@types/react/index.d.ts(2314,21): error TS1005: ',' expected.
    node_modules/@types/react/index.d.ts(2314,51): error TS1005: ',' expected.
    node_modules/@types/react/index.d.ts(2314,52): error TS1005: ':' expected.
    node_modules/@types/react/index.d.ts(2316,21): error TS1005: '(' expected.
    node_modules/@types/react/index.d.ts(2316,24): error TS1005: ')' expected.

A: The first error you are getting is on a line with a conditional type (which was introduced in typescript 2.8) so this suggests you don't have the latest version (3.0 at the time of writing)
If you look at your output you will also clearly see:
18:34 $ tsc --version
Version 2.7.2

So the version being used is 2.7 which does not support the features used in the definitions.


text:
Q: Taking memory dump using C# I've got a System.Diagnostics.Process object. My C# program is monitoring it for some condition. When the condition is hit, I want to take a full memory dump of the Process.
What is the best way to achieve this?
Is there a way that is provided by the CLR?

A: Microsofts MSDN lists a code example on how to achieve this using C# code within your own application:
using System;
using System.Diagnostics;
using System.Linq;
using System.Runtime.InteropServices;
using System.Windows;
using System.Windows.Controls;

// !load \\ddelementary\autowatson\vsdbg\vsdbg.dll

namespace CreateMiniDump
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            this.Loaded += (ol, el) =>
            {
                IntPtr hFile = IntPtr.Zero;
                try
                {
                    if (IntPtr.Size == 4)
                    {
                        this.Title = "CreateMiniDump Running as 32 bit, creating 32 bit dumps";
                    }
                    else
                    {
                        this.Title = "CreateMiniDump Running as 64 bit, creating 64 bit dumps";
                    }
                    this.Height = 800;
                    this.Width = 800;
                    var sp = new StackPanel() { Orientation = Orientation.Vertical };
                    this.Content = sp;
                    var dumpFileName = System.IO.Path.Combine(
                              System.IO.Path.GetTempPath(),
                              "testdump.dmp");
                    var txtDumpFile = new TextBox()
                    {
                        Text = dumpFileName
                    };
                    sp.Children.Add(txtDumpFile);

                    var txtProcName = new TextBox()
                    {
                        ToolTip = "Process name without extension",
                        Text = "devenv"
                    };
                    sp.Children.Add(txtProcName);
                    var lstDumpType = new ListBox()
                    {
                        // allow multi select
                        SelectionMode = SelectionMode.Extended
                    };
                    lstDumpType.ItemsSource = Enum.GetValues(typeof(NativeMethods._MINIDUMP_TYPE));
                    // set initial value
                    // for a dump with memory info we want these:
                    foreach (var val in new[] {
                  NativeMethods._MINIDUMP_TYPE.MiniDumpWithFullMemory,
                  NativeMethods._MINIDUMP_TYPE.MiniDumpWithFullMemoryInfo,
                  NativeMethods._MINIDUMP_TYPE.MiniDumpWithHandleData,
                  NativeMethods._MINIDUMP_TYPE.MiniDumpWithThreadInfo
            })
                    {
                        var nval = (int)(Math.Log((int)val) / Math.Log(2)) + 1;
                        lstDumpType.SelectedItems.Add(
                                  lstDumpType.Items[nval]
                          );
                    }
                    sp.Children.Add(lstDumpType);

                    var btnGo = new Button()
                    {
                        Content = "_Create Dump",
                        Width = 200
                    };
                    sp.Children.Add(btnGo);
                    var txtStatus = new TextBox()
                    {
                        IsUndoEnabled = false,
                        VerticalScrollBarVisibility = ScrollBarVisibility.Auto,
                        MaxHeight = 400
                    };
                    sp.Children.Add(txtStatus);
                    btnGo.Click += (ob, eb) =>
                      {
                          try
                          {
                              var sw = new Stopwatch();
                              sw.Start();
                              dumpFileName = txtDumpFile.Text.Trim();
                              if (System.IO.File.Exists(dumpFileName))
                              {
                                  System.IO.File.Delete(dumpFileName);
                              }
                              hFile = NativeMethods.CreateFile(
                                dumpFileName,
                                NativeMethods.EFileAccess.GenericWrite,
                                NativeMethods.EFileShare.None,
                                lpSecurityAttributes: IntPtr.Zero,
                                dwCreationDisposition: NativeMethods.ECreationDisposition.CreateAlways,
                                dwFlagsAndAttributes: NativeMethods.EFileAttributes.Normal,
                                hTemplateFile: IntPtr.Zero
                              );
                              if (hFile == NativeMethods.INVALID_HANDLE_VALUE)
                              {
                                  var hr = Marshal.GetHRForLastWin32Error();
                                  var ex = Marshal.GetExceptionForHR(hr);
                                  throw ex;
                              }
                              NativeMethods._MINIDUMP_TYPE dumpType = NativeMethods._MINIDUMP_TYPE.MiniDumpNormal; // 0
                              foreach (var item in lstDumpType.SelectedItems)
                              {
                                  var dt = (NativeMethods._MINIDUMP_TYPE)item;
                                  dumpType |= dt;
                              }

                              var exceptInfo = new NativeMethods.MINIDUMP_EXCEPTION_INFORMATION();
                              var proc = Process.GetProcessesByName(
                                  txtProcName.Text.Trim()
                                  ).FirstOrDefault();

                              if (!proc.Is32BitProcess() && IntPtr.Size == 4)
                              {
                                  throw new InvalidOperationException(
                                    "Can't create 32 bit dump of 64 bit process"
                                    );
                              }

                              var result = NativeMethods.MiniDumpWriteDump(
                                        proc.Handle,
                                        proc.Id,
                                        hFile,
                                        dumpType,
                                        ref exceptInfo,
                                        UserStreamParam: IntPtr.Zero,
                                        CallbackParam: IntPtr.Zero
                                        );
                              if (result == false)
                              {
                                  var hr = Marshal.GetHRForLastWin32Error();
                                  var ex = Marshal.GetExceptionForHR(hr);
                                  throw ex;
                              }

                              txtStatus.Text = string.Format(
                                        "Dump Created. Pid= {0} {1}\r File size = {2:n0}\rElapsed = {3:n3}\r",
                                        proc.Id,
                                        dumpType,
                                        (new System.IO.FileInfo(dumpFileName)).Length,
                                        sw.Elapsed.TotalSeconds
                                        );
                          }
                          catch (Exception ex)
                          {
                              txtStatus.Text = ex.ToString();
                          }
                          finally
                          {
                              NativeMethods.CloseHandle(hFile);
                          }
                      };
                }
                catch (Exception ex)
                {
                    this.Content = ex.ToString();
                }
            };
        }
    }
    public static class ExtensionMethods
    {
        public static bool Is32BitProcess(this Process proc)
        {
            bool fIs32bit = false;
            // if we're runing on 32bit, default to true
            if (IntPtr.Size == 4)
            {
                fIs32bit = true;
            }
            bool fIsRunningUnderWow64 = false;
            // if machine is 32 bit then all procs are 32 bit
            if (NativeMethods.IsWow64Process(NativeMethods.GetCurrentProcess(), out fIsRunningUnderWow64)
                && fIsRunningUnderWow64)
            {
                // current OS is 64 bit
                if (NativeMethods.IsWow64Process(proc.Handle, out fIsRunningUnderWow64)
                      && fIsRunningUnderWow64)
                {
                    fIs32bit = true;
                }
                else
                {
                    fIs32bit = false;
                }
            }
            return fIs32bit;
        }
    }
    public static partial class NativeMethods
    {
        [DllImport("Dbghelp.dll")]
        public static extern bool MiniDumpWriteDump(
            IntPtr hProcess,
            int ProcessId,
            IntPtr hFile,
            _MINIDUMP_TYPE DumpType,
            ref MINIDUMP_EXCEPTION_INFORMATION ExceptionParam,
            IntPtr UserStreamParam,
            IntPtr CallbackParam
            );
        //https://msdn.microsoft.com/en-us/library/windows/desktop/ms680519%28v=vs.85%29.aspx?f=255&MSPPError=-2147217396
        [Flags]
        public enum _MINIDUMP_TYPE
        {
            MiniDumpNormal = 0x00000000,
            MiniDumpWithDataSegs = 0x00000001,
            MiniDumpWithFullMemory = 0x00000002,
            MiniDumpWithHandleData = 0x00000004,
            MiniDumpFilterMemory = 0x00000008,
            MiniDumpScanMemory = 0x00000010,
            MiniDumpWithUnloadedModules = 0x00000020,
            MiniDumpWithIndirectlyReferencedMemory = 0x00000040,
            MiniDumpFilterModulePaths = 0x00000080,
            MiniDumpWithProcessThreadData = 0x00000100,
            MiniDumpWithPrivateReadWriteMemory = 0x00000200,
            MiniDumpWithoutOptionalData = 0x00000400,
            MiniDumpWithFullMemoryInfo = 0x00000800,
            MiniDumpWithThreadInfo = 0x00001000,
            MiniDumpWithCodeSegs = 0x00002000,
            MiniDumpWithoutAuxiliaryState = 0x00004000,
            MiniDumpWithFullAuxiliaryState = 0x00008000,
            MiniDumpWithPrivateWriteCopyMemory = 0x00010000,
            MiniDumpIgnoreInaccessibleMemory = 0x00020000,
            MiniDumpWithTokenInformation = 0x00040000,
            MiniDumpWithModuleHeaders = 0x00080000,
            MiniDumpFilterTriage = 0x00100000,
            MiniDumpValidTypeFlags = 0x001fffff,
        };
        /*
         *
    https://msdn.microsoft.com/en-us/library/windows/desktop/bb513622(v=vs.85).aspx
    WER_DUMP_TYPE:
    WerDumpTypeHeapDump
        MiniDumpWithDataSegs
        MiniDumpWithProcessThreadData
        MiniDumpWithHandleData
        MiniDumpWithPrivateReadWriteMemory
        MiniDumpWithUnloadedModules
        MiniDumpWithFullMemoryInfo
        MiniDumpWithThreadInfo (Windows 7 and later)
        MiniDumpWithTokenInformation (Windows 7 and later)
        MiniDumpWithPrivateWriteCopyMemory
    WerDumpTypeMicroDump
        MiniDumpWithDataSegs
        MiniDumpWithUnloadedModules
        MiniDumpWithProcessThreadData
        MiniDumpWithoutOptionalData

    WerDumpTypeMiniDump
        MiniDumpWithDataSegs
        MiniDumpWithUnloadedModules
        MiniDumpWithProcessThreadData
        MiniDumpWithTokenInformation
         */

        [StructLayout(LayoutKind.Sequential, Pack = 4)]
        public struct MINIDUMP_EXCEPTION_INFORMATION
        {
            public uint ThreadId;
            public IntPtr ExceptionPointers;
            public int ClientPointers;
        }

        [DllImport("kernel32.dll",
          SetLastError = true,
          CharSet = CharSet.Auto)]
        public static extern IntPtr CreateFile(
                string lpFileName,
                EFileAccess dwDesiredAccess,
                EFileShare dwShareMode,
                IntPtr lpSecurityAttributes,
                ECreationDisposition dwCreationDisposition,
                EFileAttributes dwFlagsAndAttributes,
                IntPtr hTemplateFile
            );

        [DllImport("kernel32.dll",
          SetLastError = true)]
        [return: MarshalAs(UnmanagedType.Bool)]
        public static extern bool CloseHandle(IntPtr hObject);

        public static IntPtr INVALID_HANDLE_VALUE = new IntPtr(-1);
        [Flags]
        public enum EFileAccess : uint
        {
            //
            // Standart Section
            //

            AccessSystemSecurity = 0x1000000,   // AccessSystemAcl access type
            MaximumAllowed = 0x2000000,     // MaximumAllowed access type

            Delete = 0x10000,
            ReadControl = 0x20000,
            WriteDAC = 0x40000,
            WriteOwner = 0x80000,
            Synchronize = 0x100000,

            StandardRightsRequired = 0xF0000,
            StandardRightsRead = ReadControl,
            StandardRightsWrite = ReadControl,
            StandardRightsExecute = ReadControl,
            StandardRightsAll = 0x1F0000,
            SpecificRightsAll = 0xFFFF,

            FILE_READ_DATA = 0x0001,        // file & pipe
            FILE_LIST_DIRECTORY = 0x0001,       // directory
            FILE_WRITE_DATA = 0x0002,       // file & pipe
            FILE_ADD_FILE = 0x0002,         // directory
            FILE_APPEND_DATA = 0x0004,      // file
            FILE_ADD_SUBDIRECTORY = 0x0004,     // directory
            FILE_CREATE_PIPE_INSTANCE = 0x0004, // named pipe
            FILE_READ_EA = 0x0008,          // file & directory
            FILE_WRITE_EA = 0x0010,         // file & directory
            FILE_EXECUTE = 0x0020,          // file
            FILE_TRAVERSE = 0x0020,         // directory
            FILE_DELETE_CHILD = 0x0040,     // directory
            FILE_READ_ATTRIBUTES = 0x0080,      // all
            FILE_WRITE_ATTRIBUTES = 0x0100,     // all

            //
            // Generic Section
            //

            GenericRead = 0x80000000,
            GenericWrite = 0x40000000,
            GenericExecute = 0x20000000,
            GenericAll = 0x10000000,

            SPECIFIC_RIGHTS_ALL = 0x00FFFF,
            FILE_ALL_ACCESS =
            StandardRightsRequired |
            Synchronize |
            0x1FF,

            FILE_GENERIC_READ =
            StandardRightsRead |
            FILE_READ_DATA |
            FILE_READ_ATTRIBUTES |
            FILE_READ_EA |
            Synchronize,

            FILE_GENERIC_WRITE =
            StandardRightsWrite |
            FILE_WRITE_DATA |
            FILE_WRITE_ATTRIBUTES |
            FILE_WRITE_EA |
            FILE_APPEND_DATA |
            Synchronize,

            FILE_GENERIC_EXECUTE =
            StandardRightsExecute |
              FILE_READ_ATTRIBUTES |
              FILE_EXECUTE |
              Synchronize
        }

        [Flags]
        public enum EFileShare : uint
        {
            /// <summary>
            ///
            /// </summary>
            None = 0x00000000,
            /// <summary>
            /// Enables subsequent open operations on an object to request read access.
            /// Otherwise, other processes cannot open the object if they request read access.
            /// If this flag is not specified, but the object has been opened for read access, the function fails.
            /// </summary>
            Read = 0x00000001,
            /// <summary>
            /// Enables subsequent open operations on an object to request write access.
            /// Otherwise, other processes cannot open the object if they request write access.
            /// If this flag is not specified, but the object has been opened for write access, the function fails.
            /// </summary>
            Write = 0x00000002,
            /// <summary>
            /// Enables subsequent open operations on an object to request delete access.
            /// Otherwise, other processes cannot open the object if they request delete access.
            /// If this flag is not specified, but the object has been opened for delete access, the function fails.
            /// </summary>
            Delete = 0x00000004
        }

        public enum ECreationDisposition : uint
        {
            /// <summary>
            /// Creates a new file. The function fails if a specified file exists.
            /// </summary>
            New = 1,
            /// <summary>
            /// Creates a new file, always.
            /// If a file exists, the function overwrites the file, clears the existing attributes, combines the specified file attributes,
            /// and flags with FILE_ATTRIBUTE_ARCHIVE, but does not set the security descriptor that the SECURITY_ATTRIBUTES structure specifies.
            /// </summary>
            CreateAlways = 2,
            /// <summary>
            /// Opens a file. The function fails if the file does not exist.
            /// </summary>
            OpenExisting = 3,
            /// <summary>
            /// Opens a file, always.
            /// If a file does not exist, the function creates a file as if dwCreationDisposition is CREATE_NEW.
            /// </summary>
            OpenAlways = 4,
            /// <summary>
            /// Opens a file and truncates it so that its size is 0 (zero) bytes. The function fails if the file does not exist.
            /// The calling process must open the file with the GENERIC_WRITE access right.
            /// </summary>
            TruncateExisting = 5
        }

        [Flags]
        public enum EFileAttributes : uint
        {
            Readonly = 0x00000001,
            Hidden = 0x00000002,
            System = 0x00000004,
            Directory = 0x00000010,
            Archive = 0x00000020,
            Device = 0x00000040,
            Normal = 0x00000080,
            Temporary = 0x00000100,
            SparseFile = 0x00000200,
            ReparsePoint = 0x00000400,
            Compressed = 0x00000800,
            Offline = 0x00001000,
            NotContentIndexed = 0x00002000,
            Encrypted = 0x00004000,
            Write_Through = 0x80000000,
            Overlapped = 0x40000000,
            NoBuffering = 0x20000000,
            RandomAccess = 0x10000000,
            SequentialScan = 0x08000000,
            DeleteOnClose = 0x04000000,
            BackupSemantics = 0x02000000,
            PosixSemantics = 0x01000000,
            OpenReparsePoint = 0x00200000,
            OpenNoRecall = 0x00100000,
            FirstPipeInstance = 0x00080000
        }

        [DllImport("kernel32.dll", SetLastError = true, CallingConvention = CallingConvention.Winapi)]
        [return: MarshalAs(UnmanagedType.Bool)]
        public static extern bool IsWow64Process(
              [In] IntPtr hProcess,
              [Out, MarshalAs(UnmanagedType.Bool)] out bool wow64Process
              );
        [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        public static extern IntPtr GetCurrentProcess();
    }
}

A: You can try calling the C++ method from your C# code. Here's an example of how you would declare it:
    [DllImport("dbghelp.dll",
        EntryPoint = "MiniDumpWriteDump",
        CallingConvention = CallingConvention.StdCall,
        CharSet = CharSet.Unicode,
        ExactSpelling = true,
        SetLastError = true)]
    [return: MarshalAs(UnmanagedType.Bool)]
    public static extern bool MiniDumpWriteDump(
        IntPtr hProcess,
        uint processId,
        SafeHandle hFile,
        MINIDUMP_TYPE dumpType,
        IntPtr expParam,
        IntPtr userStreamParam,
        IntPtr callbackParam);

You can check out the code of this project for an example:
https://github.com/projectkudu/kudu/blob/master/Kudu.Core/Infrastructure/MiniDumpNativeMethods.cs
https://github.com/projectkudu/kudu/blob/2db563be679bb60656050ec3f04945086f07b360/Kudu.Core/Infrastructure/ProcessExtensions.cs

A: You could use ProcDump from Sysinternals and make your C# program call it when needed.
Process.Start("procdump " + otherProgramPID.ToString());


text:
Q: Flutter Dialogs do not inherit theme from context I always have to manually wrap the content of my AlertDialog with a Theme widget so that it can inherit the theme of the MaterialApp like this.
                       showDialog(
                        context: context,
                        builder: (BuildContext contextPopup) {
                          return Theme(
                            data: Theme.of(context),
                            child: AlertDialog(
                              content: Text('FONT TETST 2'),
                            ),
                          );
                        });

Question
How to make all dialog inherit the MaterialApp theme by default ? Things like fontFamily


text:
Q: At what sample size does the precision of estimate stabilise? Imagine I have a population of a known size (e.g., 100,000 voters), and I know they can only vote for A, B, C, D or E.
If a random sample of 100 voters are, e.g., A = 40%, B = 30%, C = 10%, D = 10%, E = 10%, when I incrementally increase my sample size to 200 people, count the votes, then 300, 400, etc (samples without replacement). What type of analysis can I use to determine which sample size is sufficient to say:
"For this population size (100,000) with 5 options (A, B, C, D, E), this sample size of x has a 95% probability of correctly detecting the winner (e.g, A > B)"
Once I can't use a power analysis without a H0-H1. Are there any other tests or metrics that look into how incremental sample sizes impact
variance accuracy? This might be used to inform me that after a certain point increasing the sample size is unlikely to change the reliability of my prediction.

A: Traditional power analysis is situated within the discovery (or lackthereof) of population parameters based on statistical significance, p = .05 (or some other alpha).
You are correct in saying that you don't really have an alternative hypothesis against which you are testing, so it isn't as straightforward to do a power analysis as in other situations when you are asking, "If there is an effect here, how often am I going to capture it?"
You are onto something in the latter part of your question when you say:

Are there any other tests or metrics that look into how incremental sample sizes impact variance accuracy? This might be used to inform me that after a certain point increasing the sample size is unlikely to change the reliability of my prediction.

Instead of power analysis, which does sample size planning to get a "significant" p-value, you are interested in precision of a parameter estimate.
There's a good paper, Schönbrodt, F. D., & Perugini, M. (2013). At what sample size do correlations stabilize? Journal of Research in Personality, 47, 609-612. doi:10.1016/j.jrp.2013.05.009, that examines sample size planning in the way you are looking at it (.pdf here: https://osf.io/5u6hv/).
They are looking at correlations, whereas you are interested in proportions, but the idea is the same. You could take a similar Monte Carlo approach by simulating different proportions (e.g., A = 40%, A = 75%, etc.) and doing different sample sizes and seeing when the standard errors start to plateau. That could give you the sample size at which you start to get diminishing returns in precision. So I think one way to get at your question is to think of it as looking for precision, not power.
In traditional power analyses (which could test a hypothesis like A < B), we don't really know the effect size, so we often (a) guess or (b) calculate it for many different effect sizes. This gives us an understanding of the range of effect sizes and what our power would be for each. You could also just do power for the smallest effect size you care about or, if you want to be safe, do it at the lower bound of previously-done research (http://journals.sagepub.com/doi/full/10.1177/1745691614528519).

A: You can, in a fairly straightforward fashion, run a number of power analysis calculations based on varying assumptions. For example, below is a figure where the effect size and a property of the ratio of people who had or didn't have a variable of interest were both varied.


text:
Q: Multiple actions were found that match the request:*** I am trying to call WEBAPI from postman .My AI method is post but when i execute it i get below given error

Multiple actions were found that match the request:***

Below is my Code:
webapi route.config
 public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        config.Routes.MapHttpRoute(
           name: "Api Default",
           routeTemplate: "api/{controller}/{method}/{id}",
           defaults: new { id = RouteParameter.Optional }
       );
        //config.Routes.MapHttpRoute(
        //    name: "DefaultApi",
        //    routeTemplate: "api/{controller}/{id}",
        //    defaults: new { id = RouteParameter.Optional }
        //);

        // Uncomment the following line of code to enable query support for actions with an IQueryable or IQueryable<T> return type.
        // To avoid processing unexpected or malicious queries, use the validation settings on QueryableAttribute to validate incoming queries.
        // For more information, visit http://go.microsoft.com/fwlink/?LinkId=279712.
        config.EnableQuerySupport();

        // To disable tracing in your application, please comment out or remove the following line of code
        // For more information, refer to: http://www.asp.net/web-api
        config.EnableSystemDiagnosticsTracing();
    }
}

APIController:
 public class MembershipController : ApiController
    {
      [System.Web.Http.ActionName("Upload")]
        public HttpResponseMessage Upload(string employeedetails)
        {
             `Some Code`
         }

      [System.Web.Http.ActionName("BulkUpload")]
 [System.Web.Http.HttpPost]
        public HttpResponseMessage BulkUpload(string employeedetails)
        {
                `Some Code`
         }
            [System.Web.Http.ActionName("Transfer")]
            public HttpResponseMessage Transfer(string employeedetails)
              {
                      `Some Code`
               }

         }

I am not getting whats going wrong method has different action name and route config is also fully qualified api url which contain controller method and id as optional parameter.To identify url this should be sufficient but it's not working.
Am i missing anything?

A: If this is RESTful API, you cannot have three HttpPost, unless you differentiate them by the URL slugs.
Easiest way is to use attribute route. E.g.
public class MembershipController : ApiController
{
    // POST api/Membership/data/Upload
    [Route("api/Membership/{employeedetails}/Upload")]
    [HttpPost]
    public HttpResponseMessage Upload(string employeedetails)
    {
        `Some Code`
    }

    // POST api/Membership/data/Bulk
    [Route("api/Membership/{employeedetails}/Bulk")]
    [HttpPost]
    public HttpResponseMessage BulkUpload(string employeedetails)
    {
        `Some Code`
    }

    // POST api/Membership/data/Transfer
    [Route("api/Membership/{employeedetails}/Transfer")]
    [HttpPost]
    public HttpResponseMessage Transfer(string employeedetails)
    {
        `Some Code`
    }
}

A: Solution 1:
I have added Route Config in WebApiConfig class
 public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {

   config.Routes.MapHttpRoute(
       name: "Membership",
       routeTemplate: "api/{controller}/{method}/{id}",
       defaults: new { id = RouteParameter.Optional }
   );
    config.Routes.MapHttpRoute(
       name: "Api Default",
       routeTemplate: "api/{controller}/{method}/{id}",
       defaults: new { id = RouteParameter.Optional }
   );
    //config.Routes.MapHttpRoute(
    //    name: "DefaultApi",
    //    routeTemplate: "api/{controller}/{id}",
    //    defaults: new { id = RouteParameter.Optional }
    //);

    // Uncomment the following line of code to enable query support for actions with an IQueryable or IQueryable<T> return type.
    // To avoid processing unexpected or malicious queries, use the validation settings on QueryableAttribute to validate incoming queries.
    // For more information, visit http://go.microsoft.com/fwlink/?LinkId=279712.
    config.EnableQuerySupport();

    // To disable tracing in your application, please comment out or remove the following line of code
    // For more information, refer to: http://www.asp.net/web-api
    config.EnableSystemDiagnosticsTracing();
}

}
Solution 2
public class MembershipController : ApiController
{
  [System.Web.Http.ActionName("Upload")]
    public HttpResponseMessage Upload([FromBody]string employeedetails)
    {
         `Some Code`
     }
[System.Web.Http.HttpRoute("api/membeship/BulkUpload")]
 [System.Web.Http.HttpPost]
        public HttpResponseMessage BulkUpload(string employeedetails)
        {
                `Some Code`
         }
[System.Web.Http.HttpRoute("api/membeship/Transfer")]
            public HttpResponseMessage Transfer([FromBody]string employeedetails)
              {
                      `Some Code`
               }

         }

If we compare Solution 1 and solution 2 then  Solution 1 will work but it need a query string parameter where as sollution 2 will also work for post parameters(FormBody)
I am looking in details what does solution 2 makes a difference. Because when we remove HTTPRoute From solution 2 then it's also need query string parameter only and if we try to pass parameter using post then it get passed as null value. Very soon i will find it out and will share detail analysis on stack overflow.
Happy Coding


text:
Q: Scraping with R, how to extract var require(httr)
require(XML)
basePage <- "http://bet.hkjc.com/"
h <- handle(basePage)
GET(handle = h)
res <- GET(handle = h, path = "racing/pages/odds_wp.aspx?date=27-09-2017&venue=HV&raceno=2")
resXML <- htmlParse(content(res, as = "text"))

I used the above code to scrape a aspx. website. It returned with a bunch of text. However I am interested only in getting "var infoDivideByRace", "var scratchList". May I ask how do I extract these two variables and turn them into column data? thanks! some of the returns are as follows:
var poolSellStatus = '1@@@@@@;WIN;PLA;W-P;QIN;QPL;QQP;TRI;DBL;TCE;F-F;QTT;CWA;'.split('@@@');
var poolSellStatus_bak = '1@@@@@@;WIN;PLA;W-P;QIN;QPL;QQP;TRI;DBL;TCE;F-F;QTT;CWA;'.split('@@@');
var winOddsByRace = '175852@@@@@@WIN;1=3.6=1;2=4.7=0;3=43=0;4=11=0;5=29=0;6=9.4=0;7=4.6=0;8=11=0;9=52=0;10=82=0;11=52=0;12=8.6=0#PLA;1=1.4=1;2=2.0=0;3=6.0=0;4=3.5=0;5=6.2=0;6=2.6=0;7=2.0=0;8=4.2=0;9=7.9=0;10=11=0;11=8.4=0;12=2.5=0'.split('@@@');
var multiRacePoolsStr = '@@@DBL#;1,2;2,3;3,4;4,5;5,6;6,7;7,8@@@TBL#;6,7,8@@@D-T#;3,4;6,7@@@T-T#;4,5,6@@@6UP#;3,4,5,6,7,8';
var fieldSize = 'HV;12;12;12;12;12;12;12;12';
var fieldSizeWithReserve = 'HV;12;12;12;12;12;12;12;12';
var reserveList = 'HV';
var scratchList = 'HV';

A: The easiest or the most appropriate way is to use Phantomjs or selenium. If not, Regex and rvest work around.
library(rvest)

basePage <- "http://bet.hkjc.com/"

ss <- paste0(basePage,path)

path = "racing/pages/odds_wp.aspx?date=27-09-2017&venue=HV&raceno=2"

scripts <- read_html(ss, encoding = 'utf8') %>%
    html_nodes("script") %>% html_text(trim=TRUE)

new <- scripts[grepl('var scratchList =|var infoDivideByRace = ',scripts)]

value1 <- str_replace_all(strsplit(str_extract(new,regex('var scratchList = (.*?);')), split=' ')[[1]][4],";|'",'')
value2 <- str_replace_all(strsplit(str_extract(new,regex('var infoDivideByRace = (.*?);')),split=' ')[[1]][4],";|'",'')

value1
#[1] "HV"

value2

A: Alternate option using the V8 package:
library(rvest)
library(stringi)
library(purrr)
library(V8)

Get the page content you specified:
pg <- read_html("http://bet.hkjc.com/racing/pages/odds_wp.aspx?date=27-09-2017&venue=HV&raceno=2", encoding = "UTF-8")

Extract script tags that contain your target variables, convert the script tag to text, split into a character vector, keep only the var lines:
html_nodes(pg, xpath=".//script[contains(., 'infoDivideByRace')]") %>%
  html_text() %>%
  stri_split_lines() %>%
  flatten_chr() %>%
  keep(stri_detect_regex, "^var") -> script_txt

Initialise the V8 javascript engine:
ctx <- v8()

Let it parse the javascript and create the data:
ctx$eval(script_txt)

Retrieve the data (infoDivideByRace has 2 blank array elements so we ignore them):
grep("^$", ctx$get('infoDivideByRace'), value=TRUE, invert=TRUE)
## [1] STACKOVERFLOW'S SPAM PROTECTION WON'T LET ME PASTE THIS CONTENT

ctx$get('scratchList')
[1] "HV"


text:
Q: Grouping the Ordered data  What is the best way to display group data?
Currently in my controller I have:
@items = Item.order("group_name")

Then in my view I can iterate through it:
- @items.each do |item|
  %p= item.name

What would be the cleanest and most efficient approach to produce something like this:
Group Name 1

Item 1

Item 2

Group Name 2

Item 1

A: I think the group_by method does what you're looking for. There's a pretty nice overview here: http://railscasts.com/episodes/29-group-by-month

A: Controller
@items = Item.sanitized_and_ordered

Model
class Item <<  ActiveRecord::Base
scope :ordered_group ,order('group_name')

class << self
   def sanitized_and_ordered
      ordered_group.group_by {|item| item.group_name}
   end
 end
end

View
- @items.each_pair do |key,value|
  %p= key
   - value.each do |item|
      %p= item.name


text:
Q: Does the magnitude of centripetal acceleration always stay the same? I'm in ap physics 1 and currently learning uniform circular motion. Does the magnitude of centripetal acceleration always stay the same even in a vertical circular motion?
Thanks!

A: If the speed of the motion is constant, then yes, the centripetal acceleration is constant. Otherwise, the centripetal acceleration changes according to
$$a_c = \frac{v^2}{r}$$
where $a_c$ is the centripetal acceleration, $v$ is the current speed, and $r$ is the radius of the circular motion.
However, in vertical circular motion where the only forces are gravity and rope tension (like a ball on a rope), then keeping a constant speed is impossible. At the point where the rope is horizontal and the ball's motion is vertical, there is no force to counteract gravity, so the ball will be speeding up or slowing down.

A: Does $a_c$ stay constant
Short answer: It depends.
The centripetal acceleration is given by
$$a_c=\dfrac{v^2}{r}.$$
For an object to be in circular motion, the radius $r$ will be constant -- that is obvious. Therefore, for $a_c$ to not remain constant, $v$ must not remain constant. i.e. the object is either speeding up or slowing down.
Therefore, $a_c$ will also be constant if and only if the speed $v$ is also constant. This is referred to as Uniform Circular Motion.
When the speed changes (that is, $v$ changes and so there is tangential acceleration i.e. speeding up/slowing down), then $a_c$ must also change. This is obvious by looking at the formula above. When the speed changes, then centripetal acceleration cannot be constant. This is known as Non-uniform Circular Motion.
Does $a_c$ stay constant in vertical motion
Again, it depends.
Scenario 1. Consider (as stated by @Mark H), a ball on a rope undergoing vertical circular motion. Since the only force that affects the speed of the ball is gravity, then as the ball goes up, it gains gravitational potential energy and thus slows down. (why does tension not affect the speed? because tension in this case is always perpendicular to the velocity. you will learn that if a force is perpendicular to the velocity, that force will not change the speed, only the direction of velocity). Anyway, moral of the story is: the $a_c$ a ball attached to a string spinning around in a vertical circle will not be constant, because the speed $v$ changes.
Scenario 2. Ferris wheel. A person sitting in a Ferris wheel can go around at constant speed (due to the normal forces external on the person by the Ferris). In this case, $a_c$ will be constant.
For your course, you must be able to identify when the speed is and isn't constant, which will tell you whether or not $a_c$ is constant.
Hope this long answer helps.


text:
Q: All Usernames in a specific Role in Lotus Notes I need to get all the username of a specific role so that I would be able to send a mail to all user's who has that role access. How would I able to accomplish this task?
I saw this link,
How do I get all users who have a specified role?
Is there no other way to get all the valid username that can be used in the SendTo? Without having this problem? Though I didn't try the NotesACL. I am new in Lotus Notes Development.

A: If you have a bit influence how ACL entries are look like then you should be able to achieve a good solution. Following code collects all entries in ACL with the certain role and accepts only those entries which are of type Person or Person group.
Function GetRoleMembers(roleName As String) As String
    Dim session As New NotesSession
    Dim db As NotesDatabase
    Dim acl As NotesACL
    Dim entry As NotesACLEntry
    Dim sMembers As String
    Set db = session.CurrentDatabase
    Set acl = db.ACL
    sMembers = ""
    Set entry = acl.GetFirstEntry
    While Not ( entry Is Nothing )
        If entry.IsRoleEnabled( roleName ) And entry.IsPerson Then
            sMembers = sMembers + entry.Name & ","
        End If
        Set entry = acl.GetNextEntry( entry )
    Wend
    GetRoleMembers = sMembers
End Function

The Function returns a comma separated list of all persons and groups with given role. You can test this function with
Print GetRoleMembers("[Test]")

Make sure that users whom you want to send emails are assigned to type Person or Person group. You can set user's type in ACL


text:
Q: data is missing from text files I am using notepad to edit my php files on my desktop, and then suddenly, due to power loss, system restarted. After logging in, every file is not having any data. But, file's  size is same as before (i.e 22kb). could anyone explain this behavior ?
thanks in advance.


text:
Q: Count prime number till N This code works fine to count prime number till n. The problem is when n value is large like 1000000 or more, then it takes long time to execute and print the output (more than 30 secs.). I want to fix this issue. Any help would be great. Below is the code:
public class PrimeNotillN {

        public static void main(String[] args) {

            int n = 1000;
            int count = 0;

            for (int i = 2; i < n; i++) {
                boolean res = checkprime(i);
                if (res == true)
                    count++;
            }
            System.out.println("total prime number till " + n + " is " + count);
        }

        private static boolean checkprime(int n) {
            if (n == 1)
                return false;
            else {
                for (int i = 2; i <= n / 2; i++) {
                    if (n % i == 0) {

                        return false;
                    }
                }

                return true;
            }
        }
    }

A: The easiest change to make is to end the for loop in checkprime after i has reached the square root of n.  The reason is that if you have found a factor greater than the square root of n, that implies that there was a factor less than the square root of n that should have been found already.
for (int i = 2; i <= Math.sqrt(n); i++) {

Additionally, if you need more speed, the best algorithm for printing all prime numbers up to a limit is the Sieve of Eratosthenes.  That involves replacing what you have.  You'll need an array in which you'll mark which numbers are composite.  Starting with 2, you will mark all multiples of 2 as composite.  Moving through the array, if you find a number that isn't marked composite, it's prime and you can print it.  With each prime you encounter, you will mark all of that prime's multiples as composite as well.

A: Sieve of Eratosthenes is a very famous and efficient algorithm to generate all small prime numbers up to around 1-10 million. This is an ancient algorithm given by  a Greek mathematician named Eratosthenes.
 public class CountPrimes {

  public static void main(String[] args) {
    System.out.println(countPrimes(1000000));
  }

  public static int countPrimes(int n) {
    boolean[] primes = new boolean[n +1];

    for(int i = 0 ; i <= n ; i++) {
        primes[i] = true;
    }

    primes[0] = false;
    primes[1] = false;

    for(int i = 2 ; i * i <= n ; i++) {
        if(primes[i]) {
            for(int j = i ; i * j <= n ; j++) {
                primes[j * i ] = false;
            }
        }
    }

    int primeCounts = 0;
    for(int i = 2 ; i <= n ; i++) {
        if(primes[i]) {
            primeCounts++;
        }
    }

    return primeCounts;
  }

}

A: Primes, other than 2, are never even.
Primes are only divisible by 1 and iteslef.
Also you can check up to it's sqrt.  If you find nothing by then then it's a prime.
        public bool IsPrime(double num)
    {
        bool isprime = true;
        double limit = Math.Sqrt(num);

        if (num % 2 == 0)
            return num == 2;

        if (num == 3 || num == 5 || num == 7)
            return true;

        for (int i = 3; i < limit; i++)
            if (num % 1 == 0)
                return false;

        return isprime;
    }

A: You can store found primes into list and make further checks only against them (Sieve of Eratosphenes):
import java.util.ArrayList;
import java.util.List;

public class PrimeNotillN {
    public static void main(String[] args) {
        int n = 1000000;
        int count = 0;
        List<Integer> primes = new ArrayList<>();

        for (int i = 2; i < n; i++) {
            boolean res = checkprime(primes, i);
            if (res) {
                count++;
                primes.add(i);
            }
        }
        System.out.println("total prime number till " + n + " is " + count);
    }

    private static boolean checkprime(List<Integer> primes, int n) {
        int fence = (int) Math.sqrt(n);
        for (int prime : primes) {
            if (n % prime == 0) {
                return false;
            }
            if (prime >= fence)
                break;
        }

        return true;
    }
}

A: Using the sieve of eratoshtenes approach and maintaining the cache of all prime numbers found
    public int countPrimes(int n) {
    if(n==0){
        return 0;
    }else{
        boolean[] isPrime=new boolean[n];
        for(int i=2;i<n;i++){
            isPrime[i]=true;
        }

        for(int i=2;i*i<n;i++){
           if(!isPrime[i]){
               continue;
           }
            for(int j=i*i;j<n;j+=i){
                isPrime[j]=false;
            }
        }

        int counter=0;
        for(int i=2;i<n;i++){
            if(isPrime[i]){
                counter++;
            }
        }

        return counter;

    }
}


text:
Q: ASP.NET bundle does not work when deployed (debug="false") In development bundling works as expected with uncombined and unminified files but after deploying a site with web.config set enable the bundles
<compilation debug="false" targetFramework="4.5" />

the result of get a request to a bundle may include a comment at the top similar to the following
/* Minification failed. Returning unminified contents.
.. errors like JS1002 or JSxxxx errors

In other cases no errors are thrown from minification but some javascripts fails to run or errors during execution.
What syntax in otherwise working javascript might cause this behavior after bundling?

A: One situation that can cause this is a single line comment // as the last line of a javascript file.  This will cause the next file appened to have at least the first line also commented out
if forexample you have a bundle
bundles.Add(New ScriptBundle("~/bundles/test").Include(
            "~/Scripts/adder.js",
            "~/Scripts/printer.js"))

adder.js
function adder(a, b) {
    return a + b;
}
//this is the adder.js

printer.js
printer = true;

if (printer) {
    alert("It works");
    document.getElementById("itWorked").textContent = "It worked";
}


text:
Q: Twilio click to call and gather digit I've developed a web that connect two persons into a call following this tutorial:
https://www.twilio.com/docs/tutorials/click-to-call-node-express
and everything is working fine.
Now I need to gather 1 digit of the callee in order to execute a command.
Reading the Twilio documentation it seems I can't use Gather until the Dial verb is over, but this way the call is closed and the callee can't digit anything.
I tried this without success, the dial works fine but the digits callback is never executed:
twimlResponse.say(
    'Please wait for the other person to join the call'
  );

  twimlResponse.dial({
    timeLimit: 30
  })
  twimlResponse.dial(to_number)

  const gather = twimlResponse.gather({
    input: 'dtmf',
    timeout: 30,
    numDigits: 1,
    action: url // the url is the callback that should handle the digit entered
  });

Is it a limitation of Twilio? any workaround or alternative call strategy?

A: I believe you need to send an url with the number you dial and have that URL respond with the TwiML you want to drive the interaction with the callee. From https://www.twilio.com/docs/api/twiml/number:

The 'url' attribute allows you to specify a url for a TwiML document
  that will run on the called party's end, after she answers, but before
  the parties are connected. You can use this TwiML to privately play or
  say information to the called party, or provide a chance to decline
  the phone call using <Gather> and <Hangup>.

So something like this:
const dial = twimlResponse.dial({
  timeLimit: 30
});
dial.number({
  url: urlToGather // respond to this URL with your <Gather> TwiML
}, to_number);


text:
Q: How to check if a date is within a week or month of another date In my program, I have dates stored in strings in the form of mm/dd/yyyy. The issue is, I need to know if it is within a week or month of another date.
For example, if I have 12/02/2019, I need an if statement that checks if that date is within 1 week of the computers current date, and another statement that checks if that date is within 1 month of the computers current date.
I am completely lost as to how you would go about doing this, is anyone able to help me?

A: The first thing we'll need to do is convert our string representation of a date into a DateTime object. The DateTime struct, like many other .NET objects, has a TryParse method that can be used to attempt to parse a string into an instance of the class. It returns a bool indicating success, and takes an out parameter that gets set to the converted value on success, or the default value for the type on failure.
Normally this could be used if the string you've specified matches the date format for the culture that your program is running in. But since you've stated that the string has a specific format, then we should use TryParseExact instead, which allows us to pass a format string. This may be necessary if your program is running on a machine whose culture defines dates in the format dd/MM/yyyy (to prevent the month and days from being swapped).
Here's a sample method that will return a DateTime from your input string:
public static DateTime GetDate(string input)
{
    DateTime result;

    if (!DateTime.TryParseExact(input, "MM/dd/yyyy", CultureInfo.CurrentCulture,
        DateTimeStyles.None, out result))
    {
        throw new FormatException("date must be in the format: 'MM/dd/yyyy'");
    }

    return result;
}

Next we can use the DateTime.Today property to get the current date, after which we can get the difference between the two using the Subtract method (which returns a TimeSpan representing the difference), and then compare the TotalDays property to 7 for a week. For months, we can use the AddMonths method to determine if the date is within a month from today.
For example:
public static bool IsWithinAWeekBeforeToday(string input)
{
    var date = GetDate(input);

    return date <= DateTime.Today &&
           DateTime.Today.Subtract(date).TotalDays <= 7;
}

public static bool IsWithinAMonthBeforeToday(string input)
{
    var date = GetDate(input);
    var lastMonth = DateTime.Today.AddMonths(-1);

    return date >= lastMonth &&
           date <= DateTime.Today;
}

A: Firstly, you will need to convert your string dates into DateTime objects, using the correct format as you are currently using mm/dd/yyyy:
string myStartDateString = "...";
string myEndDateString = "...";

DateTime startDate = DateTime.ParseExact(myStartDateString, "MM-dd-yyyy", System.Globalization.CultureInfo.InvariantCulture);

DateTime endDate = DateTime.ParseExact(myEndDateString, "MM-dd-yyyy", System.Globalization.CultureInfo.InvariantCulture);

Once you have made that conversion, it's simple arithmetic. Subtract your start date, from your end date and pull the Total Days property from the result.
int differenceInDays = (endDate - startDate).TotalDays;

From here you should be able to make your own calculations to match your criterea, such as "within a month" - do you see that as <30 days?
if(differenceInDays < 30)
{
    //Do Stuff
}


text:
Q: Подскажите в чем проблема (спутниковая навигация) RINEX OBS? В заголовке указано 7 значений, но у меня в файле их 9:
7    L1    L2    C1    P2    P1    S1    S2            # / TYPES OF OBSERV

16  2 24  0 52 15.0000000  0 1R09
 114945096.765 7  89401793.977 6  21540656.227    21540659.250    21540654.770
        45.200          37.300

A: 7 и 6- это информация о силе сигнала или вроде того, они не входят в заголовок


text:
Q: Swapping the sharing page twitter logo by text I would like to add a share link from my wordpress website to tweeter.
I found how to do it but, I would like to remove the twitter logo and add a simple text link.
So I removed the twitter class "twitter-share-button" but I can't retrieve informations into the twitter textbox...
Here is my code:
<a href="https://twitter.com/share" data-url="<?php the_permalink(); ?>" data-text="<?php the_title(); ?>" data-hashtags="hashtag" >THIS_TEXT_THAT_I_WANT_TO_DISPLAY and add all data content to the twitter text area

Thanks

A: You can build your own Twitter share URL. You don't need to include any javascript or the Twitter SDK, it's just an HTML link. More info on building your own at https://dev.twitter.com/docs/tweet-button, just scroll all the way to the bottom of the page. Try something like this for yourmarkup:
<a href="https://twitter.com/share?url=<?php the_permalink(); ?>&lang=en&text='<?php the_title(); ?>' via @yourtwitterhandle&conturl=<?php the_permalink(); ?>&count=vertical" target="_blank">Tweet this

There are a lot of things you can pass into the url, so you can tweak this to get the result you're looking for.

A: Here is the result code:
<a href="https://twitter.com/share?url=<?php the_permalink(); ?>&lang=en&text='<?php the_title(); ?>'+via+@twitteraccount+:+Check+this+out+<?php the_permalink(); ?>&target="_blank">Tweet this


text:
Q: How to fill a nullable integer column and convert it into a serial primary key in Postgresql? My table contains an integer column (gid) which is nullable:
 gid | value
-------------
  0  |   a
     |   b
  1  |   c
  2  |   d
     |   e

Now I would like to change the gid column into a SERIAL primary key column. That means filling up the empty slots with new integers. The existing integers must remain in place. So the result should look like:
 gid | value
-------------
  0  |   a
  3  |   b
  1  |   c
  2  |   d
  4  |   e

I just can't figure out the right SQL command for doing the transformation. Code sample would be appreciated...

A: A serial is "just" a column that takes it default value from a sequence.
Assuming your table is named n1000 then the following will do what you want.
The first thing you need to do is to create that sequence:
create sequence n1000_gid_seq;

Then  you need to make that the "default" for the column:
alter table n1000 alter column gid set default nextval('n1000_gid_seq');

To truly create a "serial" you also need to tell the sequence that it is associated with the column:
alter sequence n1000_gid_seq owned by n1000.gid;

Then you need to advance the sequence so that the next value doesn't collide with the existing values:
select setval('n1000_gid_seq', (select max(gid) from n1000), true);

And finally you need to update the missing values in the table:
update n1000
  set gid = nextval('n1000_gid_seq')
where gid is null;

Once this is done, you can define the column as the PK:
alter table n1000
   add constraint pk_n1000
   primary key (gid);

And of course if you have turned off autocommit you need to commit all this.


text:
Q: Find object in json array Using javascript I am trying to find the index of an object containing (From:) inside a JSON array
so I did a recursive function to find the From: text and i used Lodash and FindIndex function but it is not working as expected and it is always returning -1
My code:
    // item is the actual object in the json array
   // arr is the parent holding item
  // mdfdoc is the whole json array
 static handleText(item, mdfdoc, arr) {
    try {
        let theText = item.type === "text" ? item.text : item.content.text
        if (theText && theText.replace(/\s/g, '') != "") {
                if (theText === "From:") {
                    const index = _.findIndex(mdfdoc, arr);
                    console.log(index);
                }
        }
    }
    catch(ex){console.log(ex)}
}

object:
{
  "type": "paragraph",
  "content": [
    {
      "type": "text",
      "text": "From:",
      "marks": [
        {
          "type": "strong"
        }
      ]
    },
    {
      "type": "text",
      "text": " Bassem Alameddine <bassem.alameddine@test.com> "
    },
    {
      "type": "hardBreak"
    },
    {
      "type": "text",
      "text": "Sent:",
      "marks": [
        {
          "type": "strong"
        }
      ]
    },
    {
      "type": "text",
      "text": " Tuesday, August 2, 2022 12:28 PM"
    },
    {
      "type": "hardBreak"
    },
    {
      "type": "text",
      "text": "To:",
      "marks": [
        {
          "type": "strong"
        }
      ]
    },
    {
      "type": "text",
      "text": " Bassem Alameddine <bassem.alameddine@test.com>"
    },
    {
      "type": "hardBreak"
    },
    {
      "type": "text",
      "text": "Subject:",
      "marks": [
        {
          "type": "strong"
        }
      ]
    }
  ]
},

Full Array:
{
  "type": "doc",
  "version": 1,
  "content": [
{
  "type": "paragraph",
  "content": [
    {
      "type": "text",
      "text": "Testing",
      "marks": [
        {
          "type": "em"
        },
        {
          "type": "strong"
        }
      ]
    }
  ]
},
{
  "type": "paragraph",
  "content": [
    {
      "type": "text",
      "text": "dadas",
      "marks": [
        {
          "type": "em"
        },
        {
          "type": "strong"
        },
        {
          "type": "textColor",
          "attrs": {
            "color": "#ff0000"
          }
        }
      ]
    }
  ]
},
{
  "type": "paragraph",
  "content": [
    {
      "type": "text",
      "text": " "
    }
  ]
},
{
  "type": "paragraph",
  "content": [
    {
      "type": "text",
      "text": "From:",
      "marks": [
        {
          "type": "strong"
        }
      ]
    },
    {
      "type": "text",
      "text": " Bassem Alameddine <bassem.alameddine@test.com> "
    },
    {
      "type": "hardBreak"
    },
    {
      "type": "text",
      "text": "Sent:",
      "marks": [
        {
          "type": "strong"
        }
      ]
    },
    {
      "type": "text",
      "text": " Tuesday, August 2, 2022 12:28 PM"
    },
    {
      "type": "hardBreak"
    },
    {
      "type": "text",
      "text": "To:",
      "marks": [
        {
          "type": "strong"
        }
      ]
    },
    {
      "type": "text",
      "text": " Bassem Alameddine <bassem.alameddine@test.com>"
    },
    {
      "type": "hardBreak"
    },
    {
      "type": "text",
      "text": "Subject:",
      "marks": [
        {
          "type": "strong"
        }
      ]
    }
  ]
},
{
  "type": "paragraph",
  "content": [
    {
      "type": "text",
      "text": " "
    }
  ]
}
{
  "type": "paragraph",
  "content": [
    {
      "type": "text",
      "text": " "
    }
  ]
},
{
  "type": "paragraph",
  "content": [
    {
      "type": "text",
      "text": " "
    }
  ]
}
 ]
}

A: use this function it will search you the key if it is in object
function searchIndexByKey(arr, key){
 var re = -1;
    for(var p=0;p<arr.length;p++){
    var obj = arr[p];
    var res= searchObjectByKey(obj, key, p);
    if(res>=0){
      re = res;
      break;
    }
  }
  if(re>=0){
    return re;
  }else{
   return -1;
  }
}

function searchObjectByKey(obj, k, index) {

for (var key in obj) {
    var value = obj[key];

    if (k == key) {
      return index;
      break;
    }

    if (typeof(value) === "object" && !Array.isArray(value)) {
      var y = searchObjectByKey(value, k, index);
      if (y && y[0] == k) return y;
    }
    if (Array.isArray(value)) {

      for (var i = 0; i < value.length; ++i) {
        var x = searchObjectByKey(value[i], k, index);
        if (x && x[0] == k) return x;
      }
    }
  }
  return -1;
}

var arr = [
{
  "type": "doc",
  "version": 1,
},
{
  "type1": "doc",
  "version1": 1,
}];

console.log(searchIndexByKey(arr,'type'));

A: // if more than one index occurs it will return an array of indexes
const isTextHasFrom = (text) => text === "From:";
const getArrayOfIndex = (acc, item, index) => {
  const getText = item.type === "text" ? item.text : item?.content;
  if (typeof getText === "string") {
    if (isTextHasFrom(getText)) {
      acc.push(index);
    }
  } else {
    if (item.content.some(({ text }) => isTextHasFrom(text))) {
      acc.push(index);
    }
  }
  return acc;
};

const indexes = data.reduce(getArrayOfIndex, []);
console.log(indexes);

A: I wrote simple recurssive function that return firstIndex that has From:
const findFromArr = (obj, index = 0) => {
    if (obj.type === "text") {
        return obj.text.includes("From:") ? index : false
    } else {
        const index = obj.content.findIndex((obj, index) => {
            const result = findFromArr(obj, index)
            return result
        })
        return index;
    }

}

you can simply your whole json to this function.


text:
Q: Sliding Tab layout not working in Pre - Lollipop Devices but working fine in Lollipop Devices I am using SlidingTabLayout,its working fine in Lollipop devices but when I m trying to run in pre-lollipop devices its showing an error
"android.view.InflateException: Binary XML file line #2: Error inflating class
            at android.view.LayoutInflater.createView"
But I have made another Project having same codes, in that SlidingTabLayout is working fine in both lollipop and pre-lollipop devices.
I m not getting whats the prob, same code but not working.
Please help me.
This is the XML layout code of the custom layout for the Tab.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
       android:id="@+id/tabContainer"
       android:layout_width="match_parent"
       android:layout_height="match_parent"
       android:padding="8dp"
       android:background="@drawable/tab_bg"
       android:orientation="vertical">

<ImageView
    android:id="@+id/tabImage"
    android:layout_gravity="center"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" />

<TextView
    android:id="@+id/tabText"
    android:gravity="bottom|center"
    android:textSize="14sp"
    android:padding="4dp"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" />

</LinearLayout>


text:
Q: Python Discord bot send text instead of emoji I'm making a simple code that sends an emoji if the message starts with nails:
if message.content.startswith('nails'):
    await message.channel.send('<:nails:843081338818789406>')

However, the bot only responds :nails:, instead of the actual emoji:

A: if message.content.startswith('nails'):
    emoji = bot.get_emoji(843081338818789406)
    await message.channel.send(emoji)


text:
Q: Webpack is taking 30 seconds to compile I'm using a webpack on the development, I'm not sure what is wrong with my webpack configuration as it is taking too much of time even if I make a single line of change in my code. When I start the app it takes 30 seconds to start and it continues to take the same time in all my subsequent changes.
Here is my webpack file

var webpack = require('webpack');
var path = require('path');
module.exports = {
    entry: {
        login: './js/login.js',
        progress_page: './js/react_progress_bar.js',
        home: './js/home.js',
        new_design_landing: './js/design_landing.js',
        onboarding_preview: './js/preview.js',
        popup_message: './js/message.js'
    },
    output: {
        filename: '[name].js',
        //chunkFilename: 'modern_theme_[name].[hash].chunk.js',
        path: path.resolve(__dirname, 'dist'),
        publicPath: 'http://localhost:5050/'
    },
    module: {
        rules: [{
                test: /\.js$/,
                exclude: /node_modules/,
                use: {
                    loader: "babel-loader"
                }
            },
            {
                test: /\.css$/,
                use: [{
                        loader: 'style-loader'
                    },
                    {
                        loader: 'css-loader',
                        options: {
                            //modules: true,
                            modules: {
                                // CSS name which we want to keep we can also
                                // change it to something like this [name]-[local]--[hash:base64:5]
                                localIdentName: '[name]',
                            },
                            url: false
                        }
                    }
                ]
            },
            {
                test: /\.scss$/,
                use: [{
                        loader: 'style-loader'
                    },
                    {
                        loader: 'css-loader',
                        options: {
                            //modules: true,
                            modules: {
                                // CSS name which we want to keep we can also
                                // change it to something like this [name]-[local]--[hash:base64:5]
                                localIdentName: '[name]-[local]',
                            },
                            url: false
                        }
                    },
                    {
                        loader: 'sass-loader'
                    },
                    {
                        loader: 'sass-resources-loader',
                        options: {
                            resources: './scss/abstracts/variables.scss'
                        }
                    }
                ]
            },
        ]
    },
    plugins: [
        new webpack.DefinePlugin({
            TRACKING_ID: "x"
            NODE_ENV: JSON.stringify('production'),
            SERVER_ADDRESS: JSON.stringify('http://localhost:5050/'),
            WT_SITE: JSON.stringify('http://localhost:5050')
        }),
        new webpack.EnvironmentPlugin({
            ASSETS_PATH: "http://localhost:5050/",
            SERVER_ADDRESS: "http://localhost:5050/",
            AUTO_LOGOUT_TIMER: 7180000,
        }),
        new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/),
    ],
    watch: true,
    watchOptions: {
        poll: 500
    },
    optimization: {
        minimize: false
    },
    mode: 'development',
    devtool: false
};

Can you please help me point out what is wrong in this that it is taking 30 seconds for any change I make in the code.
React version used 16.8.6
webpack version 4.23.1
Here is how my package.json looks like

A: Try ignoring node_modules in your watchOptions:
  watchOptions: {
    ignored: /node_modules/
  }

Also, polling is generally underperformant. Why do you need it ? Are you developing inside vagrant/docker or using a networked file system ?
Unrelated tangent: You may not want to set NODE_ENV: production for development, as it will suppress helpful warnings in many libraries like react, react-redux etc.


text:
Q: Load Multiple js file after page load I have multiple JavaScript files which are loaded before page load which are affecting page speed. I want that my JS files to load after page load though to improve page speed.
I tried to use async and defer but due to dependency to each other, this way is not working out for me. I also tried lazy loading through AJAX but that is also not working for me (using this link https://w3bits.com/async-javascript)
@section Scripts {

}

I use multiple JS files on a page and I want them all to load after page load. Is there any way to do that?

A: You can use getScript inside document.ready.
$(document).ready(function() {
    $.getScript("domainpath/lib/bootstrap-datetimepicker/js/moment.js");
});

It's fetch your js after dom ready.

A: You can use Jquery's $.getScript() function but then you have to keep an eye on proper loading order. Would recommend more to bundle all necessary files on the server side and only serve a single file

A: When the browser receives a request for an HTML file the DOM starts to draw. If you place your scripts in the  tag the DOM stops from rendering and the browser starts to execute the

However, if you had the


text:
Q: Issue with incrementing variable Dim chr As Range
test = 1

For Each chr In ActiveDocument.Range.Characters
Dim firstChar As Word.Range
Set firstChar = Selection.Characters(test)
MsgBox (Selection.Characters(test))
MsgBox (test)
test = test + 1

Next chr

This is supposed to select the first character and then later do something with it , and move to the second character, that part isn't happening as the value of "test" is not increasing , and the macro gives an error of :"the requested collection doesn't exist"
Why isn't the value incrementing .

A: Well, it works on the Selection. If you don't select any text, it will give you the mentioned error. But why overcomplicate it? This code does what you (seem to) want:
Dim chr As Range

For Each chr In Selection.Characters

  MsgBox chr.Text

Next chr


text:
Q: shutdown -h now: FreeBSD server won't power down I'm not a sysadmin, but got a used dell poweredge r320 anyway. A problem I've been having with it is that after issuing the shutdown -h now command in FreeBSD the system goes through the init system shutdown sequence, then simply stays powered on after all processes are stopped. I haven't seen a computer do that since windows 95 when it would say "it is now safe to power down your computer". Is this a server specific quirk? I've been through every option I could find in the BIOS/UEFI. I'd really like to be able to power down the machine remotely.

A: From the FreeBSD man:
-h       The system is halted at the specified time.
-p       The system is halted and the power is turned off (hardware sup-
     port required) at the specified time.

I believe you need shutdown -p now.


text:
Q: Reading the results of a multilevel model I'm trying to assess the effect of showing more impressions on a user. I want to study if users who saw more ads are more likely to make a purchase onsite. To do so I've created a multilevel model. I grouped users into 10 groups averaging their scores (we score users based on a number of factors). So basically I end up having 10 groups (from 0 to 9), where on group 9 I assume to have the best users, and on group 0 the worst.
  picbucket mcuserid impressions mediacostcpm is_buyer gr.impressions gr.mediacostcpm
1         0 1           1        0.460        0       3.632794        2.767509
2         0 2           2        5.000        0       3.632794        2.767509
3         0 3           1        4.590        0       3.632794        2.767509
4         0 4           1        0.590        0       3.632794        2.767509
5         0 5           1        5.000        0       3.632794        2.767509
6         0 6           1        0.315        0       3.632794        2.767509

I think a multilevel model could be advantageous here because I'm expecting to see different effects on each group. On the best users I'm expecting an additional impression could have a higher impact, whereas on bad users and additional impression may be worthless. It could also be possible the opposite though. So that users which generally higher score will convert even without the need of serving them more impressions, whereas on mid groups additional impressions tend to change their behaviour.
A good model representation could be:
$y_{i} = \alpha_{j[i]} + X_{i}\beta + \epsilon_{i}$
The second level of the model will then be:
$\alpha_{j} = \mu_{\alpha} + \eta_{j}, \text{ with } \eta_{j} \sim N(0, \sigma_{\alpha}^{2})$
On the first level I want to include as a predictor how many impression a user saw. On the second level I want to include the average impressions a user saw within its group and the average media cost for the impressions we served on that user. I've used the package lme4 in R to build my model.
glmer(formula = is_buyer ~ impressions + mediacostcpm + (1 +
    gr.impressions + gr.mediacostcpm | picbucket), data = new.df,
    family = binomial())
             coef.est coef.se
(Intercept)  -7.42     0.33
impressions   0.00     0.02
mediacostcpm  0.03     0.01

Error terms:
 Groups    Name            Std.Dev. Corr
 picbucket (Intercept)     7.86
           gr.impressions  2.22     -0.99
           gr.mediacostcpm 0.57     -0.68  0.60
 Residual                  1.00
---
number of obs: 103146, groups: picbucket, 10
AIC = 2755.4, DIC = 2680.5
deviance = 2708.9

This is my first experiment with multilevel modeling so I would like to make sure I don't misunderstand the results of my model.
From what I see here, the impressions predictor on the first level is useless. Its coefficient is zero and its standard deviation is very small. This could be due to the fact I'm including a group average on the second level for the impression count (gr.impressions). So, on any group (picbucket), serving more impressions than the average doesn't tell us much about the likelihood of a cookie to convert.
The average media cost on the first level is however an interesting one. Generally, within a group, if I spend a bit more for every impression I should increase the probability of generating conversions. This is probably due to inventory quality. Better inventory costs more, but also has better changes to be viewable inventory.
The coefficients on the group level instead tell you how much they contribute on explaining the group slope. So in this case the average number of impressions at the group level seems to explain quite a significant part of the group slope.
Interestingly, at the group level gr.impressions seem to be a very useful predictor, but at the within group level its usefulness is limited. The opposite applies to the mediacostcpm.
Am I interpreting these results correctly? How can I tell if the model has a good fit? Please note I've used a binomial regression because the dependent variable, is_buyer can take only 0 or 1 (one being the user made a purchase).


text:
Q: how to get configuration parameter into a command I'm trying to get a configuration parameter into a command.
I have added the parameter in the app/config/config.yml under the parameters key.
I can use it in a Controller using $this->getParameter("PRAMETER_NAME") in an action to do some stuff manually.
I'm writing a command to do the same stuff automatically with a CRON job.
I can't find how to get the parameter in the command.

A: Argument Binding
In Symfony 3.4 or later, the recommended approach is to use Autowiring and Argument Binding. Allowing for the declaration of the variable name to be "bound" as an argument for ALL services defined in the config file, without needing to explicitly specify each service the parameter is used in.
In the same configuration file that defines the command service and autowiring, add the bind option to the _defaults specification, along with the desired variable name for the parameter.
app/config/services.yml
parameters:
    PARAMETER_NAME: 'test'

services:
    _defaults:
        bind:
            $PARAMETER_NAME: '%PARAMETER_NAME%'
        autowire: true      # Automatically injects dependencies in your services.
        autoconfigure: true # Automatically registers your services as commands, event subscribers, etc.

    AppBundle\:
        resource: '../../src/AppBundle/*'
        exclude: '../../src/AppBundle/{DependencyInjection,Entity,Tests}'

    # Additional Services Below Here

Afterwards, Symfony will automatically pass the parameter value to the bound variable name when it is specified as an argument for the service constructor.
src/AppBundle/Command/MyCommand.php
namespace AppBundle\Command;

use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;

class MyCommand extends Command
{

    private $PARAMETER_NAME;

    public function __construct($PARAMETER_NAME)
    {
        $this->PARAMETER_NAME = $PARAMETER_NAME;
        parent::__construct();
    }

    // ...

    public function execute(InputInterface $input, OutputInterface $output)
    {
        dump($this->PARAMETER_NAME);
        exit;
    }

    public static function getDefaultName()
    {
        return 'app:my_command';
    }
}

Parameter Injection
Another approach, to avoid needing to override __construct, is to inject the parameter value using a method, by extending the service definition using calls.
app/config/services.yml
parameters:
    PARAMETER_NAME: 'test'

services:
    _defaults:
        autowire: true      # Automatically injects dependencies in your services.
        autoconfigure: true # Automatically registers your services as commands, event subscribers, etc.

    AppBundle\:
        resource: '../../src/AppBundle/*'
        exclude: '../../src/AppBundle/{DependencyInjection,Entity,Tests}'

    AppBundle\Command\MyCommand:
        calls:
            - [setParameterName, ['%PARAMETER_NAME%']]

    # Additional Services Below Here

src/AppBundle/Command/MyCommand.php
namespace AppBundle\Command;

use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;

class MyCommand extends Command
{

    private $parameterName;

    // ...

    public function execute(InputInterface $input, OutputInterface $output)
    {
        dump($this->parameterName);
        exit;
    }

    public function setParameterName($value)
    {
        $this->parameterName = $value;
    }
}

Alternatively, dependency injection can be used to inject the Container or ParameterBag into the command, allowing it to function similarly to a Controller.

Injecting the entire Container or ParameterBag is highly
discouraged.
Only inject the parameter(s) and service(s) that are needed
instead.

In either of the below examples, ensure autowire and autoconfigure are enabled.
app/config/services.yml
parameters:
    PARAMETER_NAME: 'test'

services:
    _defaults:
        autowire: true      # Automatically injects dependencies in your services.
        autoconfigure: true # Automatically registers your services as commands, event subscribers, etc.

    AppBundle\:
        resource: '../../src/AppBundle/*'
        exclude: '../../src/AppBundle/{DependencyInjection,Entity,Tests}'

    # Additional Services Below Here

ContainerAwareCommand
(depreciated as of Symfony 4.2 - removed in Syfmony 5.0+)
Using ContainerAwareCommand works similarly to Parameter Injection, but instead of calling setParameterName(). With autowiring and autoconfig enabled, Symfony will automatically inject the entire container using setContainer() implemented from ContainerAwareInterface.
src/AppBundle/Command/MyCommand.php
namespace AppBundle\Command;

use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;

class MyCommand extends ContainerAwareCommand
{

    // ...

    public function execute(InputInterface $input, OutputInterface $output)
    {
        dump($this->getContainer()->getParameter('PARAMETER_NAME'));
        exit;
    }
}

ParameterBag Injection
Requires Symfony 4.1+
To inject the ParameterBag with Dependency Injection when autowire is enabled, add ParameterBagInterface to the service constructor.
src/AppBundle/Command/MyCommand.php
namespace AppBundle\Command;

use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;

class MyCommand extends Command
{

    private $parameterBag;

    public function __construct(ParameterBagInterface $parameterBag)
    {
         $this->parameterBag = $parameterBag;
         parent::__construct();
    }

    // ...

    public function execute(InputInterface $input, OutputInterface $output)
    {
        dump($this->parameterBag->get('PARAMETER_NAME'));
        exit;
    }

    public static function getDefaultName()
    {
        return 'app:my_command';
    }
}

A: You can inject the container into the command declaring it ContainerAware (worse), you can inject the ParamterBag as a service (better) or you can inject the parameter in the command constructor (best).
In your command you have to accept the parameter in constructor. Ex:
YourCommand.php:
<?php

class YourCommand extends Command {
  public function __construct(string $parameter) {
    parent::__construct('app:my-command');
    $this->parameter = $parameter;
  }
}

services.yaml
services:
  YourCommand:
    arguments:
      - '%parameter_name%'


text:
Q: Mimetype vs AppID You see that it is adivsed to create your file with your app-specific mime type. Is it right way? I wonder because google drive somehow associates files with the application that created them for Open with functionality. Can this be exploited for the file picker?

A: If the file has custom contents that only your app can understand, use the app specific mime type.  Otherwise, use the standard mime type for whatever kind of file you are working with.

A: I have finally discovered that when your app (identified with CLIENT_ID) creates a file with mime-type application/vnd.google-apps.drive-sdk, the mime-type is expanded with .<AppID>. The AppID is the first part of your CLIENT_ID. Basically, project ID looked like alpine-dogfish-833 in mine case. I have then generated Client_ID 1088706429537-4oqhqr7o826ditbok23sll1rund1jim1.apps.googleusercontent.com and 1088706429537 is the AppID that we are looking for because when my app creates a file, using
gapi.client.drive.files.insert({
              'resource': {
                mimeType: application/vnd.google-apps.drive-sdk,
                title: file_name
              }

Note mime-type is application/vnd.google-apps.drive-sdk -- it does not contain any app ID. Querying the file reveals that the effective mime type of resulting file is actually application/vnd.google-apps.drive-sdk.1088706429537. Google can even fix the mime type even if you misspel application/vnd.google-apps.drive-sdk a bit.
This answers my question because eliminates all the confusions. The major confusion is that your project has additional application id, that you get even before the CLIENT-ID but it has nothing to do with signing the files with app-specific mime-type. I did not find that in the referred q&a. Secondly, this answers my question because it basically says that mime-type contains APP_ID so that app id and mime-type is therefore the same thing and there is no difference/redundancy/conflict to choose between two.

A: FYI-- You mentioned your project ID being alpine-dogfish-833. If you login to the developer console, then click on your project (which takes you to the project "Overview" page), you will see 2 identifiers at the top: Project ID: alpine-dogfish-833 and Project Number: 1088706429537. "Project Number" == "App ID" == "the numeric prefix on the Client ID"