text:
Q: Using named result params partially to set defaults Let's say I have a function with 3 return values. I set the values of 2 of them, and want to leave the 3rd one to default if I do not set it. Something like this -
func call(a int) (int, int, r3 string){

  //        return a, a+1, "no error" // stmt 1
  //        return a, a+1             // stmt 2
  //        return                    // stmt 3
}

Running with stmt 2 or stmt 3 uncommented, I get below error -
duplicate argument int
int is shadowed during return

How is int shadowed here? The return list does not have named int params.
Running with stmt 1 uncommented, I get below error -
duplicate argument int
cannot use a (type int) as type string in return argument
cannot use a + 1 (type int) as type string in return argument

Can someone explain origin of these errors ?
Is it not possible to have partial list of named result params (or even returning variables when using named result params) ?

A:
The Go Programming Language Specification
Function types
Within a list of parameters or results, the names (IdentifierList)
  must either all be present or all be absent. If present, each name
  stands for one item (parameter or result) of the specified type and
  all non-blank names in the signature must be unique. If absent, each
  type stands for one item of that type.

package main

// duplicate argument int
func call1(a int) (int, int, r3 string) {
    // int is shadowed during return
    return
}

// duplicate argument int
func call2(a int) (int string, int string, r3 string) {
    // int is shadowed during return
    return
}

// duplicate argument int
func call3(a bool) (int, int, r3 string) {
    // int is shadowed during return
    return
}

func call4(a int) (int, r2, r3 string) {
    return
}

func call5(a int) (r1, r2, r3 string) {
    return
}

func main() {}

Playground: https://play.golang.org/p/PUhY7Y0H9f
Output:
tmp/sandbox842451638/main.go:4:33: duplicate argument int
tmp/sandbox842451638/main.go:6:2: int is shadowed during return
tmp/sandbox842451638/main.go:10:47: duplicate argument int
tmp/sandbox842451638/main.go:12:2: int is shadowed during return
tmp/sandbox842451638/main.go:16:34: duplicate argument int
tmp/sandbox842451638/main.go:18:2: int is shadowed during return

call1 is shorthand for call2. As you can see, you have duplicate return argument names int: "all non-blank names in the signature must be unique." The first return argument name int is shadowed by the second return argument name int.

If you want anonymous return arguments, you can use the blank identifier.
package main

// duplicate argument int
func callA(a int) (int, int, r3 string) {
    // int is shadowed during return
    return
}

func callB(a int) (_ int, _ int, r3 string) {
    return
}

func main() {}

Playground: https://play.golang.org/p/CS1x9mmIh6


text:
Q: Express Req.body empty on one PC but works fine on another I've a Firebase Express JS project folder on 1 PC.
When I run firebase serve, everything works fine.
I am trying to change my work PC to another one.
I've setup my nodejs, firebase cli, and opened the same exact folder on this new PC (via OneDrive with all files made available locally)
However, when I run firebase serve and attempt to POST, I see that the req.body is empty.
Am I missing something here?

The debug log of the working PC shows
[debug] [2020-12-19T09:39:00.832Z] Accepted request POST /project_path/sessionLogin --> app_name

While the debug log of the non working PC shows
[debug] [2020-12-19T09:34:13.542Z] <<< [apiv2][status] POST http://localhost:5001/project_path/sessionLogin 500
[debug] [2020-12-19T09:34:13.542Z] <<< [apiv2][body] POST http://localhost:5001/project_path/sessionLogin [stream]
[info] i  hosting: 127.0.0.1 - - [19/Dec/2020:09:34:13 +0000] "POST /sessionLogin HTTP/1.1" 500 2257 "http://localhost:5000/" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36" {"metadata":{"emulator":{"name":"hosting"},"message":"127.0.0.1 - - [19/Dec/2020:09:34:13 +0000] \"POST /sessionLogin HTTP/1.1\" 500 2257 \"http://localhost:5000/\" \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36\""}}
[info] >  TypeError: Cannot read property 'toString' of undefined {"user":"TypeError: Cannot read property 'toString' of undefined","metadata":{"emulator":{"name":"functions"},"function":{"name":"app_name"},"message":"\u001b[90m> \u001b[39m TypeError: Cannot read property 'toString' of undefined"}}
[info] >      at C:\Users\name\firebase_files\functions\index.js:4059:38 {"user":"    at C:\\Users\\name\\firebase_files\\functions\\index.js:4059:38","metadata":{"emulator":{"name":"functions"},"function":{"name":"app_name"},"message":"\u001b[90m> \u001b[39m     at C:\\Users\\name\\firebase_files\\functions\\index.js:4059:38"}}
[info] >      at Layer.handle [as handle_request] (C:\Users\name\firebase_files\functions\node_modules\express\lib\router\layer.js:95:5) {"user":"    at Layer.handle [as handle_request] (C:\\Users\\name\\firebase_files\\functions\\node_modules\\express\\lib\\router\\layer.js:95:5)","metadata":{"emulator":{"name":"functions"},"function":{"name":"app_name"},"message":"\u001b[90m> \u001b[39m     at Layer.handle [as handle_request] (C:\\Users\\name\\firebase_files\\functions\\node_modules\\express\\lib\\router\\layer.js:95:5)"}}
[info] >      at next (C:\Users\name\firebase_files\functions\node_modules\express\lib\router\route.js:137:13) {"user":"    at next (C:\\Users\\name\\firebase_files\\functions\\node_modules\\express\\lib\\router\\route.js:137:13)","metadata":{"emulator":{"name":"functions"},"function":{"name":"app_name"},"message":"\u001b[90m> \u001b[39m     at next (C:\\Users\\name\\firebase_files\\functions\\node_modules\\express\\lib\\router\\route.js:137:13)"}}
[info] >      at Route.dispatch (C:\Users\name\firebase_files\functions\node_modules\express\lib\router\route.js:112:3) {"user":"    at Route.dispatch (C:\\Users\\name\\firebase_files\\functions\\node_modules\\express\\lib\\router\\route.js:112:3)","metadata":{"emulator":{"name":"functions"},"function":{"name":"app_name"},"message":"\u001b[90m> \u001b[39m     at Route.dispatch (C:\\Users\\name\\firebase_files\\functions\\node_modules\\express\\lib\\router\\route.js:112:3)"}}
[info] >      at Layer.handle [as handle_request] (C:\Users\name\firebase_files\functions\node_modules\express\lib\router\layer.js:95:5) {"user":"    at Layer.handle [as handle_request] (C:\\Users\\name\\firebase_files\\functions\\node_modules\\express\\lib\\router\\layer.js:95:5)","metadata":{"emulator":{"name":"functions"},"function":{"name":"app_name"},"message":"\u001b[90m> \u001b[39m     at Layer.handle [as handle_request] (C:\\Users\\name\\firebase_files\\functions\\node_modules\\express\\lib\\router\\layer.js:95:5)"}}
[info] >      at C:\Users\name\firebase_files\functions\node_modules\express\lib\router\index.js:281:22 {"user":"    at C:\\Users\\name\\firebase_files\\functions\\node_modules\\express\\lib\\router\\index.js:281:22","metadata":{"emulator":{"name":"functions"},"function":{"name":"app_name"},"message":"\u001b[90m> \u001b[39m     at C:\\Users\\name\\firebase_files\\functions\\node_modules\\express\\lib\\router\\index.js:281:22"}}
[info] >      at Function.process_params (C:\Users\name\firebase_files\functions\node_modules\express\lib\router\index.js:335:12) {"user":"    at Function.process_params (C:\\Users\\name\\firebase_files\\functions\\node_modules\\express\\lib\\router\\index.js:335:12)","metadata":{"emulator":{"name":"functions"},"function":{"name":"app_name"},"message":"\u001b[90m> \u001b[39m     at Function.process_params (C:\\Users\\name\\firebase_files\\functions\\node_modules\\express\\lib\\router\\index.js:335:12)"}}
[info] >      at next (C:\Users\name\firebase_files\functions\node_modules\express\lib\router\index.js:275:10) {"user":"    at next (C:\\Users\\name\\firebase_files\\functions\\node_modules\\express\\lib\\router\\index.js:275:10)","metadata":{"emulator":{"name":"functions"},"function":{"name":"app_name"},"message":"\u001b[90m> \u001b[39m     at next (C:\\Users\\name\\firebase_files\\functions\\node_modules\\express\\lib\\router\\index.js:275:10)"}}
[info] >      at urlencodedParser (C:\Users\name\firebase_files\functions\node_modules\body-parser\lib\types\urlencoded.js:100:7) {"user":"    at urlencodedParser (C:\\Users\\name\\firebase_files\\functions\\node_modules\\body-parser\\lib\\types\\urlencoded.js:100:7)","metadata":{"emulator":{"name":"functions"},"function":{"name":"app_name"},"message":"\u001b[90m> \u001b[39m     at urlencodedParser (C:\\Users\\name\\firebase_files\\functions\\node_modules\\body-parser\\lib\\types\\urlencoded.js:100:7)"}}
[info] >      at Layer.handle [as handle_request] (C:\Users\name\firebase_files\functions\node_modules\express\lib\router\layer.js:95:5) {"user":"    at Layer.handle [as handle_request] (C:\\Users\\name\\firebase_files\\functions\\node_modules\\express\\lib\\router\\layer.js:95:5)","metadata":{"emulator":{"name":"functions"},"function":{"name":"app_name"},"message":"\u001b[90m> \u001b[39m     at Layer.handle [as handle_request] (C:\\Users\\name\\firebase_files\\functions\\node_modules\\express\\lib\\router\\layer.js:95:5)"}}
[info] >      at trim_prefix (C:\Users\name\firebase_files\functions\node_modules\express\lib\router\index.js:317:13) {"user":"    at trim_prefix (C:\\Users\\name\\firebase_files\\functions\\node_modules\\express\\lib\\router\\index.js:317:13)","metadata":{"emulator":{"name":"functions"},"function":{"name":"app_name"},"message":"\u001b[90m> \u001b[39m     at trim_prefix (C:\\Users\\name\\firebase_files\\functions\\node_modules\\express\\lib\\router\\index.js:317:13)"}}
[info] >      at C:\Users\name\firebase_files\functions\node_modules\express\lib\router\index.js:284:7 {"user":"    at C:\\Users\\name\\firebase_files\\functions\\node_modules\\express\\lib\\router\\index.js:284:7","metadata":{"emulator":{"name":"functions"},"function":{"name":"app_name"},"message":"\u001b[90m> \u001b[39m     at C:\\Users\\name\\firebase_files\\functions\\node_modules\\express\\lib\\router\\index.js:284:7"}}
[info] >      at Function.process_params (C:\Users\name\firebase_files\functions\node_modules\express\lib\router\index.js:335:12) {"user":"    at Function.process_params (C:\\Users\\name\\firebase_files\\functions\\node_modules\\express\\lib\\router\\index.js:335:12)","metadata":{"emulator":{"name":"functions"},"function":{"name":"app_name"},"message":"\u001b[90m> \u001b[39m     at Function.process_params (C:\\Users\\name\\firebase_files\\functions\\node_modules\\express\\lib\\router\\index.js:335:12)"}}
[info] >      at next (C:\Users\name\firebase_files\functions\node_modules\express\lib\router\index.js:275:10) {"user":"    at next (C:\\Users\\name\\firebase_files\\functions\\node_modules\\express\\lib\\router\\index.js:275:10)","metadata":{"emulator":{"name":"functions"},"function":{"name":"app_name"},"message":"\u001b[90m> \u001b[39m     at next (C:\\Users\\name\\firebase_files\\functions\\node_modules\\express\\lib\\router\\index.js:275:10)"}}
[info] >      at jsonParser (C:\Users\name\firebase_files\functions\node_modules\body-parser\lib\types\json.js:119:7) {"user":"    at jsonParser (C:\\Users\\name\\firebase_files\\functions\\node_modules\\body-parser\\lib\\types\\json.js:119:7)","metadata":{"emulator":{"name":"functions"},"function":{"name":"app_name"},"message":"\u001b[90m> \u001b[39m     at jsonParser (C:\\Users\\name\\firebase_files\\functions\\node_modules\\body-parser\\lib\\types\\json.js:119:7)"}}
[info] >      at Layer.handle [as handle_request] (C:\Users\name\firebase_files\functions\node_modules\express\lib\router\layer.js:95:5) {"user":"    at Layer.handle [as handle_request] (C:\\Users\\name\\firebase_files\\functions\\node_modules\\express\\lib\\router\\layer.js:95:5)","metadata":{"emulator":{"name":"functions"},"function":{"name":"app_name"},"message":"\u001b[90m> \u001b[39m     at Layer.handle [as handle_request] (C:\\Users\\name\\firebase_files\\functions\\node_modules\\express\\lib\\router\\layer.js:95:5)"}}
[info] i  functions: Finished "app_name" in ~1s {"metadata":{"emulator":{"name":"functions"},"function":{"name":"app_name"},"message":"Finished \"app_name\" in ~1s"}}

A: You should run npm install to be sure all packages are installed correctly. Is there no error message in your console?

redpajama_set_name: RedPajamaStackExchange


text:
Q: why pdfcrop --xetex deletes all content of pdf file? TL 2015 I was reading this on the net, (abut 80% down the page), someone suggested to use pdfcrop with --xetex so that the generated pdf is smaller than the default.
When I tried this option, on Linux with TL 2015, I found the cropped pdf file was all blank! Everything in it was deleted.
This is what I typed:
>which pdfcrop
/usr/local/texlive/2015/bin/x86_64-linux/pdfcrop

>pdfinfo 4.pdf
Creator:        TeX
Producer:       pdfTeX-1.40.16
CreationDate:   Thu Dec 17 23:31:34 2015
ModDate:        Thu Dec 17 23:31:34 2015
Tagged:         no
Form:           none
Pages:          1
Encrypted:      no
Page size:      618 x 793 pts
Page rot:       0
File size:      104183 bytes
Optimized:      no
PDF version:    1.6

>pdfcrop --xetex --margins 5 --clip 4.pdf  4.pdf
PDFCROP 1.38, 2012/11/02 - Copyright (c) 2002-2012 by Heiko Oberdiek.
==> 1 page written on `4.pdf'.

>pdfinfo 4.pdf
Creator:         XeTeX output 2015.12.24:1640
Producer:       xdvipdfmx (20150315)
CreationDate:   Thu Dec 24 16:40:59 2015
Tagged:         no
Form:           none
Pages:          1
Encrypted:      no
Page size:      597 x 772 pts
Page rot:       0
File size:      701 bytes
Optimized:      no
PDF version:    1.6

The new 4.pdf file is blank, here is before and after:

Here is link to 4_before.pdf before the crop. Here is link to 4_after.pdf after the crop. if someone likes to reproduce this.
Did I do something wrong? Why new pdf file is blank?
if I do not use --xetex then then the new pdf is not blank. (it is not cropped for some reason, and I am still trying to find out why, but at least it is not blank!).

A: xdvipdfmx in TeX Live 2015 does not include PDF with
newer version than 1.5 by default. The version of
4.pdf is 1.6, thus pdfcropped one becomes blank.
In upcoming TeX Live 2016, this feature is improved.
Even in TeX Live 2015, the commandline
xetex --output-driver="xdvipdfmx -E -V 6"

can be used in order to include PDF images with version 1.6.
Please study if pdfcrop allows to pass options
for xetex.


text:
Q: String Insertion Sort program I am just starting to lean C so I don't know it very well. The program we are given tells us to write an Insertion Sort program that takes 20 strings seperated by space and sorts then alphabetically and prints them out in order. This is confusing me greatly since C doesn't have a String data type (at least to my knowledge). Aren't Strings just character arrays? Here is what I got:
#include <stdio.h>
#include <string.h>
#define MAX_STRINGS 20

void InsertionSort(char list[]);

void main()
{
    int index;
    char strings[MAX_STRINGS];

    /* Get input */
    printf("Enter %s strings.\n", MAX_STRINGS);
    for (index = 0; index < MAX_STRINGS; index++)
    {
        char tempString[100];
        printf("Input string %d : ", index);
        scanf("%s", &tempString[0]);
        strings[index] = tempString;
    }

    InsertionSort(strings);

    printf("\nThe input set, in alphabetical order:\n");
    for (index = 0; index < MAX_STRINGS; index++)
    {
        printf("%s\n", strings[index]);
    }
}

void InsertionSort(char list[])
{
    int unsorted;
    int sorted;
    char unsortedItem;

    for(unsorted = 1; unsorted < MAX_STRINGS; unsorted++)
    {
        unsortedItem = list[unsorted];

        for (sorted = unsorted - 1; (sorted >= 0) && (list[sorted] >  unsortedItem); sorted--)
        {
            list[sorted + 1] = list[sorted];
        }
        list[sorted + 1] = unsortedItem;
    }
}

I am completely new to C and C syntax and I find it very confusing. This program is not working correctly. What it is doing is it allows me to enter 20 strings, but then nothing is sorted and it prints out nothing. Any idea on how to fix that? Also, is there any idea to how I can get it to where I type a single sentence and the each string is separated by white space? For example if I type, "I am learning how to program in C and right now I do not like it." that would give me 16 strings. "I", "am", "learning", etc. Thanks.

A: A few problems with the original code:
1) You cannot copy strings using =; use strncpy for that (using = only assigns pointers).
2) A string is an array of chars; therefore an array of strings is an array of arrays of chars (so your InsertionSort signature is wrong). Note that C strings are null terminated, which simply means that a byte with the value of 0 signifies the end of a string (this is very important, if you forget everything else, remember this).
3) %s expects a char*; this line produces UB: printf("Enter %s strings.\n", MAX_STRINGS);. What you want is %d instead (read up on printf format specifiers).
4) You can't compare strings using normal arithmetic operators; those compare pointers. You need to use strcmp.
5) Your implementation of the insertion sort algorithm was wrong.
6) There are a few versions of main declarations allowed by the standard, and char main isn't one of them. In this case just use int main.
Here is a fixed version of your code:
#include <stdio.h>
#include <string.h>
#define MAX_STRINGS 20
#define MAX_STRING_LEN 200

void InsertionSort(char list[MAX_STRINGS][MAX_STRING_LEN]);

int main()
{
    int index;
    char strings[MAX_STRINGS][MAX_STRING_LEN];

    /* Get input */
    printf("Enter %d strings.\n", MAX_STRINGS);
    for (index = 0; index < MAX_STRINGS; index++)
    {
        printf("Input string %d : ", index);
        scanf("%199s", strings[index]);     // limit the width so we don't go past the buffer
        strings[index][sizeof(strings[index]) - 1] = '\0';
    }

    InsertionSort(strings);

    printf("\nThe input set, in alphabetical order:\n");
    for (index = 0; index < MAX_STRINGS; index++)
    {
        printf("%s\n", strings[index]);
    }
}

void InsertionSort(char list[MAX_STRINGS][MAX_STRING_LEN])
{
    for (int i = 1; i < MAX_STRINGS; i++)
    {
        int j = i;

        while (j > 0 && strcmp(list[j - 1], list[j]) > 0)
        {
            char tmp[MAX_STRING_LEN];
            strncpy(tmp, list[j - 1], sizeof(tmp) - 1);
            tmp[sizeof(tmp) - 1] = '\0';

            strncpy(list[j - 1], list[j], sizeof(list[j - 1]) - 1);
            list[j - 1][sizeof(list[j - 1]) - 1] = '\0';

            strncpy(list[j], tmp, sizeof(list[j]));
            list[j][sizeof(list[j]) - 1] = '\0';

            --j;
        }
    }
}

This might be a bit overwhelming at first, but read it slowly and carefully and you should have no problems.
The = '\0's after strncpy or scanf - these function don't implicitly null-terminate strings, so we have to do that manually - you might get away without doing it a few times, but in the long run it'll get back to you eventually. Stay safe and make it a habit.
Everyone else: if you spot any errors, let me know - it's late and I'm tired.
Regarding your questions in the comments:
1) Why am I starting at 1 in the for loop?
Because I'm later referring to list[j - 1], and with j set to the value of i (initially), it can't be less than 1 or we'd be using negative indices. See here for a description of the algorithm.
2) How to read an entire line of string, including spaces?
The best solution would be to use fgets. Note that it has one quirk: it stores the \n character in the array as well. If you don't want it you'll have to remove it manually.
3) What is tmp for?
This is just a temporary char buffer so I can swap the two strings, as the algorithm requires. This isn't specific to strings, in general to swap two variables you need a third, temporary one (unless you opt for some dirty XOR hacks).

A: Use this function to sort strings alphabetically:
int s_bubblesortA(int argc,char **argv)
{
    int i , j = 0;
    char *p_1 , *p_2 , *tmp;
    while( j < argc )
    {
        for( i = 0 ; i < argc - j - 1 ; i++ )
        {
            p_1 = argv[i] , p_2 = argv[i+1];
            while( *p_1 && *p_2 )
            {
                if( *p_1 < *p_2 )
                    break;
                else if( *p_1 > *p_2 || ( ! *(p_2 + 1) && ( *p_1 == *p_2 ) && *(p_1+1) ) )
                {
                    tmp = argv[i];
                    argv[i] = argv[i+1];
                    argv[i+1] = tmp;
                    break;
                }
                p_1++;
                p_2++;
            }
        }
        j++;
    }
    return 0;
}

note: check this link to so my full answer to a similar post.sort words alphabeticaly in C


text:
Q: ggplot render plot with incorrect order based on value I want to plot this following data frame, for variable term, based on value val, and facet by gr
I used Windows 10 64 bit, R 3.4.3 64 bit.
I have tried fct_reorder from package forcats, without success.
library(tidyverse)

df = data_frame(gr = c(rep('foo',3), rep('bar',3),
     rep('cron',3)), term = c('a','b','c', 'd', 'a','e', 'f', 'g', 'h'),
     val = c(4,5,6,1.5,1,3,1,2,4))

df %>%
group_by(gr) %>%
arrange(desc(val)) %>%
ungroup() %>%
mutate(term = reorder(term, val)) %>%
ggplot(aes(term, val, fill = gr)) +
geom_col(position = 'identity') +
facet_wrap(~gr, scales = 'free') +
ylab('')+
coord_flip()

Expectation is term a would be in bottom of both group foo and bar.
However, in the plot, group bar has incorrect order, as a plotted in middle.

A: @Camille 's comment was key. But you are right - it needs a different approach for another data frame - below an approach, updated as per your comment.
I used rank instead of arrange and am introducing helper columns. This is somewhat 'dangerous', because the positions of the new columns do not correspond to the old columns any more. I therefore stored this in a new data frame, in order to not change the underlying data, and also not to get confused.
I then created the factored column term_f, based on @ Camille 's suggestions (and after ungrouping, as you have done)
Some caveats:
Just use reorder(term, val, FUN = min), i.e. not desc(val)
library(tidyverse)
df = data_frame(gr = c(rep('foo',3), rep('bar',3), rep('cron',3)), term = c('a','b','c', 'd', 'a','e', 'f', 'g', 'h'), val = c(4,3,6,1.5,1,3,1,2,4))

df_f <-
  df %>% group_by(gr) %>%
  mutate(rank_val = val[rank(val)],
         rank_term = term[rank(val)]) %>%
  ungroup() %>%
  mutate(term_f = fct_inorder(rank_term))

df_f
#> # A tibble: 9 x 6
#>   gr    term    val rank_val rank_term term_f
#>   <chr> <chr> <dbl>    <dbl> <chr>     <fct>
#> 1 foo   a       4        3   b         b
#> 2 foo   b       3        4   a         a
#> 3 foo   c       6        6   c         c
#> 4 bar   d       1.5      1   a         a
#> 5 bar   a       1        1.5 d         d
#> 6 bar   e       3        3   e         e
#> 7 cron  f       1        1   f         f
#> 8 cron  g       2        2   g         g
#> 9 cron  h       4        4   h         h

  ggplot(data = df_f, aes(term_f, rank_val)) +
  geom_col() +
  facet_wrap(~ gr, scales = 'free') +
  coord_flip()

Created on 2018-12-23 by the reprex
package (v0.2.0).


text:
Q: SSRS: Trying to hide a Textbox and keep getting a data aggregation error I am basically trying to hide this placeholder/text box based off the condition of the preapproval field i am using in this report. If the field has the value of "Yes" leave the textbox there and if it is "No" hide the textbox from the user.
I have tried using
=iif( Fields!Preapproval.Value = "Yes", false,true)

and the ssrs report will error saying

The Hidden expression for the text box 'Textbox86' refers directly to the field 'Preapproval' without specifying a dataset aggregate.  When the report contains multiple datasets, field references outside of a data region must be contained within aggregate functions which specify a dataset scope.

I have seen some posts saying to use code similar to this
=First(Fields!Preapproval.Value, "TestDateSet")
to get around the error I am currently receiving.
Anyone have any ideas on what I need to do to get the visibility working correctly for this textbox?

A: It sound like you are trying to hide the textbox but the textbox is not inside a table/matrix that is bound to the dataset.
If the textbox was, for example, in a row in a table that was bound to your dataset then what you have tried would work.
If the textbox is in a table/matrix but not in the details row group, you can specify the row group name as the scope, something like
=IIF(FIRST(Fields!Preapproval.Value, "myRowGroupName") = "Yes", False, True)

Assuming the textbox is just sat on it's own on the report somewhere then depending on what your dataset contains you would have to decide what approach to use.
If you dataset only contains 1 record then you can use
=IIF(FIRST(Fields!Preapproval.Value, "myDataSetName") = "Yes", False, True)

If you dataset contains more than one records then you can still use the above or you could use a different aggregate function such as MIN() or MAX() instead of FIRST().
NOTE: The scope name (in this case your dataset name) is case sensitive and must be enclosed in double quotes.
BTW: You could simplify the hidden expression to something like
=FIRST(Fields!Preapproval.Value, "myDataSetName") <> "Yes"

as this will return true or false anyway, so no need for an IIF


text:
Q: How to access the Public property of aspx page in the custom Control I have created a Custom control and embedded in the aspx page.
Now i want to access a public property in the aspx webpage in the Custom Control (eg: Test.ascx.cs)
How i can do that?
TIA

A: It would not make much sense to add dependency from the custom control to the outside.
Create an interface that contains the property you specified :
public interface IMyPageInterface
{
   string MyProperty {get;set;}
}

implement interface on your page :
//your page code behind
public partial class WebForm1: System.Web.UI.Page,IMyPageInterface
{
    public string MyProperty
    {
       get;
       set;
    }
}

you can get your page as IMyPageInterface in your custom control
IMyPageInterface myPage = this.Page as IMyPageInterface;
myPage.MyProp...

A property of type IMyPageInterface can also be defined
public class MyControl :Control
{
    public IMyPageInterface MyPage
    {
        get
        {
            return this.Page as IMyPageInterface;
        }
    }
}


text:
Q: Display single item from List Is it possible to display a specific item from a list in ASP.NET MVC 4?  I am currently looping through the list and displaying multiple items.  But I need to break out of the loop and just display the REGISTER.UID from the list.
Here is the simplified code
@model List<INCA_RVS.Models.REGISTER>

if (Model != null)
    {

User ID

<input type="text" name="userid" value="/* ListValueHere */" />

    }

A: Found the answer I need.
    if (Model != null)
        {
        var uid = Model.First(item => item.UID != "").UID.ToUpper();

User ID

<input type="text" name="userid" value="@uid" />

        }


text:
Q: Unable to serve static assets on rails 5.0. "super: no method `silence` for #" I'm pretty lost, so I'm not completely sure what would be useful information for this issue, but I'm trying to serve some static assets for an angular app in rails, including as my own and third party JS, HTML, and CSS. I've created a directory called third_party under assets where all my bower installed components go, and a directory called my_app for my own client code.
I require the necessary code in a main_app.js file in app/assets/javascript:
//= require jquery
//= require jquery_ujs
//= require angular/angular

<snipped>

//= require_tree ../my_app/common
//= require main/index/index
//= require_tree ../my_app/main

I added those directories to the asset paths in my application.rb file with these lines:

config.assets.paths << Rails.root.join('app', 'assets', 'third_party')
config.assets.paths << Rails.root.join('app', 'assets', 'main_app')
And added them to the precompile step in assets.rb:
Rails.application.config.assets.precompile += %w( main_app.js )
Finally I have an assets being served via a custom assets_controller that looks like this:
class AssetsController < ApplicationController
  skip_before_filter :verify_authenticity_token

  def serve_main_asset
    serve_asset_for_app("main")
  end

  protected

  def serve_asset_for_app(app_name)
    path = params[:path]
    respond_to do |format|
      format.html { render :file => "app/assets/my_app/#{app_name}/#{path}.html", layout:
          false }
      format.js { render :file => "#{path}.js" }
      format.css { render(:file => "#{path}.css") }
      format.json { render(:file => "app/assets/my_app/#{app_name}/#{path}.json") }
    end
  end
end

But whenever I try to GET any of these files, I'm seeing this error/stacktrace:
    2016-08-04 01:23:16 -0500: Rack app error handling request { GET /assets/main/index/index.html }
    #<NoMethodError: super: no superclass method `silence' for #<Logger:0x00000004bd78c0>>
    /home/pawan/.rvm/gems/ruby-2.2.3/gems/activesupport-5.0.0/lib/active_support/logger.rb:63:in `block (3 levels) in broadcast'
...

On a possibly related note, I notice that the app is also trying to serve assets with a unique filename, even though I thought I have all cache-busting logic turned off for development mode. (ex: bootstrap.self-c8d853976ca268a5391a9470ebdcf3ba43e0b78936cdc925146afcb60a3116be.js)
I feel like the issue may just be an outdated gem of some sort? TIA.

A: I had the same issue.
The problem was I used a plain Ruby Logger (config/environmens/development.rb):
config.logger = Logger.new('/dev/null')

To make it work, I've changed it to use an ActiveSupport Logger:
config.logger = ActiveSupport::Logger.new('/dev/null')

This worked for me.

A: This is because of some recent changes in sprockets-rails gem, which is now offer a configuration option to silence asset request logging in development.
You can disable asset logging in your development.rb by setting below configuration.
config.assets.quiet = false
or use ActiveSupport::Logger instead.
config.logger = ActiveSupport::TaggedLogging.new(ActiveSupport::Logger.new(STDOUT))


text:
Q: has anyone else had cypress.io test start failing as of Feb 18, 2019? With no changes to the tests or tested environment, cypress.io tests that ran successfully up until Feb 18, 2019 are now failing with error.
Cypress.io is version 3.1.5
The tests are run by jenkinsfile as:
sh "npx cypress run --browser chrome  --reporter mocha-multi-reporters   --reporter-options configFile=config-v1-smoke.json  --spec \"cypress/integration/smoke/*.js\""

The error is:
TypeError: Cannot read property 'passes' of undefined
    at Spec.Base.epilogue (/var/jenkins_home/workspace/svn_ci/node_modules/mocha/lib/reporters/base.js:318:25)
    at Object.onceWrapper (events.js:316:30)
    at emitOne (events.js:120:20)
    at Runner.emit (events.js:210:7)
    at Reporter.emit (/var/jenkins_home/.cache/Cypress/3.1.5/Cypress/resources/app/packages/server/lib/reporter.js:239:55)
    at Object.server.startWebsockets.onMocha (/var/jenkins_home/.cache/Cypress/3.1.5/Cypress/resources/app/packages/server/lib/project.js:296:22)
    at Socket.<anonymous> (/var/jenkins_home/.cache/Cypress/3.1.5/Cypress/resources/app/packages/server/lib/socket.js:237:36)
    at emitTwo (events.js:125:13)
    at Socket.emit (events.js:213:7)
    at /var/jenkins_home/.cache/Cypress/3.1.5/Cypress/resources/app/packages/socket/node_modules/socket.io/lib/socket.js:503:12
    at _combinedTickCallback (internal/process/next_tick.js:131:7)
    at process._tickCallback (internal/process/next_tick.js:180:9)

TypeError: Cannot read property 'passes' of undefined
    at Spec.Base.epilogue (/var/jenkins_home/workspace/svn_ci/node_modules/mocha/lib/reporters/base.js:318:25)
    at Object.onceWrapper (events.js:316:30)
    at emitOne (events.js:120:20)
    at Runner.emit (events.js:210:7)
    at Reporter.emit (/var/jenkins_home/.cache/Cypress/3.1.5/Cypress/resources/app/packages/server/lib/reporter.js:239:55)
    at Object.server.startWebsockets.onMocha (/var/jenkins_home/.cache/Cypress/3.1.5/Cypress/resources/app/packages/server/lib/project.js:296:22)
    at Socket.<anonymous> (/var/jenkins_home/.cache/Cypress/3.1.5/Cypress/resources/app/packages/server/lib/socket.js:237:36)
    at emitTwo (events.js:125:13)
    at Socket.emit (events.js:213:7)
    at /var/jenkins_home/.cache/Cypress/3.1.5/Cypress/resources/app/packages/socket/node_modules/socket.io/lib/socket.js:503:12
    at _combinedTickCallback (internal/process/next_tick.js:131:7)
    at process._tickCallback (internal/process/next_tick.js:18

0:9)

A: mocha@6.0.0 was released on 2019-02-18.
By downgrading mocha from to last release mocha@5.2.0, the problem is alleviated.  With mocha@5.2.0, the correct set of cypress.io tests are run as specified in --spec.
Something in mocha@6.0.0 is creating test spec glob problem for cypress.io with mocha reporting.

A: Washingons comment with regards to the glob problem is incorrect. Mocha 6 requires a stat collector to be instantiated.
I've now updated, tested and released updated modules that fix this with mocha 6, but also retains backwards compatibility with mocha 5 and earlier versions.
https://www.npmjs.com/package/cypress-multi-reporters
https://www.npmjs.com/package/mocha-junit-reporters
Example against Mocha 5
Example against Mocha 6
the changes required are minimal
npm i mocha-junit-reporters
npm i cypress-multi-reporters
in reporterOpts.json
{
  "reporterEnabled": "mocha-junit-reporters, mochawesome",
  "mochaJunitReportersReporterOptions": {
    "mochaFile": "cypress/reports/junit/test_results[hash].xml",
    "toConsole": false
  },
  "mochawesomeReporterOptions": {
    "reportDir": "cypress/reports/mocha",
    "quiet": true,
    "overwrite": false,
    "html": false,
    "json": true
  }
}

in cypress.json
{
  ...
  "reporter": "cypress-multi-reporters",
  "reporterOptions": {
    "configFile": "reporterOpts.json"
  }

See https://github.com/YOU54F/cypress-docker-typescript/pull/22/files
Hopefully the PR's will be merged in the source repo's soon but for now, enjoy


text:
Q: Need help: My program should react when an other class is doing something specific - Not as easy as it sounds I´m writing an program that uses twitter. I want that my app shows an UIAlertView when the user presses on the "Tweet"-Button and the username or password is wrong.
For my Twitterfunction I use the TwitterRequest.m/h from Brandon Trebitowski. If everthing works great and the username/password is right, this happens in my app:
        TwitterRequest * t = [[TwitterRequest alloc] init];
        (...);
        [t statuses_update:twittermessage.text delegate:self requestSelector:@selector(status_updateCallback:)];

        loadingActionSheet = [[UIActionSheet alloc] initWithTitle:@"Posting to Twitter..." delegate:nil
                                                cancelButtonTitle:nil destructiveButtonTitle:nil otherButtonTitles:nil];
        [loadingActionSheet showInView:self.view];
    }

    - (void) status_updateCallback: (NSData *) content {
        [loadingActionSheet dismissWithClickedButtonIndex:0 animated:YES];
        [loadingActionSheet release];
        NSLog(@"%@",[[NSString alloc] initWithData:content encoding:NSASCIIStringEncoding]);
    }

But how can I show an UIAlertView when the username/password was wrong?
Here is the TwitterRequest.m:
#import "TwitterRequest.h"

@implementation TwitterRequest

@synthesize username;
@synthesize password;
@synthesize receivedData;
@synthesize delegate;
@synthesize callback;
@synthesize errorCallback;

-(void)friends_timeline:(id)requestDelegate requestSelector:(SEL)requestSelector{
    isPost = NO;
    // Set the delegate and selector
    self.delegate = requestDelegate;
    self.callback = requestSelector;
    // The URL of the Twitter Request we intend to send
    NSURL *url = [NSURL URLWithString:@"http://twitter.com/statuses/friends_timeline.xml"];
    [self request:url];
}

-(void)statuses_update:(NSString *)status delegate:(id)requestDelegate requestSelector:(SEL)requestSelector; {
    isPost = YES;
    // Set the delegate and selector
    self.delegate = requestDelegate;
    self.callback = requestSelector;
    // The URL of the Twitter Request we intend to send
    NSURL *url = [NSURL URLWithString:@"http://twitter.com/statuses/update.xml"];
    requestBody = [NSString stringWithFormat:@"status=%@",status];
    [self request:url];
}

-(void)request:(NSURL *) url {
    theRequest   = [[NSMutableURLRequest alloc] initWithURL:url];

    if(isPost) {
        NSLog(@"ispost");
        [theRequest setHTTPMethod:@"POST"];
        [theRequest setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
        [theRequest setHTTPBody:[requestBody dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES]];
        [theRequest setValue:[NSString stringWithFormat:@"%d",[requestBody length] ] forHTTPHeaderField:@"Content-Length"];
    }

    theConnection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self];

    if (theConnection) {
        // Create the NSMutableData that will hold
        // the received data
        // receivedData is declared as a method instance elsewhere
        receivedData=[[NSMutableData data] retain];
    } else {
        // inform the user that the download could not be made
    }
}

- (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge {
    //NSLog(@"challenged %@",[challenge proposedCredential] );

    if ([challenge previousFailureCount] == 0) {
        NSURLCredential *newCredential;
        newCredential=[NSURLCredential credentialWithUser:[self username]
                                                 password:[self password]
                                              persistence:NSURLCredentialPersistenceNone];
        [[challenge sender] useCredential:newCredential
               forAuthenticationChallenge:challenge];

    } else {
        [[challenge sender] cancelAuthenticationChallenge:challenge];
        // inform the user that the user name and password
        // in the preferences are incorrect
        NSLog(@"Invalid Username or Password"); //THIS MUST be important. The console shows this message, if the username/password is wrong. Here is also the place, where I set the bool to TRUE
    }

}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    // this method is called when the server has determined that it
    // has enough information to create the NSURLResponse

    // it can be called multiple times, for example in the case of a
    // redirect, so each time we reset the data.
    // receivedData is declared as a method instance elsewhere
    //[receivedData setLength:0];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
    //NSLog([[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
    // append the new data to the receivedData
    // receivedData is declared as a method instance elsewhere
    [receivedData appendData:data];
}

- (void)connection:(NSURLConnection *)connection
  didFailWithError:(NSError *)error
{
    // release the connection, and the data object
    [connection release];
    // receivedData is declared as a method instance elsewhere
    [receivedData release];

    [theRequest release];

    // inform the user
    NSLog(@"Connection failed! Error - %@ %@",
          [error localizedDescription],
          [[error userInfo] objectForKey:NSErrorFailingURLStringKey]);

    if(errorCallback) {
        [delegate performSelector:errorCallback withObject:error];
    }
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    // do something with the data

    if(delegate && callback) {
        if([delegate respondsToSelector:self.callback]) {
            [delegate performSelector:self.callback withObject:receivedData];
        } else {
            NSLog(@"No response from delegate");
        }
    }

    // release the connection, and the data object
    [theConnection release];
    [receivedData release];
    [theRequest release];
}

-(void) dealloc {
    [super dealloc];
}

@end

I know that the important line in the TwitterRequest.m is in the else-cause of the -(void)connection-methode, because the Console writes always Invalid Username or Password, when they are wrong. So I tried to make there a bool as propertey, which will be set to TRUE, when the name/password is wrong(= when the else-cause will be used). In my ViewController I made this:
if (t.stimmtNicht == TRUE) {
    [loadingActionSheet dismissWithClickedButtonIndex:0 animated:YES];
    [loadingActionSheet release];
    UIAlertView *alert;
    alert = [[UIAlertView alloc] initWithTitle:@"Ouch!"
                                       message:@"Your Username or Password is wrong!"
                                      delegate:self
                             cancelButtonTitle:@"OK"
                             otherButtonTitles: nil];
    [alert show];
    [alert release];
}

But he always doesn't use the if-cause, even if the password is wrong. I think the code go faster through the if-quere than the TwitterRequest set it to TRUE. What can I do?
Thanks for your help and sorry for this stupid question, but I'm learning Objective-C and programming in general since just one week and I don´t know correctly how to interact from my ViewController with other classes.
Also sorry for my bad English!

A: Two ways I can think of:

*

*Apparently your TwitterRequest class has a "delegate" ivar; try calling the delegate to tell him (her?) that your credentials are wrong.

*Send an NSNotification through the NSNotificationCenter

In both cases, the class who gets notified should display the login view (with the username and password fields), and that's it.


text:
Q: Dead Time Insertion BLDC motor control I'm trying to build my own BLDC motor controller. I'm wondering if I really have to implement dead time between switching the high- and low-side FETs. My switching frequency is 30 kHz, my motor is 5 kW, 48 V and the max. RPM of the motor is ~3000 RPM.
Attached is the switching scheme for my motor in forward direction. It also shows the state of the Hall sensors.

For example, the state of phase U never suddenly changes from HIGH to LOW. As far as I understood dead time insertion, I don't need this for my switching scheme, am I right?

A:
I don't need this for my switching scheme, am I right?

Correct. You only need dead time if you are switching the high and low sides of a phase terminal alternately, eg. when doing synchronous PWM or 'active freewheeling'.


text:
Q: VBA Multi-Criteria Parent-Child SumProduct Please help.
I'm trying to create a user defined function that will use an array as multiple criteria (Pedigree) to check for corresponding parents (Parent) and then sum their respective ranges (Sumrange).
I've managed to create code that will check if a parent is in the pedigree range which will then return a result of 1 or 0. This will not return true values if blanks verify blanks. I intend to create an array with these 1's and 0's to then SumProduct it with my Sumrange. My problem is that I am unable create an array of these 1's and 0's and SumProduct them with the Sumrange without returning a #value.
This below code doesn't include the SumProduct portion but just returns 1 or 0 based on the criteria.
Function ProdIfs(Parent As Range, Pedigree As Range, Sumrange As Range) As Long
Application.Volatile

Dim i As Variant
Dim j As Variant
Dim result As Integer
    result = 0

For Each i In Parent
For Each j In Pedigree
    If i.Value = "" Or j.Value = "" Then
        result = result
        ElseIf i.Value = j.Value Then
        result = 1: GoTo NextIteration
    End If
Next j
NextIteration:
Next i

ProdIf = result

End Function

Thanks for you help.

A: Answer changed following comments
If you want to return an array, you actually have to create and populate an array in your function and make sure the return type is Variant.
Try this
Function ProdIfs(Parent As Range, Pedigree As Range, Sumrange As Range) As Variant
    Application.Volatile

    Dim i As Long
    Dim j As Long
    Dim result() As Integer ' The return value must be an array
    ReDim result(1 To Parent.Rows.Count, 1 To 1) ' Assuming Parent is 1 column

    For i = 1 To Parent.Rows.Count
        result(i, 1) = 0 ' set to 0 by default but always good to do it explicitly
        For j = 1 To Pedigree.Rows.Count
            If Parent.Cells(i, 1).Value <> "" And Parent.Cells(i, 1) = Pedigree.Cells(j, 1) Then
                result(i, 1) = 1
                Exit For
            End If
        Next j
    Next i

    ProdIfs = result

End Function

Edit: following your answer

*

*You just need to keep a running sum.

*To make your code run faster you should read values of these ranges and process them in memory. (It is much faster than asking excel for values in cells).

*The return value should be a Double

*This feels like a SumIfs ranther than a ProdIfs
Function ProdIfs(Parent As Range, Pedigree As Range, Sumrange As Range) As Double
    Application.Volatile

    Dim i As Long
    Dim v As Variant
    Dim vParent As Variant:     vParent = Parent.Value
    Dim vPedigree As Variant:   vPedigree = Pedigree.Value
    Dim vSumRange As Variant:   vSumRange = Sumrange.Value

    ProdIfs = 0
    For i = 1 To UBound(vParent, 1)
        For Each v In vPedigree
            If len(v) > 0 And v = vParent(i, 1) Then
                ProdIfs = ProdIfs + vSumRange(i, 1)
                Exit For
            End If
        Next v
    Next i

End Function

A: Thanks to Super Symmetry for getting this 99% of the way there.
Since the original code returned a 1 or 0, I changed the code to provide a sumproduct.
Also I've made the PedigreeRange loop through columns instead of rows to fit the way my Pedigree data is.
Function ProdIfs(Parent As Range, Pedigree As Range, Sumrange As Range) As Variant
    Application.Volatile

    Dim i As Long
    Dim j As Long
    Dim result() As Variant
    ReDim result(1, 1 To Parent.Rows.Count)
    Dim x As Long

    For i = 1 To Parent.Rows.Count
        x = 0
        result(1, i) = x
        For j = 1 To Pedigree.Columns.Count
            If Parent.Cells(i, 1).Value <> "" And Pedigree.Cells(1, j) <> "" And Parent.Cells(i, 1) = Pedigree.Cells(1, j) Then
                x = 1
                Exit For
            End If
        Next j
        result(1, i) = x * Sumrange(i, 1).Value
    Next i

    ProdIfs = WorksheetFunction.Sum(result)

End Function

Thanks again. If there are any improvements that can be made to this please let me know.


text:
Q: how to allow http:// as value of a GET variable after controller segment? Can someone please tell me why the following gives an error 404
 http://example.com/welcome/?=http://

but any thing else work normally, eg:
 http://example.com/welcome/?=hppt://
 http://example.com/welcome/?=htpp://
 http://example.com/welcome/?=pthh://

And this also works :
 http://example.com/welcome/?=http:/ ( with single slash)

Please help, I'm running into serious trouble and I'm going to reinvent more than 1 month of work just because of this mistake...

A: Try encoding your query string like this
http://example.com/welcome/?=http:%2F%2F


text:
Q: Sum occurrences of string for each row of a matrix using awk I have a very long data frame (~11 million x 130) for which is sparsely filled with percentages (0.00 - 100.00, float).
The entries that are missing are labeled "NA", like so:
cat1    NA    NA    99.90    NA    NA    10.90    NA
cat2    NA    1.00    NA    19.12    NA    NA    NA
cat3    NA    NA    NA    NA    NA    NA    45.00

I want to go through this data frame row by row and sum up the occurrences of "NA".
I can normally accomplish this very easily in R by doing apply(data.frame, 1, function(x) sum(is.na(x)), but because the file is so large I keep having memory problems. I'd like to do this with AWK if possible so that I can apply this on the command line for future similar problems.
I am not great with awk, but I essentially want to sum the occurrences of "NA" across fields for each record/row and then later I can use this as an index for skipping lines of the file.
Thanks in advance

A: Straightforwardly:
$ awk '{ for (i=2;i<=NF;i++) if ($i=="NA") c++; print c; c=0 }' file
5
5
6

A: You could just use a string replacement function that matches the pattern NA and count the number of occurrences it is doing per line and sum it up for the whole file as below.
awk '{ sum += gsub(/NA/, "", $0) } END { print sum }' file

or make it more robust to avoid false matches to the pattern NA. The below regex is based on your input sample where NA does not appear at the start of the file.
awk '{ sum += gsub(/[[:space:]]*NA[[:space:]]*|[[:space:]]*NA$/, "", $0) } END { print sum }' file

A: *

*table without header:awk '{ sum += gsub(/[[:space:]]*NA[[:space:]]*|[[:space:]]*NA$/, "", $0) ; print sum }' file

*table with header:awk 'NR > 1{ sum += gsub(/[[:space:]]*NA[[:space:]]*|[[:space:]]*NA$/, "", $0) ; print sum }' file


text:
Q: Insert N Blank Rows to R Data Frame Using Value in a Column I have a data frame:
Var_1 = c("A","B","C","D","E","F","G","H")
Var_2 = c(0,1,0,2,1,0,0,1)
DF = data.frame(Var_1,Var_2)
print(DF)

 Var_1 Var_2
1     A     0
2     B     1
3     C     0
4     D     2
5     E     1
6     F     0
7     G     0
8     H     1

I need to insert N blank rows filled with NA into the data frame, using the value found in Var_2 to determine N.  These new rows should be inserted immediately after the Var_2 value is >=1.  So I'd like my data frame to look like this:
print(DF)

 Var_1 Var_2
1      A     0
2      B     1
3   <NA>    NA
4      C     0
5      D     2
6   <NA>    NA
7   <NA>    NA
8      E     0
9      F     0
10     G     0
11     H     1
12  <NA>    NA

I'm pretty stuck with this, any help would be greatly appreciated.  Thank you.

A: Sequences and subsetting to the rescue.
Duplicating each row by Var_2 + 1 generates Var_2 extra rows when the value is > 0 and maintains the row when the value == 0
Then you can use the duplicated TRUE/FALSE on the sequence to replace only the additional rows with NA.
s <- rep(sequence(nrow(DF)), DF$Var_2 + 1)
DFnew <- DF[s,]
DFnew[duplicated(s),] <- NA
DFnew
#    Var_1 Var_2
#1       A     0
#2       B     1
#2.1  <NA>    NA
#3       C     0
#4       D     2
#4.1  <NA>    NA
#4.2  <NA>    NA
#5       E     1
#5.1  <NA>    NA
#6       F     0
#7       G     0
#8       H     1
#8.1  <NA>    NA

This should also be pretty quick on all but the most massive datasets.
# 800K records
DF <- DF[rep(1:8,1e5),]
system.time({
  s <- rep(sequence(nrow(DF)), DF$Var_2 + 1)
  DFnew <- DF[s,]
  DFnew[duplicated(s),] <- NA
})
#   user  system elapsed
#  0.600   0.000   0.601

A: Interesting problem:
ind <- which(DF$Var_2 > 0)
ind
# [1] 2 4 5 8
starts <- 1L + unique(c(0L, head(ind, n = -1)))
stops <- unique(c(ind, nrow(DF))) # in case the last !0 is not on bottom row
starts
# [1] 1 3 5 6
stops
# [1] 2 4 5 8
DFaug_list <- Map(
  function(a, b) rbind(DF[a:b,], DF[b,][rep(NA, DF$Var_2[b]), ]),
  starts, stops)

We now have a list of frames:
str(DFaug_list)
# List of 4
#  $ :'data.frame': 3 obs. of  2 variables:
#   ..$ Var_1: Factor w/ 8 levels "A","B","C","D",..: 1 2 NA
#   ..$ Var_2: int [1:3] 0 1 NA
#  $ :'data.frame': 4 obs. of  2 variables:
#   ..$ Var_1: Factor w/ 8 levels "A","B","C","D",..: 3 4 NA NA
#   ..$ Var_2: int [1:4] 0 2 NA NA
#  $ :'data.frame': 2 obs. of  2 variables:
#   ..$ Var_1: Factor w/ 8 levels "A","B","C","D",..: 5 NA
#   ..$ Var_2: int [1:2] 1 NA
#  $ :'data.frame': 4 obs. of  2 variables:
#   ..$ Var_1: Factor w/ 8 levels "A","B","C","D",..: 6 7 8 NA
#   ..$ Var_2: int [1:4] 0 0 1 NA

and all we have to do to combine them is a trick with do.call or use functions from either of the data.table or dplyr packages:
DFaug <- do.call(rbind.data.frame, DFaug_list)
DFaug
#      Var_1 Var_2
# 1        A     0
# 2        B     1
# NA    <NA>    NA
# 3        C     0
# 4        D     2
# NA1   <NA>    NA
# NA.1  <NA>    NA
# 5        E     1
# NA2   <NA>    NA
# 6        F     0
# 7        G     0
# 8        H     1
# NA3   <NA>    NA
DFaug <- data.table::rbindlist(DFaug_list)
DFaug <- dplyr::bind_rows(DFaug_list)

A: You could repeat each row Var_2 times and replace duplicated rows with NA
library(dplyr)
DF1 <- DF %>% mutate(Var_3 = Var_2 + 1, row = row_number()) %>%
             tidyr::uncount(Var_3)
DF1[duplicated(DF1$row), ] <- NA
DF1$row <- NULL

#    Var_1 Var_2
#1       A     0
#2       B     1
#2.1  <NA>    NA
#3       C     0
#4       D     2
#4.1  <NA>    NA
#4.2  <NA>    NA
#5       E     1
#5.1  <NA>    NA
#6       F     0
#7       G     0
#8       H     1
#8.1  <NA>    NA


text:
Q: update cell data with results from procedure i would like to run a procedure on a schedule, take the results from that procedure and input that data into a cell.
BEGIN
    select location from StartPositions where id = (FLOOR(1 + RAND() * (5 - 0 +1)));
    UPDATE wanderingtrader.npcs
    SET startpos=''
    WHERE id=1;
END

when SET startpos =
i need this data to be the result of the location given by the id which gets the coords

A: set startpos = (select location from StartPositions where id = (FLOOR(1 + RAND() * (5 - 0 +1))))


text:
Q: How to fix CORS error while callnig Laravel on Homestead from localhost browser I'm having Laravel 8 running on Homestead (Windows 11 OS) and can call APIs normally from Postman but when I try to call any API from the browser (build using VUE JS) I get CORS error. here's my Http/Middleware/Cors.php
namespace App\Http\Middleware;
use Closure;
class Cors {
    /**
     * Handle an incoming request.
     *
     * @param \Illuminate\Http\Request $request
     * @param \Closure $next
     * @return mixed
     */
    public function handle($request, Closure $next) {
        $response = $next($request);
        $response->headers->set('Access-Control-Allow-Origin', '*');
        $response->headers->set('Access-Control-Allow-Methods', 'POST, GET, OPTIONS, PUT, DELETE');
        $response->headers->set('Access-Control-Allow-Headers', '*');

        return $response;
    }

}

THis didn't fix the problem so I installed fruitcake/laravel-cors and modified app\Http\Kernel.php
protected $middleware = [
    \Fruitcake\Cors\HandleCors::class,
    \App\Http\Middleware\TrustProxies::class,
    \App\Http\Middleware\CheckForMaintenanceMode::class,
    \Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
    \App\Http\Middleware\Cors::class,
    \App\Http\Middleware\TrimStrings::class,
    \Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
    \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
];

It didn't work also so I tried to modify the cors config
'paths' => ['*', 'api/*'],
'allowed_origins' => ['*', 'http://localhost:8081', 'http://192.168.1.27'],

But still can't make API requests from the browser to Laravel on Homestead. Any help please?
[Update]
In the console I get
ccess to XMLHttpRequest at 'https://backend.test:44300/api/passport_auth' from origin 'http://localhost:8081' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

A: try putting these lines to your /etc/nginx/sites-enabled/domain.tld configuration file. Check here for more detail:
https://github.com/laravel/homestead/issues/1368#issuecomment-609668101
add_header 'Access-Control-Allow-Origin' '*' always;
add_header 'Access-Control-Allow-Credentials' 'true' always;
add_header 'Access-Control-Allow-Methods' 'GET, POST, PUT, DELETE, OPTIONS' always;
add_header 'Access-Control-Allow-Headers' 'Accept,Authorization,Cache-Control,Content-Type,DNT,If-Modified-Since,Keep-Alive,Origin,User-Agent,X-Requested-With' always;


text:
Q: What is the order of function arguments evaluation and structs initialization in Rust? Is the order of function argument evaluation defined in Rust?
fn f(a: u64, b: u64, c: u64) {}
fn g() -> u64 { 0 }
fn h() -> u64 { 1 }
fn i() -> u64 { 2 }

fn main() {
    f(g(), h(), i());
}

Also, I am worried about the initialization order of structs:
fn f() {}
fn g() {}

A {
    a: f(),
    b: g(),
}

Is the order guaranteed to be a and then b?
For my particular use case, I am going to initialize a struct within a diesel transaction like that:
db_connection.transaction(||
    Ok(CompanyAndUser {
        company: companies::register_company(...)?, // performs diesel insert
        user: users::register_user(...)?, // performs diesel insert
    })
);

Obviously, I want these two diesel calls within a transaction to be ordered.
I have not found any information about this, unfortunately. Also, I've found some more or less relevant info, but it was quite old.

A: The order used to be unspecified, but it's now left-to-right:

Many expressions contain sub-expressions, called the operands of the expression.

and:

The operands of these expressions are evaluated prior to applying the effects of the expression. Expressions taking multiple operands are evaluated left to right as written in the source code.


text:
Q: I am trying to write a parser but I got these errors: I am trying to write a parser but after I did javac ProgramParser*.java I got these errors:
error: package org.antlr.v4.runtime does not exist

import org.antlr.v4.runtime.ParserRuleContext;

ProgramParserBaseListener.java:4: error: package org.antlr.v4.runtime.tree does not exist

import org.antlr.v4.runtime.tree.ErrorNode;
ProgramParserBaseListener.java:5: error: package org.antlr.v4.runtime.tree does not exist

import org.antlr.v4.runtime.tree.TerminalNode;
ProgramParserListener.java:2: error: package org.antlr.v4.runtime.tree does not exist

import org.antlr.v4.runtime.tree.ParseTreeListener;

Any idea why and what I should do to fix this?


text:
Q: align environment with multicols not starting on top of the column I want to make tree columns wit an simple equation. Problem is that the first equation in the environment align is not aligned on top of the column. With text I don't have that problem:
\documentclass[11pt,a4paper,addpoints,twoside]{exam}
\usepackage{geometry}
\geometry{a4paper}
\geometry{margin=1in}

\usepackage{amsmath}
\usepackage{marvosym}
\usepackage{multicol}
\setlength{\columnsep}{20pt}
\setlength{\columnseprule}{0.3pt}

\begin{document}

\section{Oplossen van vergelijkinegn}
Voorbeeldopgaven:
\begin{multicols}{2}
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec dapibus lectus sed sollicitudin venenatis. Ut ut convallis elit. Morbi non tortor faucibus, facilisis nisl et, faucibus nunc. Nunc faucibus et massa non venenatis. Phasellus sed lorem id ex fermentum auctor. Aenean blandit velit vel augue ultrices dictum. Praesent nec tortor pharetra, facilisis tellus sed, ullamcorper ipsum. Sed in odio pellentesque, interdum ex vitae, laoreet ante. Vestibulum dui erat, cursus sit amet pulvinar vel, convallis ut risus. Sed fringilla, lacus sit amet tempor finibus, felis purus elementum nulla, nec condimentum nisl erat vitae ante. Proin iaculis odio eget aliquam aliquam. In ac leo ex. Phasellus ut risus ut libero lobortis pretium vitae sit amet arcu. Aliquam ipsum ex, vulputate quis arcu et, porta sodales mauris. Phasellus pellentesque tellus vel venenatis dignissim. Phasellus id ullamcorper velit, vel hendrerit sapien.
\end{multicols}

\begin{multicols}{3}
\begin{align*}
    x+3&=7 \\
    x&=7-3\\
    x&=4
\end{align*}
\columnbreak
\begin{align*}
    x-5&=7 \\
    x&=7+5\\
    x&=12
\end{align*}
\begin{align*}
    -x+2&=6 \\
    -x&=6-2\\
    -x&=4\\
    x&=-4
\end{align*}
\end{multicols}

\end{document}

So how can I make the first equation to be aligned at the top of the column?

A: you missed \noindent in the first column.
\documentclass[11pt,a4paper,addpoints,twoside]{exam}
\usepackage{geometry}
\geometry{a4paper}
\geometry{margin=1in}

\usepackage{amsmath}
\usepackage{marvosym}
\usepackage{multicol}
\setlength{\columnsep}{20pt}
\setlength{\columnseprule}{0.3pt}

\begin{document}

\section{Oplossen van vergelijkinegn}
Voorbeeldopgaven:
\begin{multicols}{2}
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec dapibus lectus sed sollicitudin venenatis. Ut ut convallis elit. Morbi non tortor faucibus, facilisis nisl et, faucibus nunc. Nunc faucibus et massa non venenatis. Phasellus sed lorem id ex fermentum auctor. Aenean blandit velit vel augue ultrices dictum. Praesent nec tortor pharetra, facilisis tellus sed, ullamcorper ipsum. Sed in odio pellentesque, interdum ex vitae, laoreet ante. Vestibulum dui erat, cursus sit amet pulvinar vel, convallis ut risus. Sed fringilla, lacus sit amet tempor finibus, felis purus elementum nulla, nec condimentum nisl erat vitae ante. Proin iaculis odio eget aliquam aliquam. In ac leo ex. Phasellus ut risus ut libero lobortis pretium vitae sit amet arcu. Aliquam ipsum ex, vulputate quis arcu et, porta sodales mauris. Phasellus pellentesque tellus vel venenatis dignissim. Phasellus id ullamcorper velit, vel hendrerit sapien.
\end{multicols}

\begin{multicols}{3}
\noindent\begin{align*}
    x+3&=7 \\
    x&=7-3\\
    x&=4
\end{align*}
\columnbreak
\begin{align*}
    x-5&=7 \\
    x&=7+5\\
    x&=12
\end{align*}
\begin{align*}
    -x+2&=6 \\
    -x&=6-2\\
    -x&=4\\
    x&=-4
\end{align*}
\end{multicols}
\end{document}


text:
Q: How to tell if two 3D vectors are in the same direction? Given:

$$AB=\left( \begin{array}{ccc}2\\1\\3\end{array} \right) \;\;\;\; \text{and}\;\;\;\; CD=\left( \begin{array}{ccc}4\\3\\6\end{array} \right).$$

Justify if $AB$ has the same direction as $CD$ -- give the explanation.

A: I don't know how deep you're already into vector theory, so the following might be too easy and way too basic. But anyways, it doesn't hurt to refresh that knowledge I guess.
The other answers are correct. If $AB$ and $CD$ have the same direction, then $r\cdot AB=CD$ for some real number $r\geq 0$ (If there is such $r$, but it is negative, they are exactly in opposite directions! Sometimes when people say "same direction", they include the case $r<0$ which can be quite confusing...). In your case this means $r\cdot\begin{pmatrix}2\\1\\3\end{pmatrix}=\begin{pmatrix}4\\3\\6\end{pmatrix}$ which means $\begin{pmatrix}r\cdot 2\\r\cdot 1\\r\cdot 3\end{pmatrix}=\begin{pmatrix}4\\3\\6\end{pmatrix}$, so there must be a $r\geq 0$ such that
$$\begin{align*}2r&=4 \\r&=3\\3r&=6\end{align*}$$
hold at the same time. Well, that's not possible, because if $r=3$, then $2r=6\neq 4$.
Just for illustration why this is the correct way (only 2D, works for 3D the same):

So if we want to know if $AB$ and $CD$ have the same direction, we fix the starting point of $AB$ and $CD$ to be in the same place (usually $(0,0)$, so the end point of the vectors is the same as in the vector representation, but it doesn't really matter). The vectors (and their direction) don't change when we "move" them around like that which is an important point in the concept of vectors. Then, we clearly see that in this example they're not in the same direction. (And we observe that there's no $r$ such that $r\cdot AB=CD$, which you can proove the same way as I did with your example above.)
Take another example:

Doing the same here as explained before, we see that these two are in the same direction. And if we do the math, one can observe, that $2\cdot AB=CD$.
(Through all this, $AB$ and $CD$ are vectors, $A, B, C$ and $D$ are points.)
Alternative way (also mentioned in another answer):
As you probably know, the cross product of two vectors $v_1, v_2$ yields a third vector $w$ which is perpendicular to the initial two vectors and the length of that vector equals the area of the parallelogram with sides $v_1$ and $v_2$. So if the cross product between two vectors is $0$ (so length is $0$ too), you could say that the area of said parallelogram is $0$, so $v_1$ and $v_2$ are in the same direction. (Considering the defining formula of the cross product which you can see in Mhenni's answer, one can observe that in this case the angle between the two vectors is 0° or 180° which yields the same result - the two vectors are in the "same direction".)

A: Hint: Consider their cross product

$$ ||u \times v|| = ||u||\,||v||\sin \theta. $$

The above equation should tell you something.

A: To be in the same direction, they have to be proportional. The first component of AB is half the first of CD, but the second component is three times smaller, so they are not proportional.
This means they have different directions.

A: If they are truly in the same direction, the elements need to be proportional, so divide corresponding components and see if you get the same value.  In your example, you have $\frac 42, \frac 31, \frac 63$  Since they are not equal, the two vectors are in different directions.

A: Vectors are parallel if the cross product is zero.
In this example the cross product yields $(-3,0,2)$ hence they are not parallel i.e., in the same direction.

A: I am adding this answer as there's no single one listing all conditions to have vectors of the same direction. Summarizing:

$$ ||u \times v|| = 0 \qquad \textrm{(vectors are collinear)} $$
  $$ \qquad u \cdot v > 0 \qquad \textrm{(vectors have same direction)} $$

A: Using the cosine rule
$$A.B = |A||B|cos(t)$$
Note that for same direction
$$cos(t) = 1.0$$
for opposite direction
$$cos(t) = -1$$
so now we can make a boolean test ( true for approximately the same direction )
$$\frac{A.B}{|A||B|} > 0$$
but that is expensive to calculate as calculating the length of a vector requires a square root. We don't want to do that.
$$\frac{(A.B)^2}{|A|^2|B|^2} > 0$$
or
$$\frac{(A.B)^2}{(A.A)(B.B)} > 0$$


text:
Q: Is there a way to show more live data with chart.js? I'm trying to display live data given the past day, week, month, etc. Currently, the graph displays only a section of live data but I'd like for more to be shown. I'm using a barchart for now, and I'm aware of the live data having the same time logged, but I wanted to see if there is a way for more than 20 points to be shown on the chart. I added the code that I think I should edit. I've tried ticks and bounds but it's a little difficult for me to navigate exactly what I want on the chart.js site.
Edit: after some fixes to my database, I can see more data points displayed. However, when I choose "past month", I am supposed to have every recorded point from the past month. Would a scatter plot with a line through it be more reasonable to display?
Below is the application test image and code block:
Application test image
var myChart = document.getElementById("chart").getContext('2d');

gradient = myChart.createLinearGradient(0, 0, 0, 400);
gradient.addColorStop(0, 'rgba(29, 140, 248, 0.75)');
gradient.addColorStop(0.5, 'rgba(29, 140, 248, 0.5)');
gradient.addColorStop(1, 'rgba(29, 140, 248, 0)');

// Global Options
Chart.defaults.global.defaultFontFamily = 'inherit';
Chart.defaults.global.defaultFontSize = 18; //Effects x and y's number font size
Chart.defaults.global.defaultFontColor = '#777';

barchart = new Chart(myChart, {
    type:'bar',
    data: {
        labels: {{ data.x_vals | tojson }},
        datasets:[{
            label:'Liquid Level',
            data: { { data.y_vals } },
            backgroundColor: gradient,
            borderWidth:1, //Effects plotted line on chart
            borderColor:'white',
            hoverBorderWidth:1,
            hoverBorderColor:'white',
            barThickness:15
        }]
    },
    options: {
        legend: {
            display:true,
            position:'right',
            labels: { fontColor:'#000' }
        },
        scales: {
            yAxes: [{
                display: true,
                ticks: {
                    suggestedMin: 0,
                    steps: 10,
                    stepValue: 10,
                    max: 100
                }
            }],
            xAxes: [{
                display: true,
                ticks: {
                    autoSkip: true,
                    padding: 4,
                    fontSize: 12
                }
            }]
        },
        layout:{
            padding:{
                left:0,
                right:0,
                bottom:0,
                top:0
            }
        }
    }
});


text:
Q: Logo background colour looks different on mobile vs web I have a logo with a blue background, I've picked the colour via Chrome inspector (matches Firefox colour picker as well), yet on mobile the logo stands out on the background.

What's going on/how can I prevent this?

A: Why you see another color on another display?
That logo has at least 5 colors in the background. That's the reason you can not match it.
Your monitor and mobile displays are not accurate, and it seems your contrast and brightness of the screen are not correct. In the professional photography and video editing, they call it color blind.
That's the reason professional designers do not use consumer monitors.
If you are a designer you need to have color accurate monitor and you need to calibrate it.
If you want to keep working on the current monitor at least change your monitor brightness, contrast and color settings, close to the natural settings.
What is the software solution?

*

*Get the logo in SVG, PSD or PNG file from the designer. SVG files are better because they are vector files that you can open it with free software like Inkscape. Change whatever you like and export it to the PNG.

*If your logo is a text like what you have here, Search font by image and recreate it with Inkscape. The logo you mentioned here seems to be two fonts. Clinica Pro and Sixta. and both of them are not free font.

*You can remove the background using Gimp, Layer > Color to Transparency > Color to Alpha, and select background color.
Useful links:
Changing Background Color
Making the background of an image transparent in Gimp
Anyway, I did remove the background from that logo for you (Transparent Background):


text:
Q: Name of data types in DataFrame Python? I have one simple question about types of data in Pandas DataFrame:
A column which has values like:
1,
22,
56,
66

is a numerical values column.
What is a type of values in column which has values like this:
radio,
TV,
Car

and so on ?


text:
Q: Hide element when click on checkbox I'm trying to hide element when the checkbox is clicked.
Somehow it didn't work -
html
<input type="checkbox"  onchange="showAtidit()">

hide me

js
function showAtidit($)
{
    if ($(this).is(':checked'))
    {
        alert("not hide");
        document.getElementById( "hidethis" ).style.display = 'block';
    }
    else
    {
        alert("hide");
        document.getElementById( "hidethis" ).style.display = 'none';
    }
};

http://jsfiddle.net/wv97mpcp/108/
What's wrong?
Thanks!

A: Since you're using jquery just use toggle() :
function showAtidit()
{
   $('#hidethis').toggle();
}

Hope this helps.

function showAtidit()
{
  $('#hidethis').toggle();
}

<input type="checkbox"  onchange="showAtidit()">

hide me

A: remove the $ in your function parameters and the problem will be fixed :)
function showAtidit()
    {
        if ($(this).is(':checked'))
        {
            alert("not hide");
            document.getElementById( "hidethis" ).style.display = 'block';
        }
        else
        {
            alert("hide");
            document.getElementById( "hidethis" ).style.display = 'none';
        }
    };

could also do it like this:
function showAtidit()
    {
        if(document.getElementById('checkbox').checked) {
          $("#hidethis").hide();
        }
        else {
          $("#hidethis").show();
        }
    };

(have to add id to checkbox tho)

A: Since you are using jQuery, toggle is the way to go, Here I am testing the checked:

$(function(){
  $("#toggleP").on("click",function() {
    $("#hidethis").toggle(!this.checked);
  });
});

<input type="checkbox" id="toggleP">

hide me

If you want to look at the state when loading the page:
$(function(){
  $("#toggleP").on("change",function() {
    $("#hidethis").toggle(!this.checked);
  }).change();
});

A: Please check this out. I hope it will help

$('#sample').on("change",showAtidit)
function showAtidit()
 {
  if ($(this).is(':checked'))
  {
   alert("not hide");
   document.getElementById( "hidethis" ).style.display = 'block';
  }
  else
  {
   alert("hide");

   document.getElementById( "hidethis" ).style.display = 'none';
  }
 };

 <input id="sample" type="checkbox">

hide me

A: Using $(this).toggle() is risky as you can guarentee the initial state of checkbox which may cause the checkbox not work as intended.
The actually problem with your code is the $  in the function variable.
You can see this is the issue by looking in the console on the jsfiddle you posted by pressing f12.
Here is a revised JSFiddle that will work.
http://jsfiddle.net/wv97mpcp/112/


text:
Q: JQuery without a selector? I'm trying to develop a cycling image slider and have a question about a document I'm referencing for development.
The JQuery function doesn't actually call a selector and I'm not exactly sure how to read it.
$.fn.cycle = function(options, arg2) {
var o = { s: this.selector, c: this.context };

The script above is in my javascript document and the method below is in my HTML doc calling to the script above.
$(document).ready(function() {
$('.headline').cycle({
    fx: 'fade', // choose your transition type, ex: fade, scrollUp, shuffle,
    cleartypeNoBg:true
});

.headline is a class that is defined in the HTML document. I'm confused because this has a selector and $.fn.cycle does not.
Is .headline passing in the value to .fn? If so, how is it passing in only to that section of the variable?
If you wish to see the full JQuery function it is here:
$.fn.cycle = function(options, arg2) {
var o = { s: this.selector, c: this.context };

// in 1.3+ we can fix mistakes with the ready state
if (this.length === 0 && options != 'stop') {
    if (!$.isReady && o.s) {
        log('DOM not ready, queuing slideshow');
        $(function() {
            $(o.s,o.c).cycle(options,arg2);
        });
        return this;
    }
    // is your DOM ready?  http://docs.jquery.com/Tutorials:Introducing_$(document).ready()
    log('terminating; zero elements found by selector' + ($.isReady ? '' : ' (DOM not ready)'));
    return this;
}

// iterate the matched nodeset
return this.each(function() {
    var opts = handleArguments(this, options, arg2);
    if (opts === false)
        return;

    opts.updateActivePagerLink = opts.updateActivePagerLink || $.fn.cycle.updateActivePagerLink;

    // stop existing slideshow for this container (if there is one)
    if (this.cycleTimeout)
        clearTimeout(this.cycleTimeout);
    this.cycleTimeout = this.cyclePause = 0;

    var $cont = $(this);
    var $slides = opts.slideExpr ? $(opts.slideExpr, this) : $cont.children();
    var els = $slides.get();
    if (els.length < 2) {
        log('terminating; too few slides: ' + els.length);
        return;
    }

    var opts2 = buildOptions($cont, $slides, els, opts, o);
    if (opts2 === false)
        return;

    var startTime = opts2.continuous ? 10 : getTimeout(els[opts2.currSlide], els[opts2.nextSlide], opts2, !opts2.rev);

    // if it's an auto slideshow, kick it off
    if (startTime) {
        startTime += (opts2.delay || 0);
        if (startTime < 10)
            startTime = 10;
        debug('first timeout: ' + startTime);
        this.cycleTimeout = setTimeout(function(){go(els,opts2,0,(!opts2.rev && !opts.backwards))}, startTime);
    }
});

A: Your new function $.fn.cycle will be called in the context of the jQuery object:
var $foo;
$foo = $('.foo') //a jQuery object created by the factory function
$.fn.bar = function (a, b, c) {
  //within the function, `this` is the jQuery selection
  console.log(this, a, b, c);
};
$foo.bar(1, 2, 3); //will output $foo, 1, 2, 3

Typically jQuery plugins return this to maintain chainability. Additionally, they typically need to iterate over every element in the selection, so a common pattern to see is:
$.fn.foo = function () {
  //in foo, `this` is a jQuery.init object
  return this.each(function (index, element) {
    //in each, `this` is a DOM node
    var $this;
    $this = $(this);
    //do stuff
  });
};

A: The selector is this in the plugin.
For example:
$.fn.cycle = function() {
   console.log(this);
};

$('.headline').cycle(); //logs the `.headline` jQuery element

See fiddle: http://jsfiddle.net/maniator/eE6q2/

A: When you run $("selector"), then jQuery already selects the appropriate elements. After that, the .cycle plugin function is called, in which this refers to the set of matched elements.
Selection is done by the jQuery core and not by plugins. Plugins "merely" do something with the elements that are passed to it. Even $("selector"); will select elements although you don't do anything with them.


text:
Q: No rule to make target src/core/librookery_core.a needed by src/exe/rookery_exe I am still scraping the rust off of my c++ after many years of not doing this.
Here is my directory structure.
src
src/core
src/exe
This is so my unit tests don't have to fight with another main function which I've defined in src/exe.
Each of these directories has a CMakeLists.txt. (I'm building all of this using CLion.)
This is the one in src
cmake_minimum_required(VERSION 3.19)
project(${PROJECT_NAME}_src)

set(CMAKE_CXX_STANDARD 20)

include_directories(core)

add_subdirectory(core)
add_subdirectory(exe)

The one in src/core
cmake_minimum_required(VERSION 3.19)
project(rookery_core)

file(GLOB_RECURSE SOURCES LIST_DIRECTORIES true *.h *.cpp)

set(SOURCES ${SOURCES})

set(CMAKE_CXX_STANDARD 20)

add_library(${CMAKE_PROJECT_NAME}_core STATIC ${SOURCES})

and then the one in exe
cmake_minimum_required(VERSION 3.19)

project(rookery_exe)

set(CMAKE_CXX_STANDARD 20)

file(GLOB_RECURSE SOURCES LIST_DIRECTORIES true *.h *.cpp)

set(SOURCES ${SOURCES})

add_executable(${PROJECT_NAME} main.cpp)

target_link_libraries(${CMAKE_PROJECT_NAME}_exe ${CMAKE_PROJECT_NAME}_core)

and when I run it I get
[ 35%] Building CXX object src/core/CMakeFiles/rookery_core.dir/WorkFile.cpp.o
[ 40%] Linking CXX static library librookery_core.a
[ 40%] Built target rookery_core
[ 45%] Building CXX object src/exe/CMakeFiles/rookery_exe.dir/main.cpp.o
make[2]: *** No rule to make target 'src/core/librookery_core.a', needed by 'src/exe/rookery_exe'.  Stop.
make[1]: *** [CMakeFiles/Makefile2:229: src/exe/CMakeFiles/rookery_exe.dir/all] Error 2
make: *** [Makefile:136: all] Error 2

and it just built librookery_core library. Don't know what to do next.
Thanks.
Since asked for, here is the root CMakeLists.txt
cmake_minimum_required(VERSION 3.16)
project(rookery)

set(CMAKE_CXX_STANDARD 20)

include_directories(src)

add_subdirectory(src)
add_subdirectory(tst)
add_subdirectory(lib/googletest)


text:
Q: fsockopen https freezing on fgets, possible server config error I am attempting to connect to a server via PHP fsockopen to initially get a cookie for basic auth and then to persistently connect to a streaming server defined in the Location header of the response.
The problem is that my code freezes on fgets and never receives any response data from the destination server. I'm connecting via https on port 443 on an Amazon ec2 instance. The server connects fine via curl in my server's terminal or via my chome browser.
Is there an outbound firewall setting that I'm missing on ec2?  I've even opened up the inbound 443 port on the server, but of course that seems pointless.
Any thoughts?

A: I solved this problem by adding the header: "Connection: Close\r\n\r\n".
The initial request for the cookie returns a 302 redirect code and will sit on the open connection unless you pass that header.
Unfortunately, this little line had me stumped for a while.


text:
Q: script to extract files/folders from parent folder Win 7 , batch script Looking for ideas to help me with this.
I have a lot of music and most of it is in order of [artist folder] [album folder] [cd folder] [files] and I want to quickly be able to bring all music files under [artist] level.
I'm not expecting miracles so I'm thinking if I can set it up as a right click command much like WinRar does with Extract Here, that should bring everything from that folder up a level?
So I need to be able to

*

*call my batch , and pass it the target folder.

*Have the batch select all files/folders within and move to the
                        same level as target folder.
Trying to keep it simple even if I need to r/click several times for one artist!

Thanks in advance for any help, pointers or further reading!

A: Here is a script to move all files under a root directory to the root.
"Moveit.bat C:\my\music"
will find everything under that directory and move them into C:\my\music.
Line 27 is commented out ... so the script will only tell you what it would do.
Uncomment line 27 for it to actually work.
    @echo off
@rem USAGE: MoveIt root

setlocal

    pushd "%~1"
    set root=%CD%

    if "%1"=="" goto :Usage

    for /f "delims=;" %%a in ('dir /a-d /b /s ') do call :MoveIt "%%a"

    goto :EOF

:MoveIt
    rem Exclude files directly under "from"
    set target=%~d1%~p1
    if "%target:~2%"==":\" (
        if "%target%"=="%root%" (
            goto :EOF
        )
    ) else if "%target:~0,-1%"=="%root%" (
        goto :EOF
    )

    echo move "%~1" "%root%"
    rem move "%~1" "%root%" > nul || echo Failed to move "%~1" to "%root%" & goto :EOF
    goto :EOF

:Usage
    echo Usage: moveit.bat  RootDirectory
    goto :EOF


text:
Q: Substitution variable in Postgres I am an Oracle DB guy and learning Postgres. Want to check if Postgres provides substitution variable functionality to supply value at run time, below is an example from oracle
select * from test where id = '&id'; => & character
Enter value for id: 1

        ID
----------
         1


text:
Q: Slide transition is very slow My senario is my image and buttons in the center of the screen but my image on the top of them so i'm using stack , then after 2 seconds my image move slightly to the top and my buttons to the bottom.
so i'm using slide transition to move an Image slightly to the top and other buttons to the bottom, and it works but it's very slow even on a real device after release.
is there any solution to fix it or a better approach ?
thanks in advance
my code
class StartView extends StatefulWidget {
  @override
  _StartViewState createState() => _StartViewState();
}

class _StartViewState extends State<StartView> with TickerProviderStateMixin {
  bool showOptions = false;
  AnimationController controller;
  Animation<Offset> offset;
  Animation<Offset> offset2;
  Animation<Offset> offset3;
  bool _isLoadingVisitor = false;

  @override
  void initState() {
    super.initState();

    controller =
        AnimationController(vsync: this, duration: Duration(seconds: 1));

    offset = Tween<Offset>(begin: Offset.zero, end: Offset(0, -.5))
        .animate(controller);
    offset2 = Tween<Offset>(begin: Offset.zero, end: Offset(0, .8))
        .animate(controller);
    offset3 = Tween<Offset>(begin: Offset.zero, end: Offset(0, 2))
        .animate(controller);
  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    controller.dispose();
  }

  @override
  Widget build(BuildContext context) {
    ScreenUtil.init(context, width: 376, height: 670, allowFontScaling: false);
    Future.microtask(()=>Future.delayed(Duration(seconds: 2), () {
      controller.forward();
    }));

    return SafeArea(
      child: Scaffold(
        body: Container(
          child: Stack(
            children: <Widget>[
              Align(
                  alignment: Alignment.center,
                  child: SlideTransition(
                    position: offset2,
                    child: RaisedButton(
                      shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(5)),
                      child: Text(
                        Localization.of(context).trans('login'),
                        style: TextStyle(
                            fontSize: ScreenUtil().setSp(20),
                            fontFamily: 'JFFlatregular'),
                      ),
                      elevation: 0,
                      onPressed: login,
                    ),
                  )),
              Align(
                alignment: Alignment.center,
                child: SlideTransition(
                  position: offset3,
                  child: _isLoadingVisitor
                      ? CircularProgressIndicator()
                      : FlatButton(
                          child: Text(
                            Localization.of(context).trans('login_as_visitor'),
                            style: TextStyle(
                                fontSize: ScreenUtil().setSp(20),
                                fontFamily: 'JFFlatregular'),
                          ),
                          onPressed: loginVisitor,
                        ),
                ),
              ),
              Align(
                alignment: Alignment.center,
                child: SlideTransition(
                  position: offset,
                  child: Image.asset(
                    'assets/images/splash.png',

                    width: ScreenUtil().setWidth(250),
                    height: ScreenUtil().setHeight(250),
                    fit: BoxFit.fill,
                    filterQuality: FilterQuality.high,
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

A: Image resolution was too high 2040*2040 when i resized it , it works just fine


text:
Q: Spring java based configuration for ByteArrayHttpMessageConverter <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
  <property name="messageConverters">
    <util:list>
      <bean id="byteArrayMessageConverter"   class="org.springframework.http.converter.ByteArrayHttpMessageConverter"/>
    </util:list>
  </property>
</bean>

I'm new to the Spring java configuration to create a bean. Can some one help me with the java configuration for the above xml configuration. I have an requirement to send image to client through my rest spring controller.


text:
Q: Are Shagrat and Gorbag really talking about "the old days" from personal experience? In the last chapter of The Two Towers, the two orc captains, Shagrat and Gorbag discuss the current status of war and politics in Mordor.  They discuss how the Nazgul are the master's preferred servants, and talk about running away to somewhere where there are no bosses (no Sauron, no Nazgul, specifically), just like in the good old days.
In reference to several questions here (regarding topics such as possible orcish immortality), people have suggested that the two captains are speaking, from personal experience, about very ancient times, in the Second Age or very early Third Age.  I admit, this possibility had never really occurred to me (even though I have always thought that orcs of elvish stock ought to be authentically immortal).  So, is there something in their dialogue that definitely suggests that these two orcs are thousands of years old?  Or could they merely be referring to good old days only decades past, before Sauron's return to Lugburz; and references to the great siege being known to them only through history and folklore?

A: Shagrat and Gorbag also mention "the Great Siege", presumably the siege of Barad-dur 3019 to 3026 years earlier, though it could something else like the Noldorin siege of Angband.
About SA (Second Age) 500 Sauron becomes active in Middle-earth again.  Sauron begins to take control of all orc groups, ending their centuries of freedom from higher powers.
About SA 1,000 Sauron takes over Mordor, begins populating it with orcs.
In SA (Second Age) 3262 Sauron taken a prisoner to Numenor.
SA 3319 Numenor sinks, Sauron's body killed.
SA 3320 Sauron's sprit returns to Mordor and soon makes a new body.
SA 3434 to SA 3441. The Siege of Barad-dur, probably "the Great Siege" mentioned by Shagrat and Gorbag.
SA 3441.  Sauron defeated and killed and his ring taken.  The Second Age ends and the Third Age begins.  The Kingdom of Gondor guards Morder with fortresses.
About TA (Third Age) 1050. Sauron forms a new body.  All orcs and other evil creatures begin to fall more and more under Sauron's control, ending about a millennium of Orcish freedom from higher powers.
About TA 1100.  The Wise realize that some dark power, probably a Nazgul, has made a stronghold at Dol Guldur in Mirkwood.  Actually it is Sauron.
About TA 1300 Orcs and other evil creatures begin to multiply again.  The Nazgul reappear and their chief goes to Angmar and becomes the Witch-king.
TA 1636 the Great Plague devastates Gondor.
TA 1640 Mordor is left unguarded.
TA 1975.  The Witch-King of Angmar is defeated and leaves the north.
TA 1980.  The Witch-king comes to Morder and gathers the Nazgul.
TA 2000-2002.  The Nazgul from Morder besiege Minas Ithil, presumably with the help of Mordor Orcs.  This may be "the Great Seige" mentioned by Shagrat and Gorbag. Minas Ithil becomes known as Minas Morgul.
TA 2063 to TA 2460.  The Watchful Peace.  Gandalf enters Dol Guldur in Mirkwood, Sauron leaves Dol guldur and hides in the East, and the Nazgul are quiet in Mordor.  (But no doubt the Nazgul boss the Mordor orcs).
TA 2460.  Sauron returns to Dol Guldor in Mirkwood.
TA 2850.  Gandalf enters Dol Guldur in Mirkwood and discovers that Sauron has returned.
TA 2941.  The Hobbit.  And also the Wise drive Sauron from Dol Guldur in Mirkwood.
TA 2942.  Sauron returns in secret to Mordor.
TA 2951.  Sauron declares himself in Mordor and openly rebuilds his power.
The Dark Tower is rebuilt.  Three Nazgul are sent to rebuild Dol Guldur.
TA 3018. War of the Ring begins.
TA 3019. Presumably equivalent to SA 6460. War of the Ring continues.  Shagrat and Gorbag have their conversation.  This is:
68 years after Sauron openly proclaims himself.
77 years after he returns to Mordor.
1,019 years after the Nazgul have sufficient control over Mordor orcs to presumably form an army of them to besiege Minis Ithil.
1,039 years after the Witch-king comes to Mordor and gathers the nazgul, presumably bossing around the Mordor orcs.
1,719 years after orcs start multiplying again, presumably under Sauron's influence.
About 1,969 years after Sauron forms a new body and beings controlling evil creatures like orcs, ending about a millennium of orcish freedom from higher powers.
3,140 years after Sauron returns from Numenor and possibly ends a period of orcish freedom in Mordor.
And about 5,960 years since Sauron becomes active in Middle-earth again and presumably ends about 500 years of orcish independence of higher powers.
I think that it is a little presumptuous to assume that one knows which era Shagrat and Gorbag are referring to as the good old days without big bosses over the orcs.  It is theoretically possible that they might be referring to the three ages when Morgoth was imprisoned in Valinor during the Elder Days.

A: No conclusive evidence
The relevant part conversation between Shagrat and Gorbag is this:

'They would,' grunted Gorbag. 'We'll see. But anyway, if it does go well, there should be a lot more room. What d'you say? – if we get a chance, you and me'll slip off and set up somewhere on our own with a few trusty lads, somewhere where there's good loot nice and handy, and no big bosses.'
'Ah!' said Shagrat. 'Like old times.'
The Lord of the Rings Book Four, Chapter 10: The Choices of Master Samwise
Page 738 (Single volume 50th Anniversary Edition)

It is not clear whether "the old times" that Shagrat refers to are times that he himself experienced, or older times that he has heard of.
He may have been referring to the time before Sauron came back to power 68 years earlier
Even if Shagrat is speaking about his own experience, it need not have been thousands of years ago. Sauron was absent for most of the Third Age, and I assume many Orcs would have been free of "big bosses" during that period. According to The Tale of Years, it wasn't until 2951 (Third Age) that Sauron declared himself and calls his former servants to him.

2951 Sauron declares himself openly and gathers power in Mordor. He begins the rebuilding of Barad-dûr.
The Lord of the Rings Appendix B, Section 2: The Third Age
Page 1088 (Single volume 50th Anniversary Edition)

If Shagrat and Gorbag had returned to Sauron's service in 2951, that would have been 68 years before the War of the Ring.
The lifespan of Orcs
The comment by AakashM links to Are Tolkien's orcs immortal?. Answers to that question by Valorum and ElendilTheTall indicate that Orcs are not immortal and do not live as long as the Edain.

They could be slain, and they were subject to disease; but apart from these ills they died and were not immortal, even according to the manner of the Quendi; indeed they appear to have been by nature short-lived compared with the span of Men of higher race, such as the Edain"
The History of Middle-earth Volume X, Part Five: Myths Transformed, Section 10
Page 418 (Houghton Mifflin 1993 hardback edition)

Of course, the Edain lived much longer lives than most men, and we know that some Orcs did as well. As ElendilTheTall points out, Bolg succeeded his father, Azog when he was killed by Dain II in the battle of Nanduhirion in TA 2799. Bolg also takes part in the Battle of Five Armies TA 2941, making him at least 142 years old.

The Dragon was slain by Bard of Esgaroth, but there was battle in Dale. For the Orcs came down upon Erebor as soon as they heard of the return of the Dwarves; and they were led by Bolg, son of that Azog whom Dáin slew in his youth. In that first Battle of Dale, Thorin Oakenshield was mortally wounded; and he died and was laid in a tomb under the Mountain with the Arkenstone upon his breast.
The Lord of the Rings Appendix A, Section 3: Durin's Folk
Page 1079 (Single volume 50th Anniversary Edition)

Conclusion
From this I conclude that it is certainly possible that Shagrat and Gorbag could have been living free of "big bosses" before Sauron returned to power.