text:
Q: Warnings thrown when accessing methods of reference class through RStudio The code and the warnings:
tinyclass <- setRefClass("TinyClass", methods = list(doNothing=function(){}))
tc <- tinyclass()
tc$doNothing()
NULL
Warning messages:
1: In installClassMethod(value, self, field, selfEnv, thisClass) :
  method .objectPackage from class TinyClass was not processed into a class method until being installed.  Possible corruption of the methods in the class.
2: In installClassMethod(value, self, field, selfEnv, thisClass) :
  method .objectParent from class TinyClass was not processed into a class method until being installed.  Possible corruption of the methods in the class.

I also get this from the code supplied in the help page for setRefClass, and on any other class I try to make. I get it reliably on a Mac running R 3.2.2 which I installed myself, and intermittently on several real and virtual Windows 64 machines running R 3.2.1 which were installed by an IT department.
I am using RStudio 0.99.467.  I have the following packages installed:
datasets, graphics, grDevices, methods, stats, utils.
NEW INFO:
It seems that the problem occurs when I run the code through RStudio, but not through the native R gui.
Loaded packages in RStudio:

search()
   [1] ".GlobalEnv"        "tools:rstudio"     "package:stats"     "package:graphics"  "package:grDevices" "package:utils"
   [7] "package:datasets"  "package:methods"   "Autoloads"         "package:base"

Loaded packages in native R:

search()
   [1] ".GlobalEnv"        "tools:RGUI"        "package:stats"     "package:graphics"  "package:grDevices" "package:utils"
   [7] "package:datasets"  "package:methods"   "Autoloads"         "package:base"

Thoughts?
Thanks


text:
Q: Get argument description of excel worksheetfunctions in VSTO vb.net I am trying to build a function that returns the description a built-in worksheetfunction's argument using worksheetfunction's name and field position as inputs.
GetExcelArgumentDescription("IF",1) should return "logical_test"
GetExcelArgumentDescription("IF",2) should return "value_if_true"
GetExcelArgumentDescription("IF",3) should return "value_if_false"

I have seen this in add-ins like this one (screenshot).
Is is possible to get this argument description (screenshot) via VSTO? How does the code look like in vb.net?

A: The worksheetfunction property of Excel is not an addressable collection.  You can create your own list from Microsoft's listing. Then reference your own list.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Calculate current and subsequent FY Quarter based on today's date I am trying to calculate the current FY Quarter (1 October start) based on =TODAY() date and the next x number of quarters, with the result being:
Q2 2017
Q3 2017
Q4 2017
Q1 2018
...
Qx 20xx

With this formula:
="Q" & ROUNDDOWN(MOD((TODAY()-DATE(YEAR(TODAY()-365),10,1)+K6*(365/4))/(365/4),4)+1,0)&" "&YEAR(TODAY()+K6*(365/4))

The result is:
K6=X    Result
0       Q2 2017
1       Q3 2017
2       Q4 2017
3       Q1 2017 * should be 2018
4       Q2 2018
5       Q3 2018
6       Q4 2018
7       Q1 2018 * should be 2019
8       Q2 2019

Question 1: the years are changing one quarter before they should, and
Question 2: this is a terrible mess of a formula - is there a way to make it more simple?
Full disclosure, I intend to implement use this formula in a VBA FOR x = 0... loop, with x = quarters since today, and setting the cell's formula accordingly.
EDIT: Alternatively, how could the desired output be generated using only VBA, and set in the desired cells as a text string?  A string representing the FY Quarter may make my application more stable.

A: Add this Function to a module sheet
Function NextQuarter(ByVal iCQ As Integer) As String
    Dim qtrd As Date
    Dim qtr As Integer

    qtrd = DateAdd("m", 3 + (3 * iCQ), Now())

    qtr = (Month(qtrd ) + 2) \ 3

    NextQuarter = "Q" & qtr & " " & Year(qtrd )

End Function

And in your cell use formula "=NextQuarter(K6)"

A: Try the VBA code below (I put the results in Column A, from row 2):
Option Explicit

Sub FormatQandY()

Dim x As Long

For x = 0 To 10 '<-- loop from today 10 Q ahead
    Cells(x + 2, 1) = "Q" & WorksheetFunction.RoundUp((Month(DateAdd("m", x * 3, Date))) / 3, 0) & "-" & Year(DateAdd("m", x * 3, Date))
Next x

End Sub


text:
Q: Catching a default error in Swift I am trying to learn Swift, and wondered about Apple's expected answer to the experiment below which is provided in the Error Handling section of Apple's GuidedTour playground as follows;

Experiment: Add code to throw an error inside the do block. What kind of error do you need to throw so that the error is handled by the first catch block? What about the second and third blocks?

enum PrinterError: ErrorType {
    case OutOfPaper
    case NoToner
    case OnFire
}

func sendToPrinter(printerName: String) throws -> String {
    if printerName == "Never Has Toner" {
        throw PrinterError.NoToner
    }
    return "Job sent"
}

do {
    let printerResponse = try sendToPrinter("Gutenberg")
    print(printerResponse)
} catch PrinterError.OnFire {
    print("I'll just put this over here, with the rest of the fire.")
} catch let printerError as PrinterError {
    print("Printer error: \(printerError).")
} catch {
    print(error)
}

Below are my answers to the questions asked in this experiment, and they all seem to work...

What kind of error do you need to throw so that the error is handled by the first catch block?

By adding throw PrinterError.OnFire as below;
do {
    throw PrinterError.OnFire
    let printerResponse = try sendToPrinter("Gutenberg")
    print(printerResponse)
} catch PrinterError.OnFire {
    print("I'll just put this over here, with the rest of the fire.")
} catch let printerError as PrinterError {
    print("Printer error: \(printerError).")
} catch {
    print(error)
}

What about the second...

By sending "Never Has Toner" to sendToPrinter.
do {
    let printerResponse = try sendToPrinter("Never Has Toner")
    print(printerResponse)
} catch PrinterError.OnFire {
    print("I'll just put this over here, with the rest of the fire.")
} catch let printerError as PrinterError {
    print("Printer error: \(printerError).")
} catch {
    print(error)
}

...and third blocks?

The only way I can trigger the third block -and the expected answer in my opinion in this case- is to create a different enum conforming to ErrorType and to throw it, as below;
enum anotherEnum: ErrorType {
    case someCase
}

do {
    throw anotherEnum.someCase
    let printerResponse = try sendToPrinter("Gutenberg")
    print(printerResponse)
} catch PrinterError.OnFire {
    print("I'll just put this over here, with the rest of the fire.")
} catch let printerError as PrinterError {
    print("Printer error: \(printerError).")
} catch {
    print(error)
}

However, as the first sentence for this experiment starts with "Add code to throw an error inside the do block.", I wondered if there was another expected answer that I was supposed to find out while staying in the do block.
I'm asking because I don't want to miss something else that I was expected to find out. Do you think these answers are valid from Apple's perspective?
Thank you!

A: A more practical example of that third scenario might be something like checking to see if the network was available before even bothering to  try sending something to the network printer:
enum NetworkError: ErrorType {
    case Unavailable
}

enum PrinterError: ErrorType {
    case OutOfPaper
    case NoToner
    case OnFire
}

func sendToPrinter(printerName: String) throws -> String {
    if printerName == "Never Has Toner" {
        throw PrinterError.NoToner
    }
    return "Job sent"
}

var networkAvailable = false     // some other process will update this when the network is available

Then you could do:
do {
    if !networkAvailable {
        throw NetworkError.Unavailable
    }

    let printerResponse = try sendToPrinter("Gutenberg")
    print(printerResponse)
} catch PrinterError.OnFire {
    print("I'll just put this over here, with the rest of the fire.")
} catch let printerError as PrinterError {
    print("Printer error: \(printerError).")
} catch {
    print(error)
}

This will result in the third catch block being caught.
Or a more realistic, Cocoa example might be:
do {
    let documents = try NSFileManager.defaultManager().URLForDirectory(.DocumentDirectory, inDomain: .UserDomainMask, appropriateForURL: nil, create: false)
    let fileURL = documents.URLByAppendingPathComponent("document.txt")
    let contents = try String(contentsOfURL: fileURL)

    let printerResponse = try sendToPrinter(contents)
    print(printerResponse)
} catch PrinterError.OnFire {
    print("I'll just put this over here, with the rest of the fire.")
} catch let printerError as PrinterError {
    print("Printer error: \(printerError).")
} catch {
    print(error)
}

Note, this isn't actually manually throwing an error, but relying upon errors thrown by URLForDirectory and String(contentsOfURL:). But if the document.txt was not found in the Documents folder, String(contentsOfURL:) would throw an error which would be caught by your third catch block.


text:
Q: How to prevent class member obfuscation when using multiple classes related classes? I have the following location in my project:
package com.example.data

Where I have placed four classes, A, B, C and D that look like this:
public class A {
    public List<B> bList = new ArrayList<>();
}

public class B {
    public List<C> CList = new ArrayList<>();
}

public class C {
    public D d;
}

public class D {
    public String s;
}

Now, in my ProGuard I can add simething like this:
-keepclassmembers class com.example.data.data.A{*;}
-keepclassmembers class com.example.data.data.B{*;}
-keepclassmembers class com.example.data.data.C{*;}
-keepclassmembers class com.example.data.data.D{*;}

But is there a more simpler way I can avoid obfuscation in my classes configuration?

A: You can give a rule to the package level. So all classes under this package will not be obfuscated. In your proguard rules file, for example in proguard-common.pro file, add the below code.
-keep class com.example.data.** { *; }


text:
Q: Generate 256 numbers using /dev/urandom in Assembly; I would like to know how to use /dev/urandom to generate numbers in assembly 32 bits.
I know i should that i should have the name of the file "/dev/urandom" in memory :
segment.data :
file : db "/dev/random",10
len : equ $-file
index : db "1",10
lenindex : equ $-index

then I should read the file in my loop to generate a number and write 1 in the index of the generated number, here is my loop
loop1 : xor ecx,ecx
        cmp ecx,256
        je end_loop1
        mov EAX, 5
        mov ebx, file
       mov ecx, 0; o for octal // I guess this is how i generate a number (by reading it)
     mov edx, 0001o;o for octal // Permission on file.
       inc ecx
       int 0x80;
       mov ebx,eax
       mov eax,4
       mov ecx,index
       mov edx,lenindex
       int 0x80
       jmp loop1

as u may constat, I'm a beginner in assembly 32 bits I would love if someone explains how can I generate numbers using /dev/urandom and indicate 1 in the index of the generated number.

A: To get 256 random bytes at once and print them (NASM assembler):
SECTION .data                   ; Section containing initialised data

    file db "/dev/urandom",0
    txt db " random bytes generated", 0x0A, 0x0A
    txt_len EQU $ - txt
    index dd 0

SECTION .bss                    ; Section containing uninitialised data
    decstr resb 40              ; 40 Bytes for an ASCII string
    decstr_len resd 1
    filedescriptor resd 1
    numbers resb 256

SECTION .text                   ; Section containing code
global  _start                  ; Linker needs this to find the entry point!
_start:

    ; http://www.lxhp.in-berlin.de/lhpsysc1.html#open
    mov eax, 5                  ; SYSCALL open
    mov ebx, file               ; File descriptor
    mov ecx, 0                  ; Access: read only
    mov edx, 0x00004            ; Mode: read by others
    int 0x80                    ; Call Linux kernel
    mov [filedescriptor], eax   ; Store the resulting fd

    ; http://www.lxhp.in-berlin.de/lhpsysc1.html#read
    mov eax, 3                  ; SYSCALL read
    mov ebx, [filedescriptor]   ; File descriptor
    mov ecx, numbers            ; Pointer to input buffer
    mov edx, 256                ; Max. count of bytes to read
    int 0x80                    ; Call Linux kernel
    mov [index], eax            ; Store the count of bytes received

    ; http://www.lxhp.in-berlin.de/lhpsysc1.html#close
    mov eax, 6                  ; SYSCALL close
    mov ebx, [filedescriptor]   ; File descriptor
    int 0x80                    ; Call Linux kernel

    ; Print index
    mov eax, [index]            ; Argument: Integer to convert
    mov edi, decstr             ; Argument: Address of the target string
    call int2str                ; Get the digits of EAX and store it as ASCII & LF & NUL
    sub edi, decstr             ; EDI (pointer to the terminating NULL) - pointer to decstr = length of the string
    dec edi                     ; Shorten the string by the LF
    mov [decstr_len], edi       ; Store the resulting length of the string

    ; http://www.lxhp.in-berlin.de/lhpsysc1.html#write
    mov eax, 4                  ; SYSCALL write
    mov ebx, 1                  ; File descriptor: STDOUT
    mov ecx, decstr             ; Pointer to output buffer
    mov edx, [decstr_len]       ; count of bytes to send
    int 0x80

    ; http://www.lxhp.in-berlin.de/lhpsysc1.html#write
    mov eax, 4                  ; SYSCALL write
    mov ebx, 1                  ; File descriptor: STDOUT
    mov ecx, txt                ; Pointer to output buffer
    mov edx, txt_len            ; count of bytes to send
    int 0x80

    ; Print the numbers
    mov esi, numbers            ; Start address for lodsb
L1:                             ; Loop to print <index> numbers
    xor eax, eax                ; Argument: Integer to convert
    lodsb
    mov edi, decstr             ; Argument: Address of the target string
    call int2str                ; Get the digits of EAX and store it as ASCII & LF & NUL
    sub edi, decstr             ; EDI (pointer to the terminating NULL) - pointer to decstr = length of the string
    mov [decstr_len], edi       ; Store the resulting length of the string

    ; http://www.lxhp.in-berlin.de/lhpsysc1.html#write
    mov eax, 4                  ; SYSCALL write
    mov ebx, 1                  ; File descriptor: STDOUT
    mov ecx, decstr             ; Pointer to output buffer
    mov edx, [decstr_len]       ; count of bytes to send
    int 0x80

    sub dword [index], 1
    jnz L1                      ; Do it again

    ; http://www.lxhp.in-berlin.de/lhpsysc1.html#exit
    mov eax, 1                  ; SYSCALL exit
    mov ebx, 0                  ; Exit Code
    int 80h                     ; Call Linux kernel

int2str:    ; Converts an positive integer in EAX to a string pointed to by EDI
    xor ecx, ecx
    mov ebx, 10
    .LL1:                       ; First loop: Collect the remainders
    xor edx, edx                ; Clear EDX for div
    div ebx                     ; EDX:EAX/EBX -> EAX Remainder EDX
    push dx                     ; Save remainder
    inc ecx                     ; Increment push counter
    test eax, eax               ; Anything left to divide?
    jnz .LL1                    ; Yes: loop once more

    .LL2:                       ; Second loop: Retrieve the remainders
    pop dx                      ; In DL is the value
    or dl, '0'                  ; To ASCII
    mov [edi], dl               ; Save it to the string
    inc edi                     ; Increment the pointer to the string
    loop .LL2                   ; Loop ECX times

    mov word [edi], 0x0A        ; Last characters: LF, NUL
    inc edi
    ret                         ; RET: EDI points to the terminating NULL

To get 256 random DWORDs one by one and print them one by one (NASM assembler):
SECTION .data                   ; Section containing initialised data

    file db "/dev/urandom",0    ; NUL terminated (ASCIZ)!
    loopcount dd 256

SECTION .bss                    ; Section containing uninitialised data

    decstr resb 40              ; 40 Bytes for an ASCII string
    decstr_len resd 1
    filedescriptor resd 1
    number resd 1

SECTION .text                   ; Section containing code
global  _start                  ; Linker needs this to find the entry point!
_start:

    ; http://www.lxhp.in-berlin.de/lhpsysc1.html#open
    mov eax, 5                  ; SYSCALL open
    mov ebx, file               ; File descriptor
    mov ecx, 0                  ; Access: read only
    mov edx, 0x00004            ; Mode: read by others
    int 0x80                    ; Call Linux kernel
    mov [filedescriptor], eax   ; Store the resulting fd

L1:                             ; Loop to print <loopcount> numbers

    ; http://www.lxhp.in-berlin.de/lhpsysc1.html#read
    mov eax, 3                  ; SYSCALL read
    mov ebx, [filedescriptor]   ; File descriptor
    mov ecx, number             ; Pointer to input buffer
    mov edx, 4                  ; Max. count of bytes to read
    int 0x80                    ; Call Linux kernel

    ; Print the number
    mov eax, [number]           ; Argument: Integer to convert
    mov edi, decstr             ; Argument: Address of the target string
    call int2str                ; Get the digits of EAX and store it as ASCII & LF & NUL
    sub edi, decstr             ; EDI (pointer to the terminating NULL) - pointer to decstr = length of the string
    mov [decstr_len], edi       ; Store the resulting length of the string

    ; http://www.lxhp.in-berlin.de/lhpsysc1.html#write
    mov eax, 4                  ; SYSCALL write
    mov ebx, 1                  ; File descriptor: STDOUT
    mov ecx, decstr             ; Pointer to output buffer
    mov edx, [decstr_len]       ; count of bytes to send
    int 0x80

    sub dword [loopcount], 1
    jnz L1                      ; Do it again

    ; http://www.lxhp.in-berlin.de/lhpsysc1.html#close
    mov eax, 6                  ; SYSCALL close
    mov ebx, [filedescriptor]   ; File descriptor
    int 0x80                    ; Call Linux kernel

    ; http://www.lxhp.in-berlin.de/lhpsysc1.html#exit
    mov eax, 1                  ; SYSCALL exit
    mov ebx, 0                  ; Exit Code
    int 80h                     ; Call Linux kernel

int2str:    ; Converts an positive integer in EAX to a string pointed to by EDI
    xor ecx, ecx
    mov ebx, 10
    .LL1:                       ; First loop: Collect the remainders
    xor edx, edx                ; Clear EDX for div
    div ebx                     ; EDX:EAX/EBX -> EAX Remainder EDX
    push dx                     ; Save remainder
    inc ecx                     ; Increment push counter
    test eax, eax               ; Anything left to divide?
    jnz .LL1                    ; Yes: loop once more

    .LL2:                       ; Second loop: Retrieve the remainders
    pop dx                      ; In DL is the value
    or dl, '0'                  ; To ASCII
    mov [edi], dl               ; Save it to the string
    inc edi                     ; Increment the pointer to the string
    loop .LL2                   ; Loop ECX times

    mov word [edi], 0x0A        ; Last characters: LF, NUL
    inc edi
    ret                         ; RET: EDI points to the terminating NULL

You can change the number in
mov edx, 4                  ; Max. count of bytes to read

to get another range, e.g.
mov edx, 2                  ; Max. count of bytes to read

for a WORD range (0..65535).


text:
Q: Trying to change category of wp_query I'm trying to change the category of the main loop, after printing posts from each category. The page shows:

*

*3 most recent posts

*3 posts from first category

*3 posts from second category

*3 posts from third category

*3 posts from fourth category

The category-specific posts can't be from the most recent.
The category-specific posts aren't right, though. I see posts, but they're not from the right category!
Here's my template. It uses blade, so slightly different syntax, but more or less the same as PHP.
  @php
    $args = array(
      'numberposts' => 3,
      'fields'      => 'ids'
    );
    $posts = new WP_Query( $args );
  @endphp

  @include ('partials.content-lh-post-previews', ['featured_text' => true, 'limit' => 3, 'headline' => 'Recent Articles', 'include_cat' => true])

  {{-- Posts by category --}}
  @php
    $args  = array(
      'taxonomy' => 'category',
      'parent' => 0,
      'fields' => 'ids',
      'meta_key' => 'category_weight',
      'orderby' => 'meta_value_num'
    );

    $terms = get_terms($args);
  @endphp

  @foreach ($terms as $index => $term)
    @php wp_reset_postdata(); @endphp
    @php
      $posts->query['cat'] = [$term];
      $term_name = get_term( $term )->name;
      $headline = $index == 0 ? 'Featured Stories' : '';
    @endphp

    @include ('partials.content-lh-post-previews', ['featured_text' => false, 'limit' => 3, 'supertext' => $term_name, 'view_more' => $term, 'headline' => $headline])
  @endforeach

And the template partial I call on lines 9 and 34:
<?php
    $count = 0;
?>
@if ($posts)

            @if ( isset($headline) && $headline )

{{ $headline }}

            @endif
            @isset ( $supertext )
                {{ $supertext }}
            @endisset

                <?php while ($posts->have_posts() && $count < $limit) : $posts->the_post(); ?>
                    @php
                        $image = get_field('small_image');
                        $title = get_the_title();
                        $copy  = $featured_text ? get_field('featured_text') : null; // only show post copy if is latest section
                        if ( isset($include_cat) && $include_cat ) :
                            $cat = get_field('main_category')['label'];
                        endif;
                    @endphp

                        @if ( $image )

                        @endif

                            @isset( $include_cat )
                                <?php echo $cat ?>
                            @endisset

{!! $title !!}

                            @if ( $copy )

{!! $copy !!}

                            @endif

Read the article

                    <?php $count++; ?>
                <?php endwhile; ?>
                @isset($view_more)
                    @php
                        $term       = get_term($view_more);
                        $term_icon  = get_field('category_icon', $term);
                        $term_color = get_field('category_color', $term);
                        $term_link  = get_category_link($view_more);
                        $term_name  = $term->name;

                    @endphp

                        @if ( $term_icon )

                        @endif

More {{ $term_name }} Articles

View all

                @endisset

@endif

@php wp_reset_postdata() @endphp

Why isn't the category working?


text:
Q: How to handle the errors while data migration to cassandra trying to migrate the data from oracle to cassandra i have below issues:
How to handle the errors while data migration to cassandra using spark-sql?
How to design the retry machanisum if anything fails ?
Is there any document/sample/github regarding the same.
~Sha

A: you can look into these below github repos for reference
https://github.com/snazy/Oracle_to_Cassandra
https://github.com/AlexGruPerm/oratocass


text:
Q: Swift - no such module PureLayout with manual installation AND cocoa pods? Its impossible? I've tried everything. EVERYTHING. I have no. idea. what Im doing wrong here.
Ive downloaded test projects and followed every step under manual installation AND install using pods here: https://github.com/PureLayout/PureLayout#problems-suggestions-pull-requests
I already have Parse and some other modules installed via pods so I first went to pods. I first went to my pods file and wrote
use_frameworks!
pod 'PureLayout'

JUST as the working sample projects did. I then navigated to my project (I think I did this right - went to terminal did cd Desktop then cd my project name, didn't think I had to cd anywhere else) and ran pod install . After this nothing happened in terminal (I got no response no matter what I did) and no PureLayout files were added to my project.
I still got no such module Purelayout when trying to trying to import PureLayout so then I tried manual.
I have dragged the files here https://github.com/PureLayout/PureLayout/tree/master/PureLayout/PureLayout into my project and imported in my bridging header:

Tell me if Im missing something. I still get no such module - even checked in my build settings that it had the right bridging header. I can continue without this and have no ideas - What am i doing wrong?
Is this an impossible problem?


text:
Q: Writing integer to console gives Segmentation Fault Going from high to low lever language I got to assembly. Now at the very beginning, I wrote a simple age program (I'm not clear how to get system time yet so I just used another input). I get Segmentation Fault (core dumped) after I enter the final input. Here is my code:
section .text
global _start

_start:

mov edx, lenask
mov ecx, ask
mov ebx, 1
mov eax, 4
int 0x80

mov edx, 5
mov ecx, input
mov ebx, 2
mov eax, 3
int 0x80

mov edx, lenask2
mov ecx, ask2
mov ebx, 1
mov eax, 4
int 0x80

mov edx, 5
mov ecx, input2
mov ebx, 2
mov eax, 3
int 0x80

mov eax, input2
mov ebx, input
sub eax, ebx

push eax

mov edx, lenanswer
mov ecx, answer
mov ebx, 1
mov eax, 4
int 0x80

pop eax

mov edx, 7
mov ecx, eax
mov ebx, 1
mov eax, 4
int 0x80

section .data

ask db "What is your age?"
lenask equ $-ask
ask2 db "What is today's year?"
lenask2 equ $-ask2
answer db "The age you were born was: "
lenanswer equ $-answer

section .bss

input resb 5
input2 resb 5

An example of what happens:
What is your age?45
What is today's year?2015
The age you were born was: Segmentation fault

It should have done:
What is your age?45
What is today's year?2015
The age you were born was: 1970

A: The problem is that int 0x80 with eax set to 4 calls the kernel's sys_write function (i.e. a write system call) which expects a pointer to a string. By providing a integer to the function call the kernel will think that the integer is a pointer to a memory location. Because 1970 is not a valid pointer it will raise a -EFAULT. To bypass this you need to code a ToString function to convert the number to a string and then pass the pointer to the converted string.
The Segmentation Fault itself is caused by not having a sys_exit call. The reason for this is that the program will continue past the end of your code (usally into a bunch of 00 00)


text:
Q: Array Methods in Java I am trying to write a method which enables me to add numbers to arrays. If I enter something execpt 0 it will be the first number of the array. The next one(except 0) will be the second number. When I enter 0 the program will end.
For example ; 1,2,3,4,5,0 will show 1,2,3,4,5 but when I enter it I get 0,5,5,5,5. Can you help?
Here an updated version, free from errors.
import java.util.*;

public class test
{
     public static int[] addToArray(int[] bag, int value)
     {
         int i;
         for(i = 0; i <= bag.length - 1; i++)
         {
              bag[i] = value;
              if(bag[i] == 0)
              {
                   return bag;
              }

         }
         return bag;
      }

      public static void main(String[] args)
      {
           Scanner scan = new Scanner(System.in);
           int[] bag = new int[5];
           int i, value;
           i = 0;
           System.out.println("Enter the values : ");
           do
           {
                value = scan.nextInt();
                addToArray(bag, value);
           }
           while(bag[i] != 0);

           System.out.println(Arrays.toString(bag));
       }
}

A: Your addToArray method is replacing the whole array every time is called. This is what the for loop is doing
for(i = 0; i <= bag.length - 1; i++) {
    bag[i] = value;
    ...
}

When you enter 0 then this code:
bag[i] = value
if(bag[i] == 0) {
  return bag;
}

Will set the bag[0] = 0 and then the if will succeed and return the bag.
What you need is to find in which position of the array you should be adding this value
public static int findNextEmptyPosition(bag) { .... }

...
int nextPosition = findNextEmptyPosition(bag);
bag[nextPosition] = value;
...

//check is the value is zero and stop your while loop.

A: OK. I solved it. The problem is in every loop in redefine the whole array so it will all print the last number I entered before 0. Thank you all for showing me this problem. I solved by adding another parameter to the method. The index parameter "i". Now, in the loop in won't start from zero. It will start from where it stopped so I can define the empty arrays without redefining the previous ones. Thank you all for helping.
import java.util.*;

public class test
{
  public static int[] addToArray(int[] bag, int value, int i)
  {
    int j;
    for(j = i; j <= bag.length - 1; j++)
    {
        bag[j] = value;
        if(bag[j] == 0)
        {
            for(; j <= bag.length - 1; j++)
            bag[j] = 0;
            return bag;
        }

      }
      return bag;
   }

   public static void main(String[] args)
   {
     Scanner scan = new Scanner(System.in);
     int[] bag = new int[5];
     int i, value;
     i = 0;
     System.out.println("Enter the values : ");
     do
     {
         value = scan.nextInt();
         addToArray(bag, value, i);
         i++;
     }
     while(value != 0);

     System.out.println(Arrays.toString(bag));
   }
}


text:
Q: Installing multiple versions of a package with pip In my application I would like to use:

*

*packageA, which requires packageX==1.3

*packageB, which requires packageX==1.4

*packageX==1.5
How can I install multiple versions of packageX with pip to handle this situation?

A: pip won't help you with this.
You can tell it to install a specific version, but it will override the other one. On the other hand, using two virtualenvs will let you install both versions on the same machine, but not use them at the same time.
You best bet is to install both version manually, by putting them in your Python path with a different name.
But if your two libs expect them to have the same name (and they should), you will have to modify them so they pick up the version they need with some import alias such as:
import dependencyname_version as dependencyname

There is currently no clean way to do this. The best you can hope is for this hack to work.
I'd rather ditch one of the two libs and replace it with an equivalent, or patch it to accept the new version of the dependency and give the patch back to the community.

A: an ugly workaround I use with python in blender is I'll install (and keep off path) a like version of python and use subprocess to have the other version do the needed work. Blenders python tends to get a little temperamental if you do much more than install pandas and scipy. I've tried this using virtualenvs with blender but that tends to break things.
Also on the off chance you are using blender for data visualization, you are going to want to add a config folder to your version number folder, this will keep all of your addons in that folder and it makes it far more portable and far less likely to mess up other installs of blender. Many people who make addons for blender are not 'programmers', so often those savvy people will do some very hackish things and this has been the best workaround I've been able to use.
Another workaround (and this has so many flags on the play that it should disqualify me from touching a keyboard) is to manually locate the init file and manually add it to globals with importlib ... this comes with risks. Some modules will play alright when you do this, other modules will toss crapfits that can lead to extra special troubleshooting sessions. Keep it to like versions and it does cut down on the issues and I've had 'alright' luck with using this to import modulus from behind virtual envs, but there is a reason why I use subprocess calls when working with blender's python.
def importfromfilelocation(x,y,z):
    #"""x = 'tk',y = "tkinter", z =r'C:\pyth"""
    mod_alis = x
    spec = importlib.util.spec_from_file_location(y, z)
    print(spec)
    mod_alis = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(mod_alis)
    globals()[str(x)]= mod_alis

A: Download the source for ea. package.  Install each on its own separate folder. For example.  I had version 1.10 package, but wanted to switch to the dev version for some work. I downloaded the source for the dev module:
git clone https://github.com/networkx/networkx.git
cd netwokrx
I created a folder for this version:
mkdir /home/username/opt/python, then I set the PYTHONPATH env var to: export PYTHONPATH=/home/username/opt/python/lib/python2.7/site-packages/.  Next, I installed it using: python setup.py install --prefix=/home/username/opt/python
Now, since my PYTHONPATH is now pointing to this other site-packages folder, when I run python on the command line, and import the new module, it works. To switch switch back, remove the new folder from PYTHONPATH.
>>> import networkx as nx
>>> nx.__version__
'2.0.dev_20151209221101'

A: Another "workaround" is to use IPC/RPC and run isolated packages in services. If the dependencies are on the different libraries, maybe can separate by the usage of the packages.


text:
Q: What it the difference between Hbase and BigTable? Can anyone tell me what is the difference between Apache HBase database and Bigtable? Or are they same?
Which one supports relations, if any?
If they are Big Searcher what is the difference?

A: They are similar enough that Google now offers access to Bigtable via HBase 1.0 APIs: cloud.google.com/bigtable

A: They are similar, but not the same!
Bigtable was initially released in 2005, but wasn't
 available to general public until 2015. Apache HBase was created based on Google's publication Bigtable: A Distributed Storage System for Structured Data with initial release in 2008.
Some similarities:

*

*Both are NoSQL. That means both don't support joins, transactions, typed columns, etc.

*Both can handle significant amounts of data - petabyte-scale! This achieved because of support of linear horizontal scaling.

*Both make emphasis on high-availability - through replication, versioning.

*Both are schema-free: you can create table and add column families or columns later.

*Both have APIs for most popular languages - Java, Python, C#, C++. Complete lists of supporting languages differ a bit.

*Both support Apache HBase Java's API: after Apache HBase's success Google added support for HBase-like API for Bigtable but with  some limitations - see API differences.

Some differences:

*

*Apache HBase is an open source project, while Bigtable is not.

*Apache HBase can be installed on any environment, it uses Apache Hadoop's HDFS as underlying storage. Bigtable is available only as a cloud service from Google.

*Apache HBase is free, while Bigtable is not.

*While some APIs are common, others are not - Bigtable supports gRPC (protobuf based) API, while Apache HBase have Thrift and REST APIs.

*Apache HBase supports server side scripting (e.q. triggers) and in general is more open to extensions due to its open source nature.

*Bigtable supports multi-cluster replication.

*Apache HBase has immediate consistency always, while Bigtable has eventual consistency in worst case scenarios.

*Different security models - Apache HBase uses Access Control Lists, while Bigtable relies on Google's Cloud Identity and Access Management.

See more at their websites - Bigtable and Apache HBase .


text:
Q: Ignore some files during branch merging I have two branches master and develop. Each branch contains a same file named "db.config" having a separate db credentials for production(master) and staging(develop).
Master branch also have .gitattributes file in which i defined a merge=ours strategy for db.config
.gitattributes
db.config merge=ours
When i merge develop into master branch by creating a pull request in bitbucket then changes in develop branch also goes to master after merge for db.config. It looks like .gitattributes file doesnot work for me.
Also stackoverflow same issue doesnot works for me. Does anyone know how i get rid out of this?

A: I've been able to replicate your issue, and pretty sure you forgot that part:
And then define a dummy ours merge strategy with:
$ git config --global merge.ours.driver true

From your master branch.
Switch to master, configure your merge strategy, it should work.
Whats the Proper usage of .gitattributes with merge=ours
Edit: due to what had been said in the comments, you probably want to remove this file from tracking:
How to stop tracking and ignore changes to a file in Git?


text:
Q: Twitter Bootstrap - unwanted space above the footer in Mobile App My question is similar to the question here:
Bootstrap Unwanted space on the bottom of modal-footer after using the unofficial Bootstrap Modal modification
But, i am not using Modal and the issue only really bothers me in Landscape mode.
This is a photo (apologies) of what I mean.
I am totally stumped. Apart from the link I gave above I cannot find any thing else relating to this?

Just to confirm - want get rid of the white space.
And this is my current markup:

       my top content

       my body content

       my footer content


text:
Q: Integration by substitution example If we decide to integrate from the limits $a$ to $b$, i.e. $\int^b_ax dx$. The function here doesn't matter, it's just an example. But if we then use the substitution $x=\frac{b-a}{2}t+\frac{b+a}{2}$ why is it that our new limits then will become $\int^1_{-1} f(x(t)) dt$. I don't see how $\frac{b-a}{2}a+\frac{b+a}{2}=-1$ or $\frac{b-a}{2}b+\frac{b+a}{2}=1$.
Specific image of example

A: It's because:

*

*$t=1\implies\frac{b-a}2t+\frac{b+a}2=b$;

*$t=-1\implies\frac{b-a}2t+\frac{b+a}2=a$.


text:
Q: Ruby/Rails ActiveAdmin Image Validator Error I'm using Rails 4.1, Ruby 2.0, and ActiveAdmin from github
I'm extremely new to rails. but basically all I want is an active admin form that will allow image uploading, and then save the URL to a string in the model called img_url.
Currently, it doesn't save anything to img_url, just NIL. But the form lets you select a file and proceed.
My activeadmin form:
ActiveAdmin.register Product do
  permit_params :name, :price, :description, :is_available,
                :img_url

  index do
    column :img_url, :sortable => false do Product
      "<img src='#img_url' alt='Product Logo' style='height:48px; display:block;
        margin-left:auto;
        margin-right:auto;'".html_safe
    end
    column :name
    column :price do |item|
      div :class => "price" do
        number_to_currency item.price
      end
    end
    column :description
    column :is_available
    actions
  end

  form :html => { :enctype => "multipart/form-data"} do |f|
    f.inputs "Details"  do
      f.input :name
      f.input :description, :as => :text
      f.input :price
      f.input :is_available
      f.input :img_url, :label => 'Product Image', :as => :file
    end
    f.actions
  end
end

My product model, which brings me to my second issue:
class Product < ActiveRecord::Base
  has_attached_file :img_url, :styles => { :thumb => "100x100" }
  validates_attachment :img_url, :content_type => { :content_type => ["image/jpg", "image/jpeg", "image/png", "image/gif"] }
end

Of course, i'd like to validate the content/type to make sure it's an image. But uncomment the validates method I get:
 "undefined method `img_url_content_type' for #<Product:0x000000060e4560>"
Parameters:
{"utf8"=>"✓",
 "_method"=>"patch",
 "authenticity_token"=>"5dtIAV866xUavdUQDFuL5/J0IIl6Un3l4Nu2sNOmy2c=",
 "product"=>{"name"=>"Test",
 "description"=>"Test Description",
 "price"=>"5",
 "is_available"=>"1",
 "img_url"=>#<ActionDispatch::Http::UploadedFile:0x000000060ce378 @tempfile=#<Tempfile:/tmp/RackMultipart20141009-8450-2vnymd>,
 @original_filename="100x100.gif",
 @content_type="image/gif",
 @headers="Content-Disposition: form-data; name=\"product[img_url]\"; filename=\"100x100.gif\"\r\nContent-Type: image/gif\r\n">},
 "commit"=>"Update Product",
 "id"=>"2"

It'd also be nice to be able to delete the file from the server within ActiveAdmin.
Here's my gemfile, too
source 'https://rubygems.org'
# Bundle edge Rails instead: gem 'rails', github: 'rails/rails'
gem 'rails', '4.1.6'
# Use mysql as the database for Active Record
gem 'mysql2'
# Use SCSS for stylesheets
gem 'sass-rails', '~> 4.0.3'
# Use Uglifier as compressor for JavaScript assets
gem 'uglifier', '>= 1.3.0'
# Use CoffeeScript for .js.coffee assets and views
gem 'coffee-rails', '~> 4.0.0'
# See https://github.com/sstephenson/execjs#readme for more supported runtimes
# gem 'therubyracer',  platforms: :ruby

# Use jquery as the JavaScript library
gem 'jquery-rails'
gem 'oj'
gem 'oj_mimic_json'
# Turbolinks makes following links in your web application faster. Read more: https://github.com/rails/turbolinks
gem 'turbolinks'
# Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder
gem 'jbuilder', '~> 2.0'
# bundle exec rake doc:rails generates the API under doc/api.
gem 'sdoc', '~> 0.4.0',          group: :doc

# Spring speeds up development by keeping your application running in the background. Read more: https://github.com/rails/spring
gem 'spring',        group: :development

# Use ActiveModel has_secure_password
# gem 'bcrypt', '~> 3.1.7'

# Use unicorn as the app server
# gem 'unicorn'

# Use Capistrano for deployment
# gem 'capistrano-rails', group: :development

# Use debugger
# gem 'debugger', group: [:development, :test]

# ActiveAdmin
gem 'activeadmin', github: 'activeadmin'
gem 'devise'
gem 'paperclip', :git => "http://github.com/thoughtbot/paperclip.git"

This is the very first project I've ever done in rails, so if any more information is needed just let me know.
Thanks!
UPDATE
I adjusted the permit_params which was the issue with img_url not saving.
I also had to add a column/migration for img_url_file_name for paperclip.
However, it now requires the validator which I can not get to work still

A: I'm going to answer my own question, I had a few problems here.
1.) I did not properly define :img_url in permit_params properly.Corrected original question with how it should be
2.) I do not need an img_url column in the database. I made a migration to remove it. My web service will rather use paperclip methods to return the URL when needed
3.) Paperclip needed an img_url_file_name, which I made a migration for.
4.) Paperclip also needed an img_url_content_type in the model, which I also made a migration for.
Now everything works as I expected.


text:
Q: difference between ffmpeg vs live555 Does anyone knows what's the main difference between live555 and ffmpeg. It seems that both are capable of doing video streaming. Is it that live555 does it in RTSP, while ffmpeg does it in mpeg-2 transport stream ? Thanks, Ran

A: They are built using some of the same libs and in general ffmpeg may be used more for transcoding and c interface to libs used in transcoding.
Live555 is good for RTSP protocol among lots of other things.
Look first to ffmpeg for transcode related stuff and to live555 for streaming .

A: To put it simply:

*

*FFMPEG is a library for encoding and decoding video/audio

*Live555 is a library for streaming already encoded movies/audio and reading in streams.
Yes some compiled/pre-built versions of FFMPEG can stream video but it's main use is for encoding and decoding video/audio.
Live555 has a quite elaborate set of tools to allow streaming over a number of different protocols and different types of streams (not just RTSP, and it can also do mpeg-2 streaming). The core Live555 library does not allow you to encode or decode movies, it is simply a set of tools for streaming video/audio only. Some compiled/pre-built versions may allow you to perform encoding/decoding but it is using some library other than live555.


text:
Q: Vertica does not export to parquet all the data without limit clause I see really weird behaviour when trying to do EXPORT TO PARQUET from Vertica to local drive.
See example:
When I do
EXPORT TO PARQUET (directory = '/data') over (partition by install_date)
    AS select field1, field2 from table where install_date >= 'some_date';

Vertica says:
Rows Exported
---------------
  16 405 136

But when I read result parquet (using pyarrow or Spark), i get only 2 522 845 rows. oO
Directory size is about 59M.
After few hours of testing I've found that if I do the same command but with limit clause with enormous large value, it works!
EXPORT TO PARQUET (directory = '/data') over (partition by install_date)
   AS select field1, field2 from table where install_date >= 'some_date' limit 10000000000;

Then Vertica exports the same 16 405 136 number of rows, and parquet has the same number of rows! And directory size is around 350M.
Any ideas why?
Thanks.

A: Are you running on multi node Vertica cluster?
If so, then each node exports its "part" (segment) of the data to a file on its own /data directory.
You need to collect those files from all nodes or export to a shared location, e.g NFS / aws S3.
With LIMIT x Vertica first collects the data to the node that executed the query, and then only this node exports the data into a file.
This approach does not take advantage of Vertica's mpp ability, and should be much slower.


text:
Q: How can I use the Stack Exchange API for creating a site like Stack Overflow in another language? How can I use the Stack Exchange API for creating a site like Stack Overflow in another language?
I know there are similar questions but no clear answer. It says in the banner (ads) "use our API to build your own q&a platform". But how? I have looked at Stack Apps and Stack Exchange but couldn't find anything.
So for free or not can I create a site like Stack Overflow of my own? If yes how?
Note: I don't have to run it on my hardware.
And what has Stack Apps to do with this?

A: No you cannot. The API is for interacting with the existing sites. See area51 if you want to propose a new one.


text:
Q: What is C in Standard Form derived from? For Example $9x + 16y = 72$. What is $72$ derived from? Why does dividing $72$ by $9x$ get us to the slope? Why does dividing $72$ by $16y$ get us to the $y$ intercept?

A: The "standard form" of a line is $Ax + By = C$ where $A$ and $B$ are not all zero. Usually we write lines in the slope intercept form $y = mx +b$. Here's how to go from standard form to slope-intercept form - I show all my students this.
From the standard form, divide by $B$ to allow the coefficient of $y$ to be $1$.
$$ \frac{A}{B}x + y = \frac{C}{B} $$
Now let's subtract $\frac{A}{B}x$ on both sides.
$$y = -\frac{A}{B}x + \frac{C}{B} $$
Now we do a thing called "equating coefficients." This process allows us to identify the slope and y-intercept of this line. The coefficient on $x$ is the slope, and the constant term the y-intercept. Hence we may identify $ m = -\frac{A}{B}$ and $b = \frac{C}{B}$.
Of course, you ask about $C$ in particular.  This is a parameter to help define other pieces of the line - namely, intercepts. Changing $C$ changes the location of these intercepts.


text:
Q: Is it possible to pause any video (mediaplayer) APP in Android when pull down the notification panel? Assume I have the AOSP source code, How can I pause the APP in the foreground when pulling down the notification panel? I've googled and find an APP can listen the event onWindowFocusChange and take some action proactively, but how can I pause ANY APP when pulling down the notification panel, without modify every APP respectively (which is impractical)?
Is there a way that I can call the onPause function of any foreground App from the SystemUI process?

A: Assuming that the Android device use the default MediaPlayer, according to this state diagram, you may use the native pause and stop state.
If you only wan't to stop sound, you may probably change the sound volume using a VolumeAutomation ?

A: There are two parts to the solution

*

*detecting notification panel pull

*pausing any media playing app

For detecting notification panel pull you may employ the method suggested by Akash or same code here by Lalith.

In your manifest file
<uses-permission android:name="android.permission.EXPAND_STATUS_BAR" />

In your activity override the onWindowFocusChanged() and write the below code.
@Override
public void onWindowFocusChanged(boolean hasFocus)
{
    try
    {
        if(!hasFocus)
        {
            Object service  = getSystemService("statusbar");
            Class<?> statusbarManager = Class.forName("android.app.StatusBarManager");
            Method collapse = statusbarManager.getMethod("collapse");
            collapse .setAccessible(true);
            collapse .invoke(service);
        }
    }
    catch(Exception ex)
    {
        if(!hasFocus)
        {
            try {
                Object service  = getSystemService("statusbar");
                Class<?> statusbarManager = Class.forName("android.app.StatusBarManager");
                Method collapse = statusbarManager.getMethod("collapse");
                collapse .setAccessible(true);
                collapse .invoke(service);

            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            ex.printStackTrace();
        }
    }
}

For the second part all well designed media players implement Audio Focus Change Listeners. Thus to pause all media player apps you can request temporary or full audio focus depending on whether you want to let the apps play again as soon as notification panel is collapsed.
Use following
AudioManager audioManager = (AudioManager) Context.getSystemService(Context.AUDIO_SERVICE);
playbackAttributes = new AudioAttributes.Builder()
    .setUsage(AudioAttributes.USAGE_GAME)
    .setContentType(AudioAttributes.CONTENT_TYPE_MUSIC)
    .build();
focusRequest = new AudioFocusRequest.Builder(AudioManager.AUDIOFOCUS_GAIN)
    // replace AUDIOFOCUS_GAIN with AUDIOFOCUS_GAIN_TRANSIENT if you want to pause and again resume when notification panel collapsed
    .setAudioAttributes(playbackAttributes)
    .setAcceptsDelayedFocusGain(true)
    .setOnAudioFocusChangeListener(afChangeListener, handler)
    .build();
// to requestAudioFocus and pause other media apps
audioManager.requestAudioFocus(focusRequest);

// to resume again in case you requested AUDIOFOCUS_GAIN_TRANSIENT
audioManager.abandonAudioFocus(afChangeListener);

Don't forget to implement AudioFocusChangeListener
AudioManager.OnAudioFocusChangeListener afChangeListener = new AudioManager.OnAudioFocusChangeListener() {
    @Override
    public void onAudioFocusChange(int focusChange) {
        // leave this empty if you don't need to handle audio focus for your app
    }
};

Is there a way that I can call the onPause function of any foreground App from the SystemUI process?

As far as I have researched system ui process is not accessible. However, you can launch an activity with transparent theme.
In your manifest
<activity android:name=".your.activity" android:theme="@android:style/Theme.Translucent.NoTitleBar" />

see this and I have also personally tested creating transparent activity.
This means that the activity on top now is your transparent activity and the onPause method of the other activity will naturally be called. Once the notification panel is collapsed you can destroy this activity. And to be on safe side you can also set onTouch listener by creating an empty view that feels the screen which should destroy the activity onTouch.

A: You can use below method for detecting the notification panel pull,
In your manifest file
 <uses-permission android:name="android.permission.EXPAND_STATUS_BAR" />

In your activity override the onWindowFocusChanged() and write the below code.
This uses the permission
@Override
public void onWindowFocusChanged(boolean hasFocus)
{
    try
    {
        if(!hasFocus)
        {
            Object service  = getSystemService("statusbar");
            Class<?> statusbarManager = Class.forName("android.app.StatusBarManager");
            Method collapse = statusbarManager.getMethod("collapse");
            collapse .setAccessible(true);
            collapse .invoke(service);
        }
    }
    catch(Exception ex)
    {
        if(!hasFocus)
        {
            try {
                Object service  = getSystemService("statusbar");
                Class<?> statusbarManager = Class.forName("android.app.StatusBarManager");
                Method collapse = statusbarManager.getMethod("collapse");
                collapse .setAccessible(true);
                collapse .invoke(service);

            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            ex.printStackTrace();
        }
    }
}

Then in your app request for audio focus, refer below link
https://developer.android.com/guide/topics/media-apps/audio-focus#java
This will pause audio access for all other apps.


text:
Q: Can't seem to find success with datetime python2.7 I have an application the does what I want with
date_time= "4/23/2013"
new_entry.set_value('lastdate', str(date_time))

But instead of hard coding the value I want to use the python 2.7 function for getting the current time.  I have tried several variations but haven't landed on success yet.
I am hoping someone with more experience can help me. One unsuccessful sample is listed below.
date_time= datetime.utcnow()
new_entry.set_value('lastdate', str(date_time))

Regards,
Chris

A: >>> from datetime import date
>>> date.today().strftime('%m/%d/%Y')
    '05/22/2013'

The strftime method is also available on datetime and time objects.  The full list of formatting options can be found here: http://docs.python.org/2/library/datetime.html#strftime-strptime-behavior

A: I believe what you are looking for is:
import datetime
datetime.datetime.utcnow().strftime("%m/%d%/%Y")

If you don't want to do the double datetime each time
now = datetime.datetime.utcnow()
now.strftime("%m/%d/%Y")


text:
Q: Why might login failures cause SQL 2005 to dump and ditch? Our SQL 2005 server began timing out and finally stopped responding on Oct 26th. The application logs showed a ton of 17883 events leading up to a reboot. After the reboot everything was fine but we were still scratching our heads. Fast forward 6 days... it happened again. Then again 2 days later. The last night. Today it has happened three times to far. The timeline is fairly predictable when it happens:

*

*Trans log backups.

*Login failure for "user2".

*Minidump

*Another minidump for the scheduler

*Repeated 17883 events.

*Server fails little by little until it won't accept any requests.

*Reboot is all that gets us going again (a band-aid)

Interesting, though, is that the server box itself doesn't seem to have any problems. CPU usage is normal. Network connectivity is fine. We can remote in and look at logs. Management studio does eventually bog down, though.
Today, for the first time, we tried stopping services instead of a reboot. All services stopped on their own except for the SQL Server service. We finally did an "end task" on that one and were able to bring everything back up. It worked fine for about 30 minutes until we started seeing timeouts and 17883's again. This time, probably because we didn't reboot all the way, we saw a bunch of 844 events mixed in with the 17883's.
Our entire tech team here is scratching heads... some ideas we're kicking around:

*

*MS Cumulative Update hit around the same time as when we first had a problem. Since then, we've rolled it back. Maybe it didn't rollback all the way.

*The situation looks and feels like an unhandled "stack overflow" (no relation) in that it starts small and compounds over time. Problem with this is that there isn't significant CPU usage. At any rate, we're not ruling SQL 2005 bug out at all.

*Maybe we added one too many import processes and have reached our limit on this box. (hard to believe).

Looking at SQLDUMP0151.log at the time of one of the crashes. There are some "login failures" and then there are two stack dumps. 1st a normal stack dump, 2nd for a scheduler dump. Here's a snippet: (sorry for the lack of line breaks)

2009-11-10 11:59:14.95 spid63      Using 'xpsqlbot.dll' version '2005.90.3042' to execute extended stored procedure 'xp_qv'. This is an informational message only; no user action is required.
  2009-11-10 11:59:15.09 spid63      Using 'xplog70.dll' version '2005.90.3042' to execute extended stored procedure 'xp_msver'. This is an informational message only; no user action is required.
  2009-11-10 12:02:33.24 Logon       Error: 18456, Severity: 14, State: 16.
  2009-11-10 12:02:33.24 Logon       Login failed for user 'standard_user2'. [CLIENT: 50.36.172.101]
  2009-11-10 12:08:21.12 Logon       Error: 18456, Severity: 14, State: 16.
  2009-11-10 12:08:21.12 Logon       Login failed for user 'standard_user2'. [CLIENT: 50.36.172.101]
  2009-11-10 12:13:49.38 Logon       Error: 18456, Severity: 14, State: 16.
  2009-11-10 12:13:49.38 Logon       Login failed for user 'standard_user2'. [CLIENT: 50.36.172.101]
  2009-11-10 12:15:16.88 Logon       Error: 18456, Severity: 14, State: 16.
  2009-11-10 12:15:16.88 Logon       Login failed for user 'standard_user2'. [CLIENT: 50.36.172.101]
  2009-11-10 12:18:24.41 Logon       Error: 18456, Severity: 14, State: 16.
  2009-11-10 12:18:24.41 Logon       Login failed for user 'standard_user2'. [CLIENT: 50.36.172.101]
  2009-11-10 12:18:38.88 spid111     Using 'dbghelp.dll' version '4.0.5'
  2009-11-10 12:18:39.02 spid111     ***Stack Dump being sent to C:\Program Files\Microsoft SQL Server\MSSQL.1\MSSQL\LOG\SQLDump0149.txt
  2009-11-10 12:18:39.02 spid111     SqlDumpExceptionHandler: Process 111 generated fatal exception c0000005 EXCEPTION_ACCESS_VIOLATION. SQL Server is terminating this process.
  2009-11-10 12:18:39.02 spid111     * *******************************************************************************
  2009-11-10 12:18:39.02 spid111     *
  2009-11-10 12:18:39.02 spid111     * BEGIN STACK DUMP:
  2009-11-10 12:18:39.02 spid111     *   11/10/09 12:18:39 spid 111
  2009-11-10 12:18:39.02 spid111     *
  2009-11-10 12:18:39.02 spid111     *
  2009-11-10 12:18:39.02 spid111     *   Exception Address = 0159D56F Module(sqlservr+0059D56F)
  2009-11-10 12:18:39.02 spid111     *   Exception Code    = c0000005 EXCEPTION_ACCESS_VIOLATION
  2009-11-10 12:18:39.02 spid111     *   Access Violation occurred writing address 00000000
  2009-11-10 12:18:39.02 spid111     * Input Buffer 138 bytes -
  2009-11-10 12:18:39.02 spid111     *  " N R S C _ P T A  22 00 4e 00 52 00 53 00 43 00 5f 00 50 00 54 00 41 00
  2009-11-10 12:18:39.02 spid111     *  C _ Q A . d b o .  43 00 5f 00 51 00 41 00 2e 00 64 00 62 00 6f 00 2e 00
  2009-11-10 12:18:39.02 spid111     *  U s p S e l N e x  55 00 73 00 70 00 53 00 65 00 6c 00 4e 00 65 00 78 00
  2009-11-10 12:18:39.02 spid111     *  t A c c o u n t    74 00 41 00 63 00 63 00 6f 00 75 00 6e 00 74 00 00 00
  2009-11-10 12:18:39.02 spid111     *   @ i n t F o r m I 0a 40 00 69 00 6e 00 74 00 46 00 6f 00 72 00 6d 00 49
  2009-11-10 12:18:39.02 spid111     *   D  &  8      @ t x  00 44 00 00 26 04 04 38 00 00 00 09 40 00 74 00 78 00
  2009-11-10 12:18:39.02 spid111     *  t A l i a s  §      74 00 41 00 6c 00 69 00 61 00 73 00 00 a7 0f 00 09 04
  2009-11-10 12:18:39.02 spid111     *  Ð    GQE9732       d0 00 00 07 00 47 51 45 39 37 33 32
  2009-11-10 12:18:39.02 spid111     *
  2009-11-10 12:18:39.02 spid111     *
  2009-11-10 12:18:39.02 spid111     *  MODULE                          BASE      END       SIZE
  2009-11-10 12:18:39.02 spid111     * sqlservr                       01000000  02C09FFF  01c0a000
  2009-11-10 12:18:39.02 spid111     * ntdll                          7C800000  7C8C1FFF  000c2000
  2009-11-10 12:18:39.02 spid111     * kernel32                       77E40000  77F41FFF  00102000

A: UspSelNex - is this a stored proc that is always running when you have your problem?


text:
Q: Updating 'Created By' field in SP2010 programatically I'm trying to import data from an .xml file to a custom list in SP2010(created programmatically).
I'm able to create and update all fields except 'Created By' as it says that "Cannot update read only field".
Is there any way that I can update the "Created By" field? Only Programmatically
This is my XML code.
Note : I don't have user Id. I only have Display Name. I need  field from xml code to be updated in SP.
<?xml version="1.0" encoding="iso-8859-1" ?>

<XMLExport DBName="local_Report DB">

<documentexport DOCID="DJHD7WJWA9APWPWO457C20004FE01A">

<Business>

<![CDATA[ Bank Subsidiary]]>

</Business>

<Company>

<![CDATA[ DMS Softies, India ]]>

</Company>

<Region />

<Author>

<![CDATA[ Dushyant M Sharma]]>

</Author>

</documentexport>

</XMLExport>

A: You can use the SPBuiltInFieldId.Author:
listItem[SPBuiltInFieldId.Author] = new SPFieldUserValue(web, userId, userName);
listItem.SystemUpdate(false);

A: you can also do:
SPFieldUserValue user = new SPFieldUserValue(Web, Web.CurrentUser.ID, Web.CurrentUser.LoginName);

listItem["Author"] = user;
listItem["Editor"] = user;

listItem.Update();

web.Update();

SPFieldUserValue can be hard coded or as iv done getting the current user, web is the SPWeb object and listItem is the SPListItem object


text:
Q: Filling in missing date/times in my pd.date_range I have a column of data which looks like the following:

I am trying to set a range of the entire month:
rng = pd.date_range('2016-09-01 00:00:00', '2016-09-30 23:59:58', freq='S')
But my column of data (above) is missing a few hours, and I am unsure where (since my data is 2 million rows large.
I tried to use the reindex command, but it instead seemed to have filled everyhthing with zeroes.
The code that I was using is as follows:
df = pd.DataFrame(df_csv)
rng = pd.date_range('2016-09-01 00:00:00', '2016-09-30 23:59:58', freq='S')
df = df.reindex(rng,fill_value=0.0)

How do I properly fill in the missing date/times without filling everything with a 0?

A: I think you need set_index from column date first, then is possible use reindex:
#cast column date if dtype is not datetime
df.date = pd.to_datetime(df.date)
df = df.set_index('date').reindex(rng,fill_value=0.0)

You get all NaN values, because reindexing int index by datetime values (After using fill_value=0.0 all NaN are replaced to 0.0).
Also if column date is sorted, you can use more general solution with selecting first and last value of column date:
start_date = df.date.iat[0]
end_date = df.date.iat[-1]
rng = pd.date_range(start_date, end_date, freq='S')


text:
Q: Ansible win_shell ad-hoc syntax I'm trying to run the win_shell Ansible module as an ad-hoc command with the "anisble" program instead of in a playbook.  Here is the playbook syntax:
  tasks:
      - win_shell: foo.exe
        args:
              chdir: 'C:\bar'
              executable: cmd

I've tried various permutations such as:
ansible \* -i windows.inventory -k -m win_shell -a "foo" -a "executable=cmd"
ansible \* -i windows.inventory -k -m win_shell -a "foo" -a "args: executable=cmd"
ansible \* -i windows.inventory -k -m win_shell -a "foo" -a "args=executable: cmd"
ansible \* -i windows.inventory -k -m win_shell -a "foo" -a "args=(executable=cmd)"
ansible \* -i windows.inventory -k -m win_shell -a "foo" -a "args={{arg}}" -e '{arg: {executable: cmd} {chdir: "C:\\bar"}}'
ansible \* -i windows.inventory -k -m win_shell -a "foo" -a "args={{arg}}" -e '{arg: {executable: cmd},{chdir: "C:\\bar"}}'
ansible \* -i windows.inventory -k -m win_shell -a "foo" -a "args={{arg}}" -e '{"arg": {"executable": "cmd"},{"chdir": "C:\\bar"}}'
ansible \* -i windows.inventory -k -m win_shell -a "foo" -a "args={{arg}}" -e '{"arg": {"executable": "cmd"},{"chdir": "C:\\bar"}}'
ansible \* -i windows.inventory -k -m win_shell -a "foo" -a "args={{arg}}" -e '{"arg": {"executable": "cmd"}}'

None of these work.
I can do it this way:
ansible \* -i windows.inventory -k -m win_shell -a 'cmd /c "cd C:\bar & foo"'

...but I want to know how to do it by specify the "args".

A: You should use Ansible inline syntax and a single -a argument, without split.
Here's how the task translates to the CLI arguments:
ansible \* -i windows.inventory -k -m win_shell -a 'foo.exe chdir=C:\bar executable=cmd'


text:
Q: Why margin is included in my standard box model? I have the following HTML

Article

Blog

and this css
.container {
    width: 1200px;
}
.article {
    background-color: red;
    float: left;
    width: 600px;
}

.blog {
    background-color: blue;
    width: 600px;
    float: left;
}

now they are perfecly putted inside the parent because 2 x 600px = 1200px ( the parent's width ).
But if i put margin in blog
.blog {
    background-color: blue;
    width: 600px;
    float: left;
    margin: 20px;
}

then the layout is broken.
On the mozilla documentation is mentioned that
https://developer.mozilla.org/en-US/docs/Learn/CSS/Building_blocks/The_box_model#the_standard_css_box_model
standard box model does not include the margin it self.
So only padding and border. But i give not padding and border rto my blog div i give only margin and i expect the layout to not be broken and to have still actuil width of 600px.
Can somoene explain me what is happening here and why my layout is broken

A: It is worth noting that margin will apply outside the borders of the element and padding will apply inside the element.
To understand this better consider the following examples.
Margin

* {box-sizing: border-box;}
.parent {width: 200px; height: 220px; background: limegreen;}
.child {height: 200px; width: 100%; background: red; margin: 20px;}

As you can see that the child element is parted way from its parent's initial position and creating a space around it.
Padding

*{box-sizing: border-box;}
.parent1 {width: 200px; height: 220px; background: limegreen;}
.child1 {height: 200px; width: 100%; background: red; padding: 20px;}

Here the padding is applied inside the child element so it won't leave the parent's width


text:
Q: Random number generation on Spartan-3E I need to generate pseudo-random numbers for my genetic algorithm on a Spartan-3E FPGA and i want to implement it in verilog: could you give me any pointers on this?

A: You've already got some good answers, but I'll just point out the canonical guide to LFSRs in FPGAs is here:
http://www.xilinx.com/support/documentation/application_notes/xapp052.pdf
It's a bit Xilinx specific in places (which is OK for your FPGA :) but the principles are transferable to others.

A: Typically you'd use the IEEE.math_real uniform function
use IEEE.math_real.all;
procedure UNIFORM (variable Seed1,Seed2:inout integer; variable X:out real);

But do a tiny bit a research on pseudo random number generators (PRNGs) and you'll find many variants that are simple LFSR's - which look remarkably similar to CRC generators.
Here are several resources if you want to roll your own starting from existing, working PRNGs:
http://www.opencores.org/?do=project&who=systemc_rng
http://verificationguild.com/modules.php?name=Downloads&d_op=viewdownload&cid=3
Here's a CRC VHDL code generator:
http://www.easics.be/webtools/crctool

A: There is an online tool that can generate Verilog or VHDL code for a pseudo-random number generator. It's on OutputLogic.com

A: The pointer above to OpenCores has a file in the verilog folder called: rng.v
I have used it in a Spartan-3AN and it works great. My code used the random number generator to select a random PWM after I programmed the part and it covered all the selectable PWMs.

A: Of course the random generator by Adam is not synthesizable! You have to explicitly create an LFSR.
Following example might help. It is an 8-bit maximal LFSR
module lfsr(input clk, reset, en, output reg [7:0] q);
  always @(posedge clk or posedge reset) begin
    if (reset)
      q <= 8'd1; // can be anything except zero
    else if (en)
      q <= {q[6:0], q[7] ^ q[5] ^ q[4] ^ q[3]}; // polynomial for maximal LFSR
  end
endmodule;

A: I agree with the LFSR.  I have made one before and it is used for encryption.


text:
Q: How to evaluate a partially alternating series. $\sum_{n=0}^{\infty} \frac{\cos{(n\pi/3)}}{n!}$ = $\sqrt{e} \cos(\sqrt{3}/2)$
Wolfram alpha gave me this answer for the sum. First I'd like to know if I can use the alternating series test to prove that this sum is convergent (absolutely or conditionally). Then I'd like to know how wolfram came up with this answer for the sum.

A: \begin{eqnarray}
\sum_{n=0}^\infty\frac{\cos(n\pi/3)}{n!}&=&\Re\sum_{n=0}^\infty\frac{e^{in\pi/3}}{n!}=\Re\exp(e^{i\pi/3})=\Re\exp(\cos\pi/3+i\sin\pi/3)\\
&=&\Re\exp(1/2+i\sqrt{3}/2)=e^{1/2}\cos(\sqrt{3}/2)
\end{eqnarray}

A: The easiest way to get the sum is using Euler's formula $e^{i\theta} = \cos\theta+i\sin\theta$.  What you have is the real part of $\sum_{n=0}^\infty \frac{1}{n!} \bigl( e^{i \pi / 3} \bigr)^n$, which is $\exp(e^{i\pi/3})$.  Then, $e^{i\pi/3}=\frac{1+i\sqrt{3}}{2}$, so $\exp(e^{i\pi/3})=e^{1/2}\, e^{i \sqrt{3}/2}$, and taking the real part gives the cosine.
What you need to prove, though, doesn't require any of that.  Remember that the cosine is bounded between $-1$ and $+1$, and that $n!$ grows very fast.  In fact, $\sum_{n=0}^\infty \frac{1}{n!} = e$ is certainly convergent, without any need for alternating properties.  The alternating series test is not the best way to go.


text:
Q: Is it possible to avoid the singularity problem of a 2nd order differential equations by restricting the solution range? I would greatly appreciate your help in implementation of Mathematica for solving a 2nd order differential equation expressing some important engineering problem.
Apparently, this equation has no analytical solution. Therefore I attempt to solve it numerically with maximal possible approach to the analytical effect, while using the ParametricNDSolve command.
The equation has 3 variables: n, Ω and ψ and differentiation is by z. Actually, z = 1. n can be above zero and below it, however the values rarely exceed ±3. Ω and ψ are positive numbers and they can reach big values. As the 1st approach I have defined n = 3. The expression is:
Solution = ParametricNDSolve[{Ω f''[z] - f'[z] - ψ f[z]^n == 0,
                              f[0] - Ω f'[0] == 1,f'[1] == 0}, f, {z, 1, 1}, {Ω, ψ}];

Unfortunately Mathematica is unable restrict itself to z = 1 and produces the singularity messages at z < 1.
My question is thus following: is it possible to restrict the solution to z=1 without attempting to solve at z<1?

A: Because boundary conditions are specified at z = 0 and at z = 1, ParametricNDSolve must integrate between those two endpoints. However, this does not in general prevent obtaining a solution.
s = ParametricNDSolveValue[{Ω f''[z] - f'[z] - ψ f[z]^3 == 0,
    f[0] - Ω f'[0] == 1, f'[1] == 0}, f, {z, 0, 1}, {Ω, ψ}];

which then can be evaluated at s[Ω, ψ][1].  For instance,
Plot[Evaluate[Table[s[Ω, ψ][1], {ψ, 5}]], {Ω, 1, 5}, AxesLabel -> {Ω, f}]

It is the case that stiffness is encountered at small Ω for ψ == 5.
Addendum
The parameter ψ can be eliminated by rescaling f by ψ^(-1/(n - 1)), which reduces parameter space from two to one dimensions.  With the rescaled f designated g,
t = ParametricNDSolveValue[{Ω g''[z] - g'[z] - g[z]^3 == 0, g[0] - Ω g'[0] == 1,
    g'[1] == 0}, g, {z, 0, 1}, {Ω}]
Plot[t[Ω][1], {Ω, 1, 20}, PlotRange -> {{0, 20}, All}, AxesLabel ->
    {"Ω", "f \!\(\*SuperscriptBox[\(ψ\), FractionBox[\(1\), \(n - 1\)]]\)"


text:
Q: Ajax call works on one host but not on another I am making an ajax call to the UPS address validation webservice.
If i make the call from my application with this domain it works (http://serverone.org/addrvalidator)
But it doesn't work if i use the other domain or an ip address instead of the domain (http://servertwo.org/addrvalidator).
Both the domain names are intranet only domains.
Any help appreciate, thanks in advance.

A: take a look at this, probably this is the answer you were looking for:
Cross-site AJAX requests


text:
Q: Cannot convert UTC to UTC+03:30 using Angular date pipe In my Angular project, I have a table with a timestamp column. Its data is being filled with an HTTP request to the server.
The format in which the server sends back the timestamp is this: 2020-10-13T12:09:42.9762
I'm trying to use the timezone parameter from the angular date pipe to format my date and show it in Iran standard time which is UTC + 3:30 like so,
       <tr *ngFor="let row of tableData; let i = index">
          <td>
            {{ row.timeStamp | date: 'short':'+0330' }}
          </td>
       </tr>

But it's not working. Only the short part is working in the pipe. The +0330 part is not doing anything.
Can anyone tell me what I'm doing wrong? or suggest an alternative way for converting this UTC date and time 2020-10-13T12:09:42.9762 to Iran Standard Time (IRST)? which is UTC+03:30 by the way.

A: Just need add UTC designator in the end of your original date and no need to set timezone in angular date pipe

Times are expressed in UTC (Coordinated Universal Time), with a special UTC designator ("Z")

{{ '2020-10-13T12:09:42.9762Z' | date:'short' }

if you need more information you can see date format specification of w3
w3 time format specification


text:
Q: Getting CTRL characters with NCurses How are control keys obtained from the NCurses library? I need to know if a result from getch () is a character pressed with ctrl, and what character was pressed with it. I googled "ctrl keys ncurses" and "control keys ncurses" without much results.
I know from a quick test that (at least in my case) all the CTRL characters are related to the characters by a difference of 96.
ie
akey is 97
^Akey is 1
bkey is 98
^Bkey is 2
ckey is 99
^Ckey is 3

But this doesn't seem like reliable information to write a program with. Does anyone know a way of doing this?

A: Beyond the straight ASCII-tests, with ncurses you can use the unctrl or keyname functions to return a string which has the relevant information parsed:

*

*if the length of the returned string is one, it is a simple character

*if the length is two, and the first character is ^, then it is a control character and the corresponding canonical pressed-with character is the second character of the string.
Keep in mind that there may be several possibilities for pressed-with, since Shift is ignored, and there are a few special cases such as ControlSpace versus Control@ which can produce the same result.
That's with ncurses: other implementations of unctrl may return a null pointer for character codes 128-255.  X/Open Curses is vague on what should be done in that case.

A: That actually is reliable (but with 64, not 96). Ctrl+A all the way through Ctrl-_ are handled properly (use of Ctrl-@ is discouraged due to other meanings of NUL).


text:
Q: How to fit a set of parametrized data to a parametrized distribution? I have a time series $d_i(a)$ which depends on the parameter $a$. On the other hand, I have a sequence of normal distributions $\mathcal{N}(0,Q_i(a))$, where the variance $Q_i$ depends on time and depends on the parameter $a$. How do I estimate $a$ so that $d_i\sim \mathcal{N}(0,Q_i)$?

A: You can just use a maximum likelihood estimator (MLE) $\hat a=\hat a_{\text{MLE}}$ of $a$.
Since you do not say anything about the dependence between the $d_i(a)$'s, let us assume they are independent. Let $X_i:=d_i(a)$ for $i=1,\dots,n$. Then the joint likelihood of the $d_i(a)$'s is
\begin{equation*}
    L(a)=(2\pi)^{-n/2}\prod_{i=1}^n \Big(Q_i(a)^{-1/2}\;\exp\Big(-\frac{X_i^2}{2Q_i(a)}\Big)\Big),
\end{equation*}
which we want to maximize in $a$. This is equivalent to maximizing
\begin{equation*}
    \ell(a):=\ln L(a)+\frac n2\,\ln(2\pi)=-\frac12\,\sum_{i=1}^n \Big(\ln Q_i(a)+\frac{X_i^2}{Q_i(a)}\Big)
\end{equation*}
in $a$.
If the set (say $A$) of all possible values of $a$ is a subset of the real line and if
the maximum of $L(a)$ is attained at a point $a_*$ in the interior of $A$ and if the functions $Q_i$ are differentiable in a neighborhood of $a_*$, then $a_*$ is a root of the equation
\begin{equation*}
    0=-2\ell'(a)=\sum_{i=1}^n \Big[\Big(\frac{1}{Q_i(a)}-\frac{X_i^2}{Q_i(a)^2}\Big)Q_i'(a)\Big]
\end{equation*}
in $a$.
For instance, if $A=(0,\infty)$ and $Q_i(a)=ia$ for $a\in A$, then $\hat a=a_*=\frac1n\,\sum_{i=1}^n \frac{X_i^2}i$.


text:
Q: How to compare 2 JSONs in python only with keys I checked this thread on comparing JSON objects.
JSON a:
{
    "errors": [
        {"error": "invalid", "field": "email"},
        {"error": "required", "field": "name"}
    ],
    "success": false
}

`
JSON b: with extra field
{
    "errors": [
        {"error": "invalid", "field": "email"},
        {"error": "required", "field": "name"},
        { "key1": : "value2", }

    ],
    "success": false
}

I want to compare these 2 jsons in python such that it will tell me

*

*IF JSON is same and found extra key-value pair then it should give result that
 Found new field: { "key1: : "value2", }  and rest of the json is same.

*If JSON is exactly same means if keys are matching in order then it will say TRUE.

*If JSON Keys are same but values are different then it will say, for the below keys the values are different.

A: you can do something like this,
import json

a = json.loads(json_1) #your json
b = json.loads(json_2) #json you want to compare

#iterating through all keys in b

for key in b.keys():
    value = b[key]
    if key not in a:
       print "found new key {0} with value {1}".format(key, value)
    else:
       #check if values are not same
       if a[key] != value: print "for key %s values are different" % key

A: If you want to print only the difference in subjson (and not the whole structure from the root), you may want to use recursive request
def json_compare(json1, json2):
    #Compare all keys
    for key in json1.keys():
        #if key exist in json2:
        if key in json2.keys():
            #If subjson
            if type(json1[key]) == dict:
                json_compare(json1[key], json2[key])
            else:
                if json1[key] != json2[key]:
                    print "These entries are different:"
                    print json1[key]
                    print json2[key]
        else:
            print "found new key in json1 %r" % key
    return True


text:
Q: Excel not inserting leading zero I am using Office OpenXml to write to an Excel file.  The file is a template so it already has all my headers and formatting for my columns.  I am inserting numbers that have leading zeroes to a "special" column which is basically a 10 digit number.  However in my code I can see that it is setting the value to for example 0000000004.  The result in the sheet with a value of 4 in that cell and the actual cell showing 0000000004.
Here is my code to write to the cell.
  if (reader[2].ToString().Length < 9)
  {

        myworksheet.Cell(firstrow, 12).Value = reader[2].ToString(); //0045678945

  }
  else
  {
        myworksheet.Cell(firstrow, 12).Value = reader[2].ToString().Substring(0, 9); //0045678945

  }

when I open the excel sheet like I stated above my value is 45678945 instead of 0045678945
Any help would be appreciated.

A: The easiest way to get the result you want is to prepend an apostrophe to the value you put in the cell - this tells Excel it is a string:
Cell.Value= "'" & "000123"

Will show up as 000123
Here is a bit of code to show how things work (at least how they work for me, in Excel 2010):
Sub testFormat()
[A1].Value = "000123"
[A2].Value = "'000123"
[A3].Value = "000123"
[A3].NumberFormat = "@"
[A4].Value = "'000123"
[A4].NumberFormat = "@"
End Sub

The result of this is as follows:

As you can see, there are three cells that show the leading zeros:

*

*A cell into which I entered the string with an apostrophe in front

*A cell that was formatted with the "@" (="text") format

*A cell that had the apostrophe AND the text formatting

I'm not sure what you did to make the apostrophe appear in your spreadsheet... But I'm hoping the above will inspire you to solve your problem.

A: If I understand correctly:
Excel shows numbers with leading zeroes, reading them from C# via OOXML you don't see the leading zeroes.
Chances are Excel is setting some formatting rules instead of storing the actual leading zeroes.
Several ways to counteract that. Here are the "cheapest" ones that come to mind, pick one:

*

*format the column in Excel as text

*in C# code don't expect the leading zeroes and instead add them

A: In order to get leading zeros to not be truncated from within Excel you need to set the number format for the cells to Text.

A: I believe if you set the cell's DataType to either a String or SharedString the leading 0's will be preserved.  Excel will see this as text and just treat the value literally and not try to apply any formatting rules.
cell.DataType = new EnumValue<CellValues>( CellValues.SharedString );

OR
    cell.DataType = new EnumValue( CellValues.String );

A: If you are using a DataTable you need to Take another DataTable and then you need to iterate through entire cells in the datatable and prepend the cells text with space i.e with '&nbsp';.We cannot modify the rows in the same table because it will throw an exception saying "Collection was Modified".We have to take a new datatable.
Consider the following code.
    //To get the result with leading zero's in excel this code is written.
    DataTable dtUpdated=new DataTable();
    //This gives similar schema to the new datatable
    dtUpdated = dtReports.Clone();
        foreach (DataRow row in dtReports.Rows)
        {
            for (int i = 0; i < dtReports.Columns.Count; i++)
            {
                string oldVal = row[i].ToString();
                string newVal = " "+oldVal;
                row[i] = newVal;
            }
            dtUpdated.ImportRow(row);
        }

We can bind this updated table to datagrid so that it can be useful for Excel Conversion.


text:
Q: Calculate Density based on Lat/Lon I'm very sorry to say that I do not have any sample code for this question.  The reason being, I've been looking for a way to do this and I've got no ideas.  I'm not looking for specific code help, more like some general guidance on where to start.
I have lat/lon for people living around California. Based on the geographic groupings of this data (county, city, zip, etc) I'm supposed to figure out a density score.  Basically, how many points per square mile, or something along those lines.  I have been looking for ways to do this, and unfortunately I haven't found anything that seems right. I have lat/lon/geographic boundary columns in my data, so I can group by the various geographic types, but I'd like to rely on the lat/lon for the density scoring.
Again, I'm sorry that I don't have any specific code to share.  Any suggestions on packages or tools for this problem would be greatly appreciated!
I'm comfortable with both R and Python, but my colleagues would prefer python driven solutions.
Below is some sample data using zip codes and lon/lat (in this order).
Zip Longitude   Latitude
95223   -120.045063 38.467308
95223   -120.040889 38.465436
95223   -120.072499 38.454202
95223   -120.049251 38.462058
95223   -120.041697 38.462194
95223   -120.045757 38.470637
96120   -119.959615 38.703965
96120   -119.937276 38.741337
96120   -119.9382   38.739344
96120   -119.901794 38.776584
96120   -119.936094 38.741865
96120   -119.957587 38.707533
96120   -119.93456  38.74194
95646   -120.072087 38.687061
95646   -120.066752 38.684097
95646   -120.069591 38.684193
95646   -120.071754 38.699738
95646   -120.066111 38.685164
95646   -120.067082 38.683881
95646   -120.070923 38.696049
95646   -120.068004 38.683615
95646   -120.07161  38.699309
95646   -120.07385  38.690719
95646   -120.066131 38.685019
95646   -120.071263 38.686228

A: From the Pyviz Examples page for census mapping here:
Example code for mapping population density:
https://examples.pyviz.org/census/census.html
Creating your boundaries:
The answer to this question covers this quite well, giving a list of boundary detection algorithms:
https://gis.stackexchange.com/questions/5426/finding-boundary-co-ordinates-from-given-set-of-point-co-ordinates
Finding the area of your polygon(AreaOfZipcode):
How to calculate the area of a polygon on the earth's surface using python?
Calculate Zipcode Populations with an accumulator algorithm.
Then:
PopDensity = PopOfZipcode/AreaOfZipcode
Define your high density/mid-density/low-density boundaries and then assign your zipcodes to each bucket.


text:
Q: How to access an XML value in Node-RED I'm receiving an XML response from an HTTP GET request which I need a specific value from. I transformed it in an JavaScript object. How can I access it's values, for example the CompName?
I thought I can use the function node, but couldn't figure out, how exactly.

A: In the Debug sidebar, when you hover over an message element, a set of buttons appears on the right-hand side.
The first of these, when clicked, will copy the path to the selected element, relative to the msg object. That will help you figure out the path you need for any particular element
In this instance, you'll find the CompName in the screenshot you've shared is:
msg.payload.feed.entry[0].content[0]['m:properties'][0]['d:CompName'][0]


text:
Q: How to manage newer Ruby installations in macOS without intervening with the default Ruby installations? macOS comes with some default ruby installations, more here, that I do not want to overwrite by running gems commands as sudo. I tried rbenv, instructed here, but I am getting a permission error in the last command gem update --system such that
brew update
brew install ruby
echo 'export PATH=/usr/local/Cellar/ruby/2.4.1_1/bin:$PATH' >> ~/.bash_profile #bash
brew install rbenv ruby-build
echo 'export PATH="$HOME/.rbenv/bin:$PATH"' >> ~/.bash_profile  # bash
echo 'eval "$(rbenv init -)"' >> ~/.bash_profile               # bash
rbenv install 2.4.1
rbenv local 2.4.1
rbenv global 2.4.1
rbenv rehash
gem update --system
Updating rubygems-update
ERROR: While executing gem ... (Gem::FilePermissionError) You don't have write permissions for the /Library/Ruby/Gems/2.0.0 directory.

I do not want to intervene with the default ruby installation in macOS, not to get the need for a fresh installation of the whole OS.
What is a proper way to install newer version of Ruby on macOS without intervening with the default ruby?
Further questions on Ruby in macOS

*

*rbenv not overriding default Ruby version

*How to install ruby gems without sudo

*Which version(s) of Mac OS X have Ruby installed by default?

A: Looks like you only update PATH etc in the shell profiles, but not in the running shell. Try to run the commands from rbenv onwards in a newly spawned shell.


text:
Q: IOS TableView multi Select by section I am currently developing an app for iPhone and i have a spent time looking at how to select multiple rows in a table view however the answers i found did not include groups. I have a table as seen below with two groups one for client selection and the other for navigation links i would like to display the selected item for both groups rather than the entire table but i have had no luck finding any answers for this.
i understand you check can what section the row is in but i am not sure how to implement this. Any suggestions would be greatly appreciated. Additionally i do know how to select rows by changing the cell style depending on if it has been selected or not but its doing this for two groups im stuck on. Again thank you for any help.

A: This is the code to allow for multiple selection:
- (void)viewDidLoad {
    [super viewDidLoad];
    self.tableView.allowsMultipleSelection = YES;
}

Perhaps you are looking for something like this to execute code based on which section the selection is in:
#define CLIENT_SECTION 0
#define MENU_SECTION 1
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == CLIENT_SECTION) {
        // execute code
    } else if (indexPath.section == MENU_SECTION) {
        // execute code
    }
}

A: -(void)viewDidLoad{
[myTable setMultipleTouchEnabled:YES];

}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{

if(indexPath.section == 0)
{
[[myTable cellForRowAtIndexPath:indexPath.row] setAccessoryType:UITableViewCellAccessoryCheckmark];
}
else
{
[[myTable cellForRowAtIndexPath:indexPath.row] setAccessoryType:UITableViewCellAccessoryCheckmark];
}

}


text:
Q: How to avoid short-circuit operation without using bitwise operators I am trying to see if there is a better way of writing the following:
if ((DirectoryDetailsPath == null) & (FileDetailsPath == null))
{
  Console.WriteLine("Error: Path for 'Directory' or 'File' has to be specified.");

}

without using the Bitwise "&" operator.  I would perfer using the logical operators, but becuase of short-circuit I am unable to evaluate both fields.
I only want to see an error if both fields are "null".
Thanks

A: I only want to see an error if both fields are "null".
Then try using &&:
if ((DirectoryDetailsPath == null) && (FileDetailsPath == null))
{
  Console.WriteLine("Error: Path for 'Directory' or 'File' has to be specified.");

}

More information:
The above solution will short-circuit if the first condition is false.   This still satisfies the requirement of only writing the output if both values are null.

A: If you really must evaluate both conditions and don't want to use the bitwise operator, do it outside of the if statement.
bool isDirectoryDetailsPathNull = DirectoryDetailsPath == null;
bool isFileDetailsPathNull = FileDetailsPath == null;

if (isDirectoryDetailsPathNull && isFileDetailsPathNull)
{
    Console.WriteLine("Error: Path for 'Directory' or 'File' has to be specified.");
}

However, there is really no point in this.  The compiler will probably decide to inline the variables, effectively giving you this, which is what you said you don't want.
if ((DirectoryDetailsPath == null) && (FileDetailsPath == null))
{
    Console.WriteLine("Error: Path for 'Directory' or 'File' has to be specified.");
}


text:
Q: assembly getting the sum of inputs I have a problem in assembly in which I could not get the sum and product of  2 inputted numbers. I'm still working on getting the sum, but it seems like I could not get it. I'm using emu8086. Could you help me fixing these codes below. I Could not also get their products yet. i'm a newbie. Thanks.
.MODEL SMALL
.STACK 1000
.DATA
MSGA DB 13,10,"Input first number: ","$"
MSGB DB 13,10,"Input second number:","$"
MSGC DB 13,10,"The sum is: ","$"
NUM1 db ?
NUM2 db ?
NUM3 db ?
.CODE
MAIN PROC NEAR
MOV AX, @DATA
MOV DS, AX
LEA DX, MSGA
MOV AH, 09h
INT 21h
MOV AH, 01
INT 21H
SUB AL, '0'
MOV BL, AL
MOV AH, 01
INT 21H
SUB AL, '0'
MOV CL, AL
LEA DX, MSGB
MOV AH, 09h
INT 21h
MOV AH, 01
INT 21H
SUB AL, '0'
MOV DL, AL
MOV AH, 01
INT 21H
SUB AL, '0'
MOV DH, AL
MOV AL, CL
MOV AH, BL
ADD AL, DH
AAA
ADD AH, DL
MOV NUM1, AL
ADD NUM1, '0'
CMP AH, 9
JLE NOT_3DIGIT
IS_3DIGIT:
MOV AL, AH
SUB AH, AH
ADD AL, 0
AAA
ADD AH, 0
MOV NUM2, AL
MOV NUM3, AH
ADD NUM2, '0'
ADD NUM3, '0'
LEA DX, MSGC
MOV AH, 09h
INT 21h
MOV DL, NUM3
MOV AH, 02H
INT 21h
MOV DL, NUM2
MOV AH, 02H
INT 21h
JMP PRINT_LASTDIGIT

NOT_3DIGIT:
MOV NUM2, AH
ADD NUM2, '0'
LEA DX, MSGC
MOV AH, 09h
INT 21h
MOV DL, NUM2
MOV AH, 02H
INT 21h

PRINT_LASTDIGIT:
MOV DL, NUM1
MOV AH, 02H
INT 21h

EXIT:
MOV AH, 4Ch
INT 21h
MAIN ENDP
END MAIN

A: You are taking 2 digit Input, so after Multiplication you want to convert the answer back to it's original [decimal] form for displaying.
That can be done by dividing it by 10 and then displaying coefficient and Remainder accordingly, Here is a code for Multiplication that firstly takes a 2 digit numbers and then multiply it with another single digit number,
But that is just to give you an Idea:
.model small
.stack
.data
msg1 db 10,13,'First Value:','$';
msg2 db 10,13,'Second Value:','$';
msg3 db 10,13,'multiplication:','$';
second db ?
temp db ?
num1 db ?
num2 db ?
a db 10

.code
main proc
mov ax,@data
mov ds,ax
mov ah,09h
lea dx,msg1
int 21h
mov ah,01h
int 21h
sub al,30h
mul a
mov temp,al
mov ah,01h
int 21h
sub al,30h
add temp,al
mov [bx],al
mov ah,09h
lea dx,msg2
int 21h
mov ah,01h
int 21h
mov second,al
sub second,30h
mov ax,00h
mov al,temp
mul second
div a
mov num1,al
mov num2,ah
add num1,30h
add num2,30h
mov ah,09h
lea dx,msg3
int 21h
mov ah,02h
mov dl,num1
int 21h
mov ah,02h
mov dl,num2
int 21h
mov al,0
inc bx
dec cx
mov ah,4ch
int 21h
main endp
end main

I hope it helps!


text:
Q: How to remove all hidden parameters from Oracle Database How do I remove all hidden parameters from Oracle Database before upgrading? I'm using the SQL query below. So what do you recommended?
SELECT name,description from SYS.V$PARAMETER WHERE name LIKE '\_%' ESCAPE '\'

Here are parameters:
_fast_full_scan_enabled
_gby_hash_aggregation_enabled
_like_with_bind_as_equality
_optimizer_push_pred_cost_based
_sort_elimination_cost_ratio
_sqlexec_progression_cost
_trace_files_public
_b_tree_bitmap_plans

Regards,

A: You'd need to add IS_SPECIFIED (or ISSPECIFIED) to the where clause, as some hidden parameters may be set by... other things.
A parameter can be removed from an spfile by issuing:
ALTER SYSTEM RESET "_some_hidden_parameter" scope = spfile;
You will likely have to stop and start the instance(s) to have the changes take effect.

A: Create a pfile from the spfile:
CREATE PFILE FROM SPFILE;

Edit the generated pfile and remove the parameters, then recreate the spfile from the edited pfile. Bounce the database & all should be well.
The database might need to be down when you recreate the spfile from the pfile.

A: Please note when RAC you need to define scope=both
IE:
Check if there are any hidden "_" parameters.
SELECT name,description
FROM SYS.V$PARAMETER
WHERE name LIKE '\_%' ESCAPE '\';

Remove the hidden parameter, In my case it is "_rac_dbtype_reset"
alter system reset "_rac_dbtype_reset" scope=both;

Check again
SELECT name,description
FROM SYS.V$PARAMETER
WHERE name LIKE '\_%' ESCAPE '\';

Then STOP and START the DB on ALL NODE in the RAC
shutdown immediate;

startup;


text:
Q: Design Practices - Several Pages with ASP.NET MVC Is there a specific design practice for MVC type sites that need to have a lot of non-model related pages? I mean, it seems very silly to make a controller action for every single page; Yet at the same time, that seems to be the only way to realistically do it and adhere to standards. Is there any documentation or examples available for things like this?
When I speak of non-model pages, I mean things that are just display; Static information that you might use a standard HTML website layout for. But it has to be intermingled with other parts of the site that do require models and validation/etc.

A: Create a folder for your static content, and put in an ignore route for those pages.  This causes those pages to be passed through directly to IIS for immediate display.
routes.IgnoreRoute("StaticPages/{*path}");

You can also load static HTML content into an existing View.  This preserves your ability to work with dynamic content in the same page.

A: I don't think it sounds silly at all to make an action for every page. That's just how MVC works.
You can ignore some routes, as Robert Harvey suggests, but then you'll have the *.html extension on your static pages but not your internal ones, and you'll be unable to use the Url. and Html. helper methods for linking to MVC actions.
I think you should just go with the flow.

A: Another alternative was suggested for common static files such as help pages which is based more on a naming convention, but would allow for some flexibility in layout control in the view:
ASP.Net MVC Routing Strategy for Static Content


text:
Q: Is there any way using which I can get Last Updated row Id Is there any way using which I can get the last row I have updated of the table.
For Ex:- my table has 1000 records in it.
I have updated the value of 500th record of table X.
So, I want the ID 500 in return.
Thanks in advance.
Regards,

A: I don't think this feature exists with MySQL. However you can get the same effect by adding a timestamp column:
ALTER TABLE yourtable
   ADD COLUMN last_update TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP

This would make the last_update column pretty much automatically maintained. Now you can select from yourtable the last updated row based on the timestamp.