text:
Q: Understanding how the function traits template works. In particular, what is the deal with the pointer to member function I am trying to understand this code and I have found some more SO content on this topic.
In compact form:
#include <tuple>
namespace sqlite {
    namespace utility {
        template<typename> struct function_traits;

        template <typename Function>
        struct function_traits : public function_traits<
            decltype(&Function::operator())
        > {  };

        template <
            typename    ClassType,
            typename    ReturnType,
            typename... Arguments
        >
        struct function_traits<
            ReturnType(ClassType::*)(Arguments...) const
        > {
            typedef ReturnType result_type;

            template <std::size_t Index>
            using argument = typename std::tuple_element<
                Index,
                std::tuple<Arguments...>
            >::type;

            static const std::size_t arity = sizeof...(Arguments);

        };
    }
}

This led me to learn about the pointer-to-member-function feature of the language, and it's pretty clear to me at this point how to use the function traits (it's fairly straightforward that I can pull out not only the return type but the arity and even the types of the arguments) but I have gotten stuck in understanding why this works, or indeed why it is even possible for it to work...

A: Let's break everything down piece by piece.
template<typename> struct function_traits;

That is the primary template declaration, declaring a template class with a single template parameter.
template <typename Function>
struct function_traits : public function_traits<
    decltype(&Function::operator())
> {  };

That is essentially a forwarding trait to allow functors (objects which have an operator()) to be used with this traits class. It's a definition of the primary template which inherits from the traits for operator(). This version will be selected when the specialization which is defined later is not matched.
template <
    typename    ClassType,
    typename    ReturnType,
    typename... Arguments
>
struct function_traits<
    ReturnType(ClassType::*)(Arguments...) const
>

That begins the definition of a partial specialization of function_traits for pointers to member functions. When you pass a member function pointer type as the template argument to function_traits, this specialization will be selected. The return type, class type and argument types will be deduced as template parameters.
    typedef ReturnType result_type;

That is a simple typedef which aliases the deduced ReturnType template parameter to result_type.
    template <std::size_t Index>
    using argument = typename std::tuple_element<
        Index,
        std::tuple<Arguments...>
    >::type;

That is what is called an alias template. When you provide an index such as function_traits<myFunc>::template argument<2>, it will collapse down to typename std::tuple_element<2, std::tuple<Arguments...>>::type. The goal of that is to extract the type of the argument at index Index. Rather than writing out all the template metaprogramming code to do that manually, the author chose  to use the existing code in std::tuple. std::tuple_element extracts the type of the nth element of a tuple.
   static const std::size_t arity = sizeof...(Arguments);

sizeof... is used to get the size of a variadic template parameter pack, so this line stores the number of arguments for the function in the static integral member arity.

A: @tartanllama 's answer actually forgets to add std::remove_reference from the code example, which is necessary to cover all cases.
The template general case that handles lambdas should really be:
template <typename Function>
struct function_traits : public function_traits<
    decltype(&std::remove_reference_t<Function>::operator())
> {  };

If you're looking for a complete solution for all types in c++ that can be invoked, see my answer on a different SO question.

A: I did realize that the part including ClassType::* is meant to bind to decltype(&Function::operator()). I was learning about this construct (pointer to member function), but really having a tough time understanding why it's important for it to exist.
ReturnType(ClassType::*)(Arguments...) const is a template typename, in this case it is to be matched to a pointer to member function, and it is cleverly constructed in such a way as to be bound to the operator() member function, allowing the pattern matching to pull out the relevant types for us, those of the args and the return type. The ClassType would presumably become recognized as the same thing as the Function template parameter.
I was also confused by why a funny-looking templated using statement is required to look up the argument type values. I then realized that the Arguments... is a variadic template type construct which has to be tuple-ized using compile-time features and the whole business has nothing to do with "real" tuples. When I looked up tuple_element indeed it is intended as a tool for manipulating types at compile-time.
the remainder of this answer I am not sure about
I do wonder why pointer-to-member-function was used. I guess the reason could be that a regular function pointer or some such construct cannot actually be used to match the operator () member of functors, as a member function requires an instance of the object in order to become callable. This answer sheds some more light on this subject. I mostly understand it now I think.


text:
Q: Writing a variadic macro which sets specific bits in an integer (bit-mask) I'm trying to write a macro which simplifies setting multiple bits in an integer. This commonly occurs in microcontroller code when initializing configuration registers. For example, one might configure an 8-bit timer by setting 3 bits in the register TCCR0A like this:
// WGM01, WGM00 and COM0A1 are constants between 0 and 7
// There are hundreds of these constants defined in avr-libc
TCCR0A |= (1<<WGM01) | (1<<WGM00) | (1<<COM0A1);

// Another way to write this:
#define _BV(bit) (1 << (bit)) // <-- defined in avr-libc
TCCR0A |= _BV(WGM01) | _BV(WGM00) | _BV(COM0A1);

However, I'd find it a lot easier to write something like this:
TCCR0A |= BITS(WGM01, WGM00, COM0A1); // <- Variable # of arguments please!

Since I can't imagine that nobody has thought of this yet, I searched around but found nothing which does exactly this. I wonder if this is possible at all, but I gave it a shot anyways while reading https://gcc.gnu.org/onlinedocs/cpp/Variadic-Macros.html and https://github.com/pfultz2/Cloak/wiki/C-Preprocessor-tricks,-tips,-and-idioms.

Here's what I tried so far. I imagine the solution must be recursive macro, but didn't get very far when trying to get it to expand correctly. Since all my registers are 8 bits long, 8 expansion passes should be sufficient (for a first try).
#define BITS_EVAL(...)  BITS_EVAL1(BITS_EVAL1(BITS_EVAL1(__VA_ARGS__)))
#define BITS_EVAL1(...) BITS_EVAL2(BITS_EVAL2(BITS_EVAL2(__VA_ARGS__)))
#define BITS_EVAL2(...) __VA_ARGS__

#define BITS(bit, ...) ((1 << bit) | BITS_EVAL(BITS(__VA_ARGS__)))

The above doesn't quite work. What it currently does is:
// BITS(2,5,7) --> ((1 << 2) | BITS(5, 7))

However, what I would like to achieve is one of these (or equivalent):
// BITS(2,5,7) --> ((1 << 2) | (1 << 5) | (1 << 7))
// BITS(2,5,7) --> ((1 << 2) | ((1 << 5) | ((1 << 7))))

Can anyone help me with my quest, or tell me that it's impossible to achieve this?

A:
Warning: Writing this was mostly a learning exercise.
DO NOT USE IN PRODUCTION CODE. People will rightly curse at you if you do.

So, after playing around a bit more with the macros from Paul's answers and github wiki, I actually managed to produce a working BITS(...) macro which does what I intended. It is a recursive macro that is scanned multiple times to expand the recursive replacements. It handles a variable number of arguments and supports integers up to 64 bits.
// test.c
#include "bits.h"
int a = BITS(1,5,7);
int b = BITS(3);
int c = BITS(); // This case is broken but irrelevant

Using gcc -E test.c -o test.txt this expands to:
int a = (0 | (1ull<<1) | (1ull<<5) | (1ull<<7));
int b = (0 | (1ull<<3));
int c = (0 | (1ull<<)); // This case is broken but irrelevant

The 0 | at the beginning is an artifact of the implementation but obviously does not affect the result of the expression.

Here's the actual implementation including comments:
// bits.h
// Macros partially from https://github.com/pfultz2/Cloak
#define EMPTY(...)
// Defers expansion of the argument by 1, 2 or 3 scans
#define DEFER(...) __VA_ARGS__ EMPTY()
#define DEFER2(...) __VA_ARGS__ DEFER(EMPTY)()
#define DEFER3(...) __VA_ARGS__ DEFER2(EMPTY)()

// Concatenate the arguments to one token
#define PRIMITIVE_CAT(a, ...) a ## __VA_ARGS__

// Apply multiple scans to the argument expression (>64 to allow uint64_t masks)
#define EVAL(...)  EVAL1(EVAL1(EVAL1(__VA_ARGS__)))
#define EVAL1(...) EVAL2(EVAL2(EVAL2(__VA_ARGS__)))
#define EVAL2(...) EVAL3(EVAL3(EVAL3(__VA_ARGS__)))
#define EVAL3(...) EVAL4(EVAL4(EVAL4(__VA_ARGS__)))
#define EVAL4(...) __VA_ARGS__

// Always expand to the second token after expansion of arguments.
// One level of indirection to expand arguments before selecting.
#define SELECT_2ND(...) SELECT_2ND_INDIRECT(__VA_ARGS__, , )
#define SELECT_2ND_INDIRECT(x1, x2, ...) x2

// Expands to a comma (which means two empty tokens in a parameter list).
// Thus, SELECT_2ND will expand to an empty token if this is the first argument.
#define BITS_RECURSIVE__END_RECURSION ,

// Adds the END_RECURSION parameter, which marks the end of the arguments
#define BITS(...) \
    (0 EVAL(BITS_RECURSIVE(__VA_ARGS__, END_RECURSION,)))

// When hitting END_RECURSION, the CAT will expand to "," and SELECT_2ND
// will select the empty argument instead of the recursive call.
#define BITS_RECURSIVE(bit, ...) \
    SELECT_2ND(PRIMITIVE_CAT(BITS_RECURSIVE__, bit), \
             | (1ull<<(bit)) DEFER3(BITS_INDIRECT)()(__VA_ARGS__))
// Needed to circumvent disabling contexts for recursive expansion
#define BITS_INDIRECT() BITS_RECURSIVE

And some code to test the extreme cases:
// test2.c
#include "bits.h"
#include <inttypes.h>
#include <stdio.h>

uint8_t u8 = BITS(0,1,2,3,4,5,6,7);
uint32_t u32 = BITS(0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,
        16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31);
uint64_t u64 = BITS(0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,
        16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,
        32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,
        48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63);
uint64_t a64 = BITS(0,1,2,3,4,5,6,7,
        16,17,18,19,20,21,22,23,
        32,33,34,35,36,37,38,39,
        48,49,50,51,52,53,54,55);

int main(void) {
    printf("0x%02" PRIX8 "\n", u8);    // Prints 0xFF
    printf("0x%08" PRIX32 "\n", u32);  // Prints 0xFFFFFFFF
    printf("0x%016" PRIX64 "\n", u64); // Prints 0xFFFFFFFFFFFFFFFF
    printf("0x%016" PRIX64 "\n", a64); // Prints 0x00FF00FF00FF00FF
    return 0;
}

A: The GCC variadic macro feature, intends to pass the variable argument list at runtime, to a function analogous to printf, say setBits( 3, WGM01, WGM00, COM0A1) to OR n values together.  I doubt evaluating this at runtime is acceptable.
If you really want to write BITS as above, I think you could use the macro-processor m4, which allows a recursive definition with shifting of argument list, so you can test $# is 1 or >= 2.  The expansions would operate something like :
1 TCCR0A |= BITS( WGM00 , COM0A1 , WGM01 );
2 TCCR0A |= (1u << WGM00) | BITS( COM0A1 , WGM01 );          # (1u << $1) | BITS( shift($*))
3 TCCR0A |= (1u << WGM00) | (1u << COM0A1) | BITS( WGM01);      # Recusion terminates
4 TCCR0A |= (1u << WGM00) | (1u << COM0A1) | (1u << WGM01);

Somehow I would not expect thanks for including something like this in C source :
define(`BITS',`ifelse(eval($#<2),1, (1u<<`$1`''),
(1u<<`$1`'') | BITS(shift($@))')')

In the CPP tricks, apparently a first argument could be seperated, but recursive macro's are not supported, nor is there a way of evaluating a termination condition.  Perhaps a chain of expansions would be feasible and clear enough :
#define BITS4(m, ...) ((1u<<m) | BITS3(__VA_ARGS__))
#define BITS3(m, ...) ((1u<<m) | BITS2(__VA_ARGS__))
#define BITS2(m, ...) ((1u<<m) | BITS1(__VA_ARGS__))
#define BITS1(m) ( 1u << m)

Testing this :
printf( "BITS3( 0, 1, 2) %u\n", BITS3( 0,1, 2));
printf( "BITS2( 0, 1) %u\n", BITS2( 0,1));
printf( "BITS1( 0) %u\n", BITS1( 0));

Results :
    BITS3( 0, 1, 2) 7
    BITS2( 0, 1) 3
    BITS1( 0) 1
Which is those expected.  Whilst this is not the general bit set macro hoped for, the solution has clarity so ought be maintainable.

A: Define you bit macros as actual bits that they set, no magic number hardcoding required, becase if the macros change so do their _B counterparts:
#define WGM00_B  (1u<<WGM00)
#define COM0A1_B (1u<<COM0A1)
#define WGM01_B  (1u<<WGM01)
...

Then simply or them together, no macro needed and the order is irrelevant:
TCCR0A |= WGM00_B | COM0A1_B | WGM01_B;

Or put it in a macro. The usage is just like you asked, but instead of commas, you use bitwise or operator.
TCCR0A |= BITS( WGM00_B | COM0A1_B | WGM01_B );

Macro BITS is defined simply as:
#defined BITS( b ) (b)

A: I couldn't find a good answer for this a few years later, so I came up with this...

*

*A _bits macro that takes 8 bit-position arguments (and accepts but ignores any number of additional ... arguments).

*A bits(...) macro that passes its arguments to _bits along with 8 x trailing 8s.

*The 8s result in (uint8_t)(1 << 8) == 0 (or are ignored if they fall into the ... part of the argument list of _bits).

Note 1. The ignored argument x is there to support the empty args case, bits() == 0, which seems nice for consistency. e.g. you might have empty #define OPTION_NO_FOO_DISABLED and want bits(OPTION_NO_FOO) == 0
Note 2. Only the first 8 arguments are used.
e.g. bits(1,1,1,1,1,1,1,1,2) == 1. -- thx Fritz
#define _bits(x, i, j, k, l, m, n, o, p, ...) \
    ((uint8_t)( (uint8_t)(1U << (i)) | \
                (uint8_t)(1U << (j)) | \
                (uint8_t)(1U << (k)) | \
                (uint8_t)(1U << (l)) | \
                (uint8_t)(1U << (m)) | \
                (uint8_t)(1U << (n)) | \
                (uint8_t)(1U << (o)) | \
                (uint8_t)(1U << (p)) ) )

#define bits(...) _bits(x, ## __VA_ARGS__, 8, 8, 8, 8, 8, 8, 8, 8)

int main()
{
    assert(bits() == 0);
    assert(bits(8) == 0);
    assert(bits(7) == (uint8_t)((1 << 7)));
    assert(bits(0) == (uint8_t)((1 << 0)));
    assert(bits(0, 8) == (uint8_t)((1 << 0) | (1 << 8)));
    assert(bits(8, 0) == (uint8_t)((1 << 8) | (1 << 0)));
    assert(bits(1,2,3) == (uint8_t)((1 << 1) | (1 << 2) | (1 << 3)));
    assert(bits(7,7,7) == (uint8_t)((1 << 7) | (1 << 7) | (1 << 7)));
    assert(bits(6,2,3,4,0,7,5,1) ==
                (uint8_t)((1 << 6) | (1 << 2) | (1 << 3) | (1 << 4) |
                          (1 << 0) | (1 << 7) | (1 << 5) | (1 << 1)));
    assert(bits(6,2,3,4,0,7,5,1,2,2,2) ==
                (uint8_t)((1 << 6) | (1 << 2) | (1 << 3) | (1 << 4) |
                          (1 << 0) | (1 << 7) | (1 << 5) | (1 << 1)));
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: How can I use streams on this PieChart I recently started learning flutter and I learnt reactive programming in flutter (Learning it actually).
Here's what i want, I have a PieChart that takes a map as an input and draws it. (Suppose the map map = { "Food" : 5, "Transportation" : 2}
What i want to do is to have a button that when i click would increment the food by 1 and then the PieChart would rerender. (eventually the button would allow the user to add their own string and int but for now i hardcode for testing)
My idea is to have a PieChart wrapped with a StreamBuilder that would watch over a stream and rebuild the PieChart when we add input to that stream.
I just don't know how to implement it properly, i also don't know if i should make the stream take in a map, or some class called deposit that has a string and a double for example.
Here's my boilerplate:
import 'package:flutter/material.dart';
import 'package:pie_chart/pie_chart.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  Map<String, double> dataMap = {"Food": 5, "Transportation": 3};

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text("Testing"),
        ),
        body: PieChart(dataMap: dataMap),
        floatingActionButton: FloatingActionButton(
          child: Icon(Icons.add),
          onPressed: () {
            dataMap["Food"] = dataMap["Food"] + 1;
          },
        ),
      ),
    );
  }
}

A: import 'package:flutter/material.dart';
import 'package:pie_chart/pie_chart.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  Map<String, double> dataMap = {"Food": 5, "Transportation": 3};

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text("Testing"),
        ),
        body: PieChart(dataMap: dataMap),
        floatingActionButton: FloatingActionButton(
          child: Icon(Icons.add),
          onPressed: () {
            setState(() => dataMap["Food"] += 1);

          },
        ),
      ),
    );
  }
}

All you need to do is use setState to tell the widget the state has changed.
https://docs.flutter.io/flutter/widgets/State/setState.html
This pattern is inspired by Reactjs. Note: do not put compute heavy operations in setState callback
Here is an example of a Stream
https://github.com/flutter/plugins/blob/master/packages/sensors/example/lib/main.dart
I do not have the Stream function, so I cannot write code.

A: If you really want to know about the basics of Streams and how to use it this is the post you are looking for you can learn mucho from it.
You can learn that and much more from Thomas Burkhart even a new pattern call RxVMS.


text:
Q: Two non-isomorphic groups with the same complex character table Could you give me an example of two non-isomorphic groups with the same complex character table?

A: Once you have one example of nonisomorphic groups $G_1$ and $G_2$ with the same character table, the groups $G_1 \times H$ and $G_2 \times H$ also have the same character table for any finite group $H$ (because irred. characters of $G \times H$ are precisely products of irred. characters of $G$ and irred. characters of $H$). If you take for $H$ a group with order relatively prime to the common order of $G_1$ and $G_2$, then $G_1 \times H$ is nonisomorphic to $G_2 \times H$. So you get infinitely many examples that way.
The example of the dihedral and quaternion groups (of order 8) mentioned by Gerry is the starting point for an infinite sequence of examples: the dihedral and generalized quaternion groups of order $2^n$ for all $n \geq 3$ are nonisomorphic with the same character table.

A: The dihedral group and the quaternion group.


text:
Q: How to validate a Timestamp from an ASN.1 encoded byte stream in Java I'm trying to validate a timestamp from an ASN.1 encoded byte stream in Java.
I'm using the bouncycastle package.
I'm creating the TimeStampToken from the encoded byte I got from the timestampserver.
TimeStampToken testTsToken = new TimeStampToken(new CMSSignedData(encodedByte));

For validation there is the following function.
testTsToken.validate(SignerInformationVerifier);
testTsToken.validate(X509Certificate, String);

I'm now wondering how do I get those Parameters?
How can I create a SignerInformationVerifier or a X509Certificate?.
I would appreciate any help because I'm stuck on this issue for days now :/

A: My problem was that when asking for the timestamp i forgot to ask for a certificate. That's why I couldn't validate.


text:
Q: Can a github repo be made to always refer to the latest version of its submodule repos? I'm making a webapp that does version control of files using git and it has the option of being hosted on GitHub Pages with some missing features (features not supported by a git-only backend).
Now the "app" itself is separated from the users content, the user content is version controlled but the app is not (or at least doesn't need to be for the functionality of the app itself), but both need to be uploaded to github pages and to isolate the content's version control, and to have different permissions for the app vs content, I host the app itself in gh-pages and the content as a git submodule inside the gh-pages repo.
This works, the app/site is built and gets exposed on username.github.io/sitename/ with everything accessible, except there is a catch.
The catch is that for some reason the submodule content repo is referred to at a specific commit instead of just the latest version of the repo, which means I can't just update the content repo and have everything work but also have to update the app repo to refer to the latest version of the submodule, on every content repo commit.
Which gets a bit tedious since I almost never actually have to update the app repo unless there is a new version of the app but I update the content repo daily, as well as the fact that the content repo should be editable by many people but the app repo by few.
So my question is:

*

*How can I define a submodule to always refer to the latest commit of a repo?

*How can I trigger a build of the site by only updating the submodule repo?

*How can the gh-pages repo always reflect the latest version of its submodules, so that the gh-pages site is always serving the latest content?

*

*Example repos:

*

*https://github.com/01AutoMonkey/app

*https://github.com/01AutoMonkey/app-content

*Combined running at: http://01automonkey.github.io/app/

*Git Submodules:

*

*https://git-scm.com/docs/git-submodule

*https://git-scm.com/book/en/v2/Git-Tools-Submodules

*https://help.github.com/articles/using-submodules-with-pages/
How I create the submodule
# Create app master + app-content master, then:
git init
git remote add origin https://github.com/01AutoMonkey/app.git
git submodule add https://github.com/01AutoMonkey/app-content ./wiki
cd wiki
git remote add origin https://github.com/01AutoMonkey/app-content.git
# And then push to both repos and create a gh-pages branch.
# The site is now running but if I update app-content the update isn't reflected on the site until I refer to the new commit in the app repo.

A: Please find my responses inline:

How can I define a submodule to always refer to the latest commit of a repo?

This is not possible from the concept and purpose of git-submodule. Though for easy update purpose you can configure a branch for a submodule.
$ git config -f .gitmodules submodule.hs-srvcommon.branch sprint is the command which will override the default master branch with sprint. (hs-srvcommon is the name of the submodule directory)

How can I trigger a build of the site by only updating the submodule repo?

You can write commands to trigger your build on the commits made on the submodule repo using the git-hooks on the submodule. The git-hooks configured on the submodule work the same way as the git-hooks for main repo work. The residing place for the hooks of the submodules are .git/modules/your-sub-module-name/hooks Refer: https://git-scm.com/docs/githooks

How can the gh-pages repo always reflect the latest version of its submodules, so that the gh-pages site is always serving the latest content?

Ohh this again should be feasible with using the git-hooks for the submodule. All you need to do is configure the post-commit/push-hooks on the submodule so that they also update the main repo references to the submodule commit sha ids.
May this answer help you in doing some git operations on the main repo from inside the git-hooks of the submodule repo.

A:
The catch is that for some reason the submodule content repo is referred to at a specific commit instead of just the latest version of the repo, which means I can't just update the content repo and have everything work but also have to update the app repo to refer to the latest version of the submodule, on every content repo commit.

You have to add the following commands
# Create app master + app-content master, then:
git init
git remote add origin https://github.com/01AutoMonkey/app.git
git submodule add https://github.com/01AutoMonkey/app-content ./wiki

#
#
#
git submodule init

# Run this command every time you want to update the submodule
git submodule update
#
#
#
cd content
git remote add origin https://github.com/01AutoMonkey/app-content.git

Now grab the latest code for each submodule:
# loop on every submodule and checkout the latest code
git submodule foreach git pull origin master

foreach
Evaluates an arbitrary shell command in each checked out submodule.

From the submodule docs:

When cloning or pulling a repository containing submodules however, these will not be checked out by default;
the init and update subcommands will maintain submodules checked out and at appropriate revision in your working tree.
update
Update the registered submodules to match what the superproject expects by cloning missing submodules and updating the working tree of the submodules


text:
Q: How do I copy a file retaining the original permissions? I would like to copy a file using pure Go, emulating the behavior of cp -p.
My copy function currently looks like:
// copy creates a copy of the file located at `dst` at `src`.
func copyFile(src, dst string) error {
    in, err := os.Open(src)
    if err != nil {
        return err
    }
    defer in.Close()

    out, err := os.Create(dst)
    if err != nil {
        return err
    }

    _, err = io.Copy(out, in)
    if err != nil {
        out.Close()
        return err
    }
    return out.Close()
}

which will create dst owned by whoever is running the process. Instead, I would like to keep the owner and permissions of src, i.e. what I get from:
// copy creates a copy of the file located at `dst` at `src`.
func copyFile(src, dst string) error {
    cmd := exec.Command("cp", "-p", src, dst)
    return cmd.Run()
}

but without having to call through to system commands (for portability). Everything I tried ended up calling through to something else. Is this possible to do in Go?

A: It's definitely possible in Go but not in a system-independent manner (because different OS kernels have different ideas about what "permissions" are, and how they are implemented).
Also consider that the identity used by the process copying the file might have insufficient permissions to set permissions on the target file (for instance, on Linux, a non-root user cannot change the owning group of a file to a group the user is not a member of, and it obviously cannot set the file owner to anyone other than theirselves — in other words, mere mortals cannot transfer ownerwhip, only share files within their own "circles" defined by group membership).
Basically, to do what you'r after, you have to Stat the source file and then os.Chmod (and os.Chown, if needed) the destination file after it is created.

Also please note that Linux-native filesystems support POSIX ACLs on files, and each file might or might not have them.
Whether you include this in what you define "permissions" are, is an open question.


text:
Q: Virtualenv, where is it saved and how do i use it (python, windows 10) I have no idea how virtualenv works and need help. I have made a virtual environment, activated it, and so on but i dont know where it is saved, whether it is saved and how i can access it when i am making a python project. (by access i mean use it a project)

A: I use PyCharm Community Edition, there you can easily select if you want to create Virtual Environment and where to save it, all from GUI. The best IDE in my opinion as you can do everything using it's GUI, you can even search for and install libraries.


text:
Q: Preg_match address So i'm trying to preg_match an address in PHP.
It should be letters SPACE numbers and not numbers SPACE letters.
So, like this: Myplace 16.
The length of the numbers and letters doesn't matter, but they can't be mixed together.
I already tried this one but this one doens't check spaces:
if(preg_match("/^[0-9a-zA-Z_]{5,}$/", $adres) === 0)
{
echo 'Address is wrong';
}

Thanks in advance!

A: The pattern you showed doesn't correspond at all to what you're trying to do.  For your purpose, you would do something like
/^[a-zA-Z]+\ +[0-9]+$/

This checks for at least one letter at the beginning of the string followed by 1 or more spaces followed by 1 or more digits, at which point the string must end.
Unless, of course, I misunderstand what you are trying to achieve...

A: I use 1 to capture a error (preg_match returns false, and a 0, no match)
if(1 !== preg_match('/^[a-z]*\ +\d*$/i', $address))
{
    echo 'Address is wrong';
}

This will match any character between a-z (case insensitive) between 0 and unlimited times, then match at least a space character, then any numbers between 0 and unlimited times.
If you need at least 1 letter and 1 number please change the * to a +


text:
Q: Where to find the translated JSP servlet code in Eclipse / RAD? I'm using IBM RAD v7 which is based on Eclipse and I've got a NullPointerException in a compiled JSP that I want to troubleshoot. So I wonder where websphere / Eclipse (IBM RAD) stores the source for the compiled JSP that the error message is referring to?

A: Locate your runtime directory. If this is an embedded runtime, it'll be something like:
/opt/IBM/SDP/runtimes/basev7

The servlets are usually compiled lazily to the profile's temp directory. This path will be of the form:
/profiles/profileName/temp/nodeName/serverName

The profile, node and server name are configuration dependent. Subdirectories will follow your EAR/WAR hierarchies.

A: It depends on your servlet container settings.  IN case of tomcat, it is most likely located under:
/work/Catalina///org/apache/jsp/


text:
Q: How to show there is no continuous trace operator from $W^{k,2}(R^m)$ to $W^{k,2}(R^{m-1})$? For positive integer k, how to show that there is no continuous trace operator mapping from $W^{k,2}(R^m)$ to $W^{k,2}(R^{m-1})$?
I want to prove this by contradiction, but have no idea what to do next.  My first thought is to construct a sequence of functions in $C^{\infty}(R^m)\cap W^{k,2}(R^m)$ say $f_n$ which converges to f, then to show that the sequence $g_n = Tf_n$ doesn't converge to $Tf$ in $W^{k,2}(R^{m-1})$.
Update:
Suppose that there exists such a continuous trace operator $T$.
By the fact that $W_{0}^{k,2}(R^m) = W^{k,2}(R^m)$,for a function $f$ in $W^{k,2}(R^m)$, we can find a sequence of functions $f_n$ in $C^{\infty}_{c} (R^m)$ converges to $f$. Then $Tf_n \to Tf$. Since $Tf_n = 0$ for each $n$, $Tf = 0$.
My main problem is that I am not sure how to show $Tf = 0$ is not true for every $f \in W^{k,2}(R^m)$.
Any assistance will be appreciated


text:
Q: Retrieve the Salesforce Org-wide API Consumption Percentage? I have been googling this for a while, the closest I have come to getting an answer on this is the API Consumption report here
However, I am looking to retrieve the current SFDC Org-wide API consumption metric via the Salesforce API itself.
Is there an Endpoint I can call to get this data?
Use case: I have several scripts running on a schedule that move large amounts of Data around on Salesforce, which risks our SFDC org getting capped out and I would like to check the API Consumption percentage for last 24 hours, and if the Consumption percentage is over a certain amount, the script does not proceed through the rest of the sequence.
This should help us avoid hitting our allotted max of API calls.

A: I'm not entirely certain if this is what you are seeking, but there is a "Limits" resource available through the REST API (I think introduced in 2015 or 16).
You can review documentation about this resource here:  https://developer.salesforce.com/docs/atlas.en-us.api_rest.meta/api_rest/resources_limits.htm

A: Salesforce REST API offers a Limits REST Endpoint which provides the ability to retrieve the org-wide API consumption. This is available in API version 29.0 and later.
The sample REST endpoint for retrieving your org API consumption is as below
https://yourInstance.salesforce.com/services/data/v40.0/limits

Additionally, refer my blog on Stalking Your Salesforce Governor Limits Was Never This Easy to understand more about the request and response format to retrieve your org limit consumption.
In addition to providing details of API limit consumption it also provides details around the following limits

*

*Daily asynchronous Apex method executions (batch Apex, future    methods, queueable Apex, and scheduled Apex)

*Daily Bulk API calls

*Daily Streaming API events (API version 36.0 and earlier)

*Daily durable Streaming API events (API version 37.0 and later)

*Streaming API concurrent clients (API version 36.0 and earlier)

*Durable Streaming API concurrent clients (API version 37.0 and later)

*Daily generic streaming events (API version 36.0 and earlier)

*Daily durable generic streaming events (API version 37.0 and later)

*Daily number of mass emails that are sent to external email addresses    by using Apex or APIs

*Daily number of single emails that are sent to external email addresses by using Apex or APIs

*Concurrent REST API requests for results of asynchronous report runs

*Concurrent synchronous report runs via REST API

*Hourly asynchronous report runs via REST API

*Hourly synchronous report runs via REST API

*Hourly dashboard refreshes via REST API

*Hourly REST API requests for dashboard results

*Hourly dashboard status requests via REST API

*Daily workflow emails

*Hourly workflow time triggers

*Hourly OData callouts

*Daily and active scratch org counts


text:
Q: App crashes after clicking on setting before the content is loaded My app crashes or goes back to home screen when someone click twice on settings in exo player, pressing it once shows " Please wait for the content to load " toast but pressing it twice crashes the app, although after the content is loaded the app doesn't crash, you can click on it as many times as you want. how do I solve it?
ImageView img_audio = findViewById(R.id.img_audio);
    img_audio.setOnClickListener(view -> {
        if (contentLoaded) {
            MappingTrackSelector.MappedTrackInfo mappedTrackInfo;
            DefaultTrackSelector.Parameters parameters = trackSelector.getParameters();
            TrackSelectionDialog trackSelectionDialog =
                    TrackSelectionDialog.createForTrackSelector(
                            trackSelector,
                            /* onDismissListener= */ dismissedDialog -> {
                            });
            trackSelectionDialog.show(getSupportFragmentManager(), null);
        } else {
            Toast.makeText(DetailsActivity.this, R.string.please_wait, Toast.LENGTH_LONG).show();
        }

        // Active playback.
        contentLoaded = true;
      });

A: Probably from setting the condition to true, on the first click.
Then on the second click, it tries to access the content, which is not loaded.
Or why is the content for sure loaded, when the event was fired once?
// Active playback.
contentLoaded = true;


text:
Q: JTextArea not wrapping when parent shrinks I am creating a Java Swing application that displays a chat log of messages. The frame holds only a JScrollPane which has a VerticalLayout, and in it are an indefinite number of JTextAreas, one for each message. The JTextAreas are uneditable, and the only reason I'm using them instead of a JLabel is because I need to wrap the text.
As a test, I create my frame and add two messages.

This is working as intended, the components form a continuous page of text and wrap around the frame.
I then increase the size of the frame.

This is still working as intended, the JScrollPane and JTextAreas have expanded and the text has rewrapped itself.
I then shrink the window back to a smaller size.

This is not working as intended. The JScrollPane stays at its largest size and the words do not wrap. How can I make it so that when the frame is shrunk width-wise, the JScrollPane and JTextAreas are shrunk as well?
Things I have already tried:

*

*Instantiating the JScrollPane with JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER

*Giving each JTextArea a BoxLayout or BorderLayout

*Wrapping each JTextArea in a JPanel and giving the panel a BoxLayout or BorderLayout

*Revalidating/redrawing the JScrollPane upon resizing events

*Calling setSize(Dimension d) of JScrollPane with getSize() of JFrame upon resizing events

EDIT: A minimum verifiable example, that produces the same effect as the described above
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;

import org.jfree.ui.tabbedui.VerticalLayout;

public class MessagingFrame extends JFrame {

    private JPanel textPanel;

    public MessagingFrame() {
        // Create display area
        textPanel = new JPanel();
        textPanel.setLayout(new VerticalLayout());
        // Wrap text panel in scroll pane
        JScrollPane scrollPane = new JScrollPane(textPanel);
        // Add scroll pane
        add(scrollPane);
        // Size center and display
        setSize(500, 500);
        setLocationRelativeTo(null);
        setVisible(true);
    }

    public void addMessage(String message) {
        JTextArea textArea = new JTextArea(message);
        textArea.setEditable(false);
        textArea.setLineWrap(true);
        textArea.setWrapStyleWord(true);
        textPanel.add(textArea);
        textPanel.updateUI();
    }

    public static void main(String[] args) {
        MessagingFrame frame = new MessagingFrame();
        frame.addMessage("According to all known laws of aviation, there is no way a bee should be able to fly. Its wings are too small to get its fat little body off the ground. The bee, of course, flies anyway because bees don't care what humans think is impossible.");
        frame.addMessage("We begin on Christmas Eve with me, Mark, and my roommate, Roger. We live in an industrial loft on the corner of 11th street and Avenue B, the top floor of what was once a music publishing factory. Old rock 'n' roll posters hang on the walls. They have Roger's picture advertising gigs at CBGB's and the Pyramid Club. We have an illegal wood burning stove; its exhaust pipe crawls up to a skylight. All of our electrical appliances are plugged into one thick extension cord which snakes its way out a window. Outside, a small tent city has sprung up in the lot next to our building. Inside, we are freezing because we have no heat.");
    }

}

Thank you!

A: You need to implement the Scrollable interface on the panel you add to the scroll panel so that the getScrollableTracksViewportWidth() method returns true.
This will force the component in the viewport to always be the same size as the viewport, not the width of the components added to the viewport.
When you implement the interface you will need to implement all the methods of the interface.
Or a simple solution is to use the Scrollable Panel which implements the interface for you and you just set the properties you want.
So the basic code would be:
ScrollablePanel panel = new ScrollablePanel( new VerticalLayout());
panel.setScrollableWidth( ScrollablePanel.ScrollableSizeHint.FIT );
panel.add(...);
JScrollPane scrollPane = new JScrollPane( panel );

Wrapping each JTextArea in a JPanel and giving the panel a BoxLayout or BorderLayout

You should be able to just add the text area directly to the panel. It appears the VerticalLayout makes each component as wide as possible.

textPanel.updateUI();

Don't use updateUI() that is for a LAF change. When you add/remove components from a visible GUI the basic code is:
panel.add();
panel.revalidate();
panel.repaint();


text:
Q: Combine values of inner object using JavaScript or Underscore I have an array as follows:
const arr = [{
  name: 'XYZ',
  values: [1, 2, 3]
}, {
  name: 'ABC',
  values: [5]
}, {
  name: 'XYZ',
  values: [4, 5, 6]
}, {
  name: 'ABC',
  values: [8, 9]
}];

I'm using underscore js and trying to transform as follows:
const result = [{
  name: 'XYZ',
  values: [1, 2, 3, 4, 5, 6]
}, {
  name: 'ABC',
  values: [5, 8, 9]
}]

I was able to group by name and trying to loop in, but not sure how do I merge values. So far this is what I've done:
_.chain(arr)
  .groupBy((item) => item.name)
  // I don't know what to do here
  .value();

A: With ES6, you can use Array#reduce with a Map to get the desired result:

const arr = [{"name":"XYZ","values":[1,2,3]},{"name":"ABC","values":[5]},{"name":"XYZ","values":[4,5,6]},{"name":"ABC","values":[8,9]}];

const result = [...arr.reduce((m, { name, values }) => {
  const el = m.get(name) || { name, values: [] }; // get the result object from the map or create a new one

  el.values.push(...values); // push the current values to the result object values property

  return m.set(name, el); // add the result object to the map, and return the map
}, new Map()).values()]; // get the map values, and spread to an array

console.log(result);

Using underscore:

const arr = [{"name":"XYZ","values":[1,2,3]},{"name":"ABC","values":[5]},{"name":"XYZ","values":[4,5,6]},{"name":"ABC","values":[8,9]}];

const result = _.chain(arr)
  .groupBy('name') // group by name
  .mapObject((group, name) => ({ // map each group to a new object
    name,
    values: _.flatten(_.pluck(group, 'values')) // get all values arrays, and flatten to a single array
  }))
  .values() // convert the groups object to an array
  .value();

console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>

A: Maybe, you can try vanilla Javascript way.
var result = [];
arr.forEach((item) => {
    let currObj = result.find((item2) => item2.name === item.name);
    if(currObj){
      currObj.values = currObj.values.concat(item.values);
    } else {
      result.push(JSON.parse(JSON.stringify(item)));
    }
})


text:
Q: Angularjs SPA detail page refresh I am working on SPA application using Angularjs, all navigation within the app works fine, but when I try refresh detail page (examle: www.domain.com/traveldetail/123), it brakes the page.
app.js
travelApp.config(['$stateProvider', '$urlRouterProvider', '$locationProvider', function ($stateProvider, $urlRouterProvider, $locationProvider) {
    $locationProvider.html5Mode(true);
    $urlRouterProvider.otherwise("travellist");
    $stateProvider
      .state('/', {
          url: '/',
          templateUrl: 'Partials/travellist.html',
          controller: 'TravelListController'
      })
      .state('travellist', {
          url: '/travellist',
          templateUrl: 'Partials/travellist.html',
          controller: 'TravelListController'
      })
      .state('traveldetail', {
          url: '/traveldetail/:travelId',
          templateUrl: 'Partials/traveldetail.html',
          controller: 'TravelDetailController'
      })
}])

Web.config
    <rewrite>
      <rules>
        <rule name="TravelList" stopProcessing="true">
          <match url="^travellist" />
          <action type="Rewrite" url="/" />
        </rule>
        <rule name="TravelDetail" stopProcessing="true">
          <match url="^traveldetail" />
          <action type="Rewrite" url="/" />
        </rule>
      </rules>
    </rewrite>

WeApiConfig.cs
public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        // Web API configuration and services
        config.Formatters.JsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
        // Web API routes
        config.MapHttpAttributeRoutes();

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

A: Here the state should be parent and child, for ex
travelApp.config(['$stateProvider', '$urlRouterProvider', '$locationProvider', function ($stateProvider, $urlRouterProvider, $locationProvider) {
$locationProvider.html5Mode(true);
$urlRouterProvider.otherwise("travellist");
$stateProvider
  .state('travel', {
      url: '/',
      templateUrl: 'Partials/travellist.html',
      controller: 'TravelListController'
  })
  .state('travel.list', {
      url: '/travellist',
      templateUrl: 'Partials/travellist.html',
      controller: 'TravelListController'
  })
  .state('travel.list.detail', {
      url: '/traveldetail/:travelId',
      templateUrl: 'Partials/traveldetail.html',
      controller: 'TravelDetailController'
  })

}])
you can refer to ui router


text:
Q: Returns only one data AJAX Here's what i'm doing. Im trying to return a data through my database and i want the data to display in an organized manner. I need to distribute the data in different html tables based on what year or semester the data is. If you know about curriculum it's like that.
here's my algorithm. first i initialize a variable outside the while loop which is $a, if semester = 1st and year = 1 then it will go through another if which is checking if $a = 1 if it's equals it will create a div that contains part of the html tables then it will print out the data fetched from the database in td after that it will check again if $a = 1 then it will create the last part of the html tables.
To summarize. I want to distribute the data based on what semester and year the data is. But the problem is only one data is shown i have two data which equals to 1st semester and year 1.
Data

    $a = 1;
    while($row = mysqli_fetch_array($result))
    {
        if($row['semester'] == '1st' && $row['year'] == 1){

           /*This if condition below is set to initiliaze the table headers only once*/

            if($a == 1){
                $output .='

                                  Subject Code
                                  Subject Title
                                  Units
                                  Pre-req
                                  Co-req

';
              }

                $output .= '

                         '.$row['code'].'
                         '.$row['title'].'
                         '.$row['unit'].'
                         '.$row['prereq'].'
                         '.$row['corequisite'].'

';

   /*This if condition below is set to initiliaze the table headers only once*/

              if($a == 1){
                $output .= '

                          </div';
                $a = 2;
              }

        }

    }
   echo $output;

A: Your problem is, that you close the table already in your first run loop, but it only should be closed at the end of the loop, and only if you opened the table at all.
It's easier to get the logic right if you use boolean variables and give them names that mean something.
$hasFoundAtLeastOneRow = false;
$firstRow = true;
$output = ''; // if you haven't above, you need to initialize that string before you can do a '.='
while($row = mysqli_fetch_array($result))
{
    if($row['semester'] == '1st' && $row['year'] == 1){

       /*This if condition below is set to initiliaze the table headers only once*/

          if($firstRow){
              $output .='

                              Subject Code
                              Subject Title
                              Units
                              Pre-req
                              Co-req

';
          }

          $output .= '

                    '.$row['code'].'
                    '.$row['title'].'
                    '.$row['unit'].'
                    '.$row['prereq'].'
                    '.$row['corequisite'].'

';
        $hasFoundAtLeastOneRow = true;   // we have at least one entry in our table
        $firstRow = false;  // set this to false, since we just worked the first row
    }

}

if($hasFoundAtLeastOneRow) {
    $output .= '

            </div';
} else {
    // optional
    $output = "nothing found";
}
echo $output;

A: the reason you get only one result is because you didn't increment the value of a $a = 1; instead of using $a=2; increment it because it skips a result and also place ending tag outside the loop
while($row = mysqli_fetch_array($result))
    {
        if($row['semester'] == '1st' && $row['year'] == 1){

           /*This if condition below is set to initiliaze the table headers only once*/

            if($a == 1){
                $output .='

                                  Subject Code
                                  Subject Title
                                  Units
                                  Pre-req
                                  Co-req

';
              }

                $output .= '

                         '.$row['code'].'
                         '.$row['title'].'
                         '.$row['unit'].'
                         '.$row['prereq'].'
                         '.$row['corequisite'].'

';

   /*This if condition below is set to initiliaze the table headers only once*/

        }
      $a++;
    }
  $output .= '

</div';

   echo $output;

A:

              Subject Code
              Subject Title
              Units
              Pre-req
              Co-req

<?php
    while($row = mysqli_fetch_array($result))
    {
        if($row['semester'] == '1st' && $row['year'] == 1)
        {
?>

                <?=$row['code']?>
                <?=$row['title']?>
                <?=$row['unit']?>
                <?=$row['prereq']?>
                <?=$row['corequisite']?>

<?php
        }
    }
?>


text:
Q: Number of ways of forming subsets satisfying the given condition below Consider a set $S$ of total elements being $"N"$ , we are taking two random subsets from the set S , called them $P$ and $Q$ .       Totals ways of choosing those subsets such that we have

*

*A) n($P$ $\cup$ $Q$) = $d$ where $d \in [1,N]$.

*B) n($P$ $\cap$ $Q$) = b where $b \in [1,N]$ .

For A part what i considered was taking case of having no element common , then 1 element common etc till all elements common but for that i need the second part answer as b varies . But i am stuck on how to get the required Ways For B part.

A: To solve this problem we can split it in two, first getting d elements from S and then splitting this elements in $3$, the ones belonging to $P,Q$ and $P \cap Q$, with $|P \cap Q| = b$.
The number of ways of choosing d elements from a set of cardinal $N$ is ${N \choose d}$. The number of ways to split d elements in $3$ disjoint sets such that $|P \cap Q| = b$ is ${d \choose b} \cdot 2^{d-b}$, since for each element that doesn't belong to $P \cap Q$ we have $2$ options.
Therefore we have that we can choose sets $P$ and $Q$ that satisfy both $A$ and $B$ in ${N \choose d} \cdot {d \choose b} \cdot 2^{d-b}$ different ways.


text:
Q: Перенос на новую строку Имеется такой вот код:

'.$row["top_sales"].'

'.$row["top_sales"].'

'.$row["under_order"].'

'.$row["novelty"].'

'.$row["title"].'

        Regular price
        '.group_numerals($row["price"]).' грн

Отображается вот так, видно что слово "Новинка" налезла сверху на другую этикетку.

Необходимо чтобы последующие этикетки если есть то чтобы они были с новой строки, как не пытался сделать, не получается, всегда съезжают этикетки вместе с фоткой кофты...
Стили этикеток прикрепляю:

.plus1{border:1px solid #0095EB;background-color:rgba(255, 255, 255, 0.8);color:#0095EB;
 z-index:3;border-radius:3px;padding:0px 4px 2px 4px;position:absolute;margin-left:35px;margin-top:-25px;font-size:12px;float:left;}

.plus2{border:1px solid #0095EB;background-color:rgba(255, 255, 255, 0.8);color:#0095EB;
 z-index:3;border-radius:3px;padding:0px 4px 2px 4px;position:absolute;margin-left:35px;margin-top:-25px;font-size:12px;float:left;}

.plus3{border:1px solid #0095EB;background-color:rgba(255, 255, 255, 0.8);color:#0095EB;
 z-index:3;border-radius:3px;padding:0px 4px 2px 4px;position:absolute;margin-left:35px;margin-top:-25px;font-size:12px;float:left;}

Пример как должно быть:

A: Не вижу в коде чтобы использовались классы стилей добавленные ниже. У вас все стили используют абсолютное позиционирование, соответственно этикетки у вас группируются в одной точке. Попробуйте создать какой-нибудь контейнер для этикеток с абсолютным позиционированием. Вместо того, чтобы указывать его для каждой этикетки.
Вот пример с контейнером:

'.$row["top_sales"].'

'.$row["top_sales"].'

      ...

И затем добавить стиль

.labels-wrapper {
  position: absolute;
}

А из классов .plus1, .plus2, .plus3 убрать position: absolute.


text:
Q: Two ways to select ranges in SQL, only one in MongoDB? I have the following SELECT statement for SQL.
SELECT TransAmount FROM STOCK WHERE TransAmount between 100 and 110;

However, this statement generates an error from querymongo.com. It says "Failure parsing MySQL query: Unable to parse WHERE clause due to unrecognized operator ". I assume it is talking about the between clause.
Correct me if I'm wrong, but does this SQL statement do the exact same thing as the one above?
SELECT TransAmount FROM STOCK WHERE TransAmount > 100 and TransAmount < 110;

This statement generates the following MongoDB code.
db.STOCK.find({
    "TransAmount": {
        "$gt": 100,
        "$lt": 110
    }
}, {
    "TransAmount": 1
});

It looks like MongoDB doesn't have a 'between' operator. Does MongoDB handle selection within ranges with a different keyword, or do you have to set it up like so $gt/%lt?

A: Between is just a shortcut (a sort of symlink) to your second query, I guess it makes life easier.
MongoDB has not yet implemented such a shortcut, I have looked around a bit for a JIRA declaring someone wants such an operator however, no luck.
The one and only way of doing ranges in MongoDB is to use $gt and $lt (you could count $in etc but that is a different kind of range, not what your looking for).


text:
Q: Partial differentiation of a integral If I have:
$$f(x,y)=\int_{x}^{y}e^{-t^2}dt$$
To calculate that, I change the t to y and x to get:
$$e^{-y^2}(e^{-y^2})'-e^{-x^2}(e^{-x^2})$$
With the differentials being in respect to x and y for each partial derivative?

A: We have: $\displaystyle \int_{x}^y = \displaystyle \int_{0}^y - \displaystyle \int_{0}^x \Rightarrow f_x = -e^{-x^2}, f_y = e^{-y^2}$.

A: Let $F$ be antiderivative of $g(t)=e^{-t^2}$(F'(t)=g(t)), then by Fundamental Theorem of Calculus:
$$f(x,y)=\int_{y}^{x}e^{-t^2}dt=F(x)-F(y)$$
So
$$\frac{\partial f}{\partial x}(x,y)=F'(x)=e^{-x^2}$$
The same with second partial derivative.


text:
Q: Selecting  Descendant using CSS How come all the result have the default Black color? Non of the rules were accepted! Is this because
 is not allowed to have descendants? Where would such rule be listed? Thanks.
Example
HTML

...some text...

 nested p

           nested span 1

     nested span 2

CSS
p>p {color:red;}
p>span {color:yellow;}
p p {color:green;}
p span {color:blue;}

A:
Is this because
 is not allowed to have descendants

No, it is because
 is not allowed to have descendants that are
 elements (among others).

Where would such rule be listed?

In the HTML specification (under "Content Model").
You may find that it useful to test your code with a markup validator.


text:
Q: relation "table" does not exist i created the following schema , inside that schema i created a table and inserted a some values.
After that i created a function that get a value in the table based on an ID.
Here is all the declarations :
CREATE SCHEMA pckg_50d_facture;
CREATE TABLE pckg_50d_facture.valeur(val_id text PRIMARY KEY, val text);

CREATE OR REPLACE FUNCTION pckg_50d_facture.const(id text) RETURNS text AS $body$
DECLARE
result text;
BEGIN
  --EXECUTE 'SELECT val FROM pckg_50d_facture.valeur WHERE val_id = id' INTO result USING checked_user, checked_date;

    SELECT val INTO result FROM pckg_50d_facture.valeur WHERE val_id = id;

 return result;
END;
$body$
LANGUAGE PLPGSQL
;

But when i call the function const i get the following error :
ERROR:  relation "valeur" does not exist
I tried to Grant some rights as follow :
GRANT USAGE ON SCHEMA pckg_50d_facture TO PUBLIC;
GRANT SELECT ON ALL TABLES IN SCHEMA pckg_50D_facture TO PUBLIC;

but still not working.

A: The error message is unrelated to privileges. The table valeur simply cannot be found. There must be some kind of confusion. My educated guess:
You call the function without schema qualification and accidentally execute a different function of the same name, because pckg_50d_facture is not in the search_path (or is there but in a later position). See:

*

*How does the search_path influence identifier resolution and the "current schema"
Or you connected to the wrong database / database cluster by mistake.


text:
Q: How to group factors with low frequence into an 'other' factor in R # Generate counts table
library(plyr)
example <- data.frame(count(diamonds,c('color', 'cut')))
example[1:3,]

# Excerpt of table
       color  cut   freq
1      D      Fair  163
2      D      Good  662
3      D Very Good 1513

You can easily filter the table for freq > 1000 with: example[example$freq > 1000,].  I would like to generate a table similar to this except where all the values which are less than a value e.g. 1000 are included in a row (Other) similar to what happens when you have too many factors and call summary(example, maxsum=3).
     color         cut          freq
 D      : 5   Fair   : 7   Min.   : 119
 E      : 5   Good   : 7   1st Qu.: 592
 (Other):25   (Other):21   Median :1204
                           Mean   :1541
                           3rd Qu.:2334
                           Max.   :4884

Example ideal output:
Ideally I want to convert this  example[example$color=='J',]:
 color   cut freq
 J      Fair  119
 J      Good  307
 J Very Good  678
 J   Premium  808
 J     Ideal  896

and produce this:
 color       cut freq
     J Very Good  678
     J   Premium  808
     J     Ideal  896
     J   (Other)  426

Bonus:
If this kind of filtering is possible with ggplot to create a plot like below, but with this filtering, that would be great also.
ggplot(example, aes(x=color, y=freq)) + geom_bar(aes(fill=cut), stat = "identity")

A: Here is an alternative using dplyr to pipe the correct data directly into the ggplot call.
library(dplyr)
example %>% mutate(cut = ifelse(freq < 500, "Other", levels(cut))) %>%
  group_by(color, cut) %>%
  summarise(freq = sum(freq)) %>%
  ggplot(aes(color, freq, fill = cut)) +
  geom_bar(stat = "identity")

Be sure to detach plyr, otherwise the output will be incorrect from the dplyr call.

A: Try this:
library(plyr)
library(ggplot2)
example <- data.frame(count(diamonds,c('color', 'cut')))

# Compute the row id where frequency is lower than some threshold
idx <- example$freq < 1000

# Create a helper function that adds the level "Other" to a vector
add_other_level <- function(x){
  levels(x) <- c(levels(x), "Other")
  x
}

# Change the factor leves for the threshold id rows
example <- within(example,
       {
         color <- add_other_level(color)
         color[idx] <- "Other"
         cut <- add_other_level(cut)
         cut[idx]    <- "Other"
       }
)

# Create a plot
ggplot(example, aes(x = color, y = freq, fill = cut)) +
  geom_bar(stat = "identity")


text:
Q: Intuitive meaning of a totally bounded set By definition, a totally bounded set is always covered by some finite collection of equal-sized open balls. Is it possible to obtain an intuitive meaning from this definition? Thanks in advance.

A: Such cover should exist for any size. Look at the following interpretation (in a metric space). Choose arbitrarily $\varepsilon>0$. There exist $x_1,\dots,x_n$ - the centers of the balls of our cover. Let $y$ be any element of our set. Then $y$ lies in some ball which means that $y$ lies $\varepsilon$-close to some $x_i$. This is, in fact, an $\varepsilon$-net.


text:
Q: Cast to ObjectId failed for value "ULID_ID" at path "docA" I am trying to get ULID working with mongoose.
My DocTypeA schema looks like this:
const mongoose = require('mongoose')
const Schema = mongoose.Schema
const ULID = require('ulid')

const schema = new Schema({
  _id: { type: Schema.Types.String, default: () => ULID.ulid(Date.now()) },
  name: { type: Schema.Types.String },
})

schema.set('toJSON', {
  virtuals: true,
  versionKey: false,
  transform: function (doc, ret) {
    // remove these props when object is serialized
    delete ret._id
  },
})

module.exports = mongoose.model('DocTypeA', schema)

My DocTypeB schema looks like this:
const mongoose = require('mongoose')
const Schema = mongoose.Schema
const ULID = require('ulid')

const schema = new Schema({
  _id: { type: Schema.Types.String, default: () => ULID.ulid(Date.now()) },
  name: { type: Schema.Types.String },
  docA: { type: Schema.Types.ObjectId, ref: 'DocTypeA' },
})

schema.set('toJSON', {
  virtuals: true,
  versionKey: false,
  transform: function (doc, ret) {
    // remove these props when object is serialized
    delete ret._id
  },
})

module.exports = mongoose.model('DocTypeB', schema)

I am able to create documents for DocTypeA and ULID generated stuff is saved as _id in DocTypeA documents.
But when I try to reference a DocTypeA document id while creating an DocTypeB document, I get the cast error (mentioned in the title).
Here is the code for creating a DocTypeA:
const create = async (payload) => {
  const docA = new DocTypeA(payload)
  await docA.save()
  return docA
}

For creating an DocTypeB, I am using:
const create = async (payload) => {
  const docB = new DocTypeB(payload)
  await docB.save()
  return docB
}

A: ULID are not qualified ObjectId.
They are not hexadecimal strings and are 26-char length identifiers.
Given the way schema for DocTypeB is declared, docA field should be of String type and not ObjectId.
Your schema definition for DocTypeB should be as follows.
const schema = new Schema({
  _id: { type: Schema.Types.String, default: () => ULID.ulid(Date.now()) },
  name: { type: Schema.Types.String },
  docA: { type: Schema.Types.String, ref: 'DocTypeA' },
});

Otherwise, Mongoose will try casting the identifier as ObjectId and that will throw.
async function create() {
  const docA = new DocTypeA({name: 'Jack'})
  await docA.save()

  const docB = new DocTypeB(
    {name: 'Jill', docA} // Or {name: 'Jill', docA: docA._id})
  )
  await docB.save();
}

create().then(console.log('done')).catch(console.error)

Note that, a unique index is automatically added for _id field in the collection so you must be careful not set the same value for it in different documents.


text:
Q: Remove items from list sequentially based on variable index def FitnessSelection(population, relative_fitness):
    selected_chromosomes = []
    selected1 = random.choices(population, weights = relative_fitness, k = 1)
    ind1 = selected1[0][1][0]
    del relative_fitness[ind1]
    del population[ind1]
    selected2 = random.choices(population, weights = relative_fitness, k = 1)
    ind2 = selected2[0][1][0]
    del relative_fitness[ind2]
    del population[ind1]
    selected = selected1, selected2
    selected_chromosomes = [i[0] for i in selected]
    return (selected_chromosomes)

I am trying to perform a random weighted selection from a list, however, I cant have the same item selected twice, therefore I am trying to exclude the selected items immediately after selection so it won't be in the population in the list for the next run of the function.
The problem is that the program is running but I don't think the items are being excluded
I have the items in the following structure
population=[[[0, 0, 1, 0, 1, 1, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1], [4], [0]],
[[0, 0, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 1], [3], [1]],
[[0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 1, 0, 0, 1, 0, 0], [4], [2]],
[[1, 0, 0, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0], [1], [3]]]

Where the last brackets of each string is an index counter. I am trying to isolate the counter and exclude the item in the same position, but when I check the population afterward, they were not excluded.
Does anyone know what could be wrong with this approach?
p.s. - I'm sorry for not posting a standalone program, I couldn't make it work in a small sample like this.
Thanks!


text:
Q: IO Exception Stream Closed using PDFMergerUtility collect the inputstream (pdf's) and merge into an single pdf document by using PDFMergerUtility, below are my code (servlet with glassfish server)
static HttpsURLConnection connectionGet;
static List<InputStream> sources = new ArrayList<>();
Integer totalPageCount = Integer.parseInt(pageCountValue);
try {
    for (int i = 1; i <= totalPageCount; i++) {
        String inputValue = countryCode + "/" + kindCode;
        String pdfUrl = "abc.org/rest-services/published-data/images/" + inputValue + "/fullimage.pdf?Range=" + i;
        URL pdfDownload = new URL(pdfUrl);
        connectionGet = (HttpsURLConnection) pdfDownload.openConnection();
        String authorizationHeader1 = "Bearer " + getToken;
        connectionGet.setRequestProperty("Authorization", authorizationHeader1);
        connectionGet.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        connectionGet.setRequestMethod("GET");
        int pageResponseCode = connectionGet.getResponseCode();
        if (pageResponseCode != 404) {
            sources.add(connectionGet.getInputStream());
        }
    }
    PDFMergerUtility pdfMerger = new PDFMergerUtility();
    pdfMerger.addSources(sources);
    String pdfFileName = countryCode+kindCode+".pdf";
    String contextPath = request.getServletContext().getRealPath("/");
    pdfMerger.setDestinationFileName(contextPath+pdfFileName);
    try {
        pdfMerger.mergeDocuments();
    } catch (COSVisitorException ex) {
       Logger.getLogger(PDFDownloadResult.class.getName()).log(Level.SEVERE, null, ex);
    }
    out.println("Document Downloaded Successfully in below server Path" + "
" +contextPath + pdfFileName+ "");
    } catch (IOException e) {
        } finally {
                // cleanup
                    sources.stream().forEach((source) -> {
                    IOUtils.closeQuietly(source);
                });
        }
    connectionGet.disconnect();

Everything works as expected. However when executed a second time I get the following error: Stream closed
Severe:   java.io.IOException: stream is closed
    at sun.net.www.protocol.http.HttpURLConnection$HttpInputStream.ensureOpen(HttpURLConnection.java:3295)
    at sun.net.www.protocol.http.HttpURLConnection$HttpInputStream.read(HttpURLConnection.java:3320)
    at java.io.BufferedInputStream.fill(BufferedInputStream.java:246)
    at java.io.BufferedInputStream.read(BufferedInputStream.java:265)
    at java.io.FilterInputStream.read(FilterInputStream.java:83)
    at java.io.PushbackInputStream.read(PushbackInputStream.java:139)
    at org.apache.pdfbox.io.PushBackInputStream.read(PushBackInputStream.java:90)
    at org.apache.pdfbox.io.PushBackInputStream.peek(PushBackInputStream.java:68)
    at org.apache.pdfbox.io.PushBackInputStream.isEOF(PushBackInputStream.java:156)
    at org.apache.pdfbox.pdfparser.BaseParser.readLine(BaseParser.java:1517)
    at org.apache.pdfbox.pdfparser.PDFParser.parseHeader(PDFParser.java:360)
    at org.apache.pdfbox.pdfparser.PDFParser.parse(PDFParser.java:186)
    at org.apache.pdfbox.pdmodel.PDDocument.load(PDDocument.java:1235)
    at org.apache.pdfbox.pdmodel.PDDocument.load(PDDocument.java:1202)
    at org.apache.pdfbox.util.PDFMergerUtility.mergeDocuments(PDFMergerUtility.java:235)
    at org.apache.pdfbox.util.PDFMergerUtility.mergeDocuments(PDFMergerUtility.java:192)

Edited: the Problem is IOUtils.closeQuietly(source); source value not cleared propelry
Example : exexuted in first time (after deploy) the count will be 2(sources list)  so the document generated without any issues
then i try to run second time , assume current total page count is 3 , now the sources count becomes 5 , this is wrong
so please help me how can clear the sources list after the document created

A: You need to clear the list after each iteration add this line in your final block,
sources.clear(); Hope this helps
.


text:
Q: "A copy of Firefox is already open. Only one copy of Firefox can be open at a time." I cannot start Firefox on my Mac. It just says "A copy of Firefox is already open. Only one copy of Firefox can be open at a time." I have tried restarting the computer. Any fixes?

You have suggested deleting the lock files in my profile, but, I don't have a profile. I was trying to fix the problem in question Firefox on Mac: Slow, slow, slow by deleting my profile, so I deleted it, and this came up. So I cannot delete the lock files because they don't exist.

A: To remove .parentlock files you can run the following command in the Terminal:
rm -f ~/Library/Application\ Support/Firefox/.parentlock

(It's not in your profile)
However as said before, removing a .parentlock file won't help fix a stuck Firefox process.

A: This kills all Firefox processes on Linux:
pgrep firefox | xargs kill -9

A: Firefox writes two lockfiles, if they are not deleted during shutdown you have to remove them manually. They are called lock and .parentlock and located in the profile folder.
MozillaZine has an article on how to do that on the Mac.
EDIT:
On OS X only .parentlock exists, so it should be enough if you delete that file.
The file will have 0 KB size, so you can delete it with no worry.

A: Somehow the Firefox process is still running even after you close the program.
First, right click on the Firefox icon and try clicking Force Quit.
If that option is not there, press Option + Apple + Esc. This will bring up a list of running programs. Select Firefox and press Force Quit
If all else fails, type killall -9 firefox into the terminal. This should force the process to close, allowing you to start Firefox again.

A: I had this issue on OS X v10.7 (Lion). Nothing showed with ps ax | grep firefox and deleting the lock files did nothing for me either. What did work however was launching Firefox via terminal with the profile manager and selecting a suitable profile:
/Applications/Firefox.app/Contents/MacOS/firefox -ProfileManager

It seems as if my default profile which Firefox was trying to open had been deleted. After selecting a different profile via the profile manager menu I was back up and running.

A: There is a command that combines the pgrep with kill, it's pkill. So:
pkill firefox

A: I always label an old Firefox application as, say FireFox 3.6.17 in the applications folder prior to installing the newer version of Firefox.  After that, I install the newer version and rename that application as, say FireFox 12.0.1.
That way, when you see the dialog box saying that another instance of Firefox is already open, pull up the Mac Dock at the bottom of your screen, and you'll see a second Firefox icon in the dock where there wasn't one before.  Right-click on the older icon (if you hover the mouse over the icon, you'll see either "Firefox 3.6.17" or the newer one) and go through Options and deselect "Open at Login."  Then force-quit the older application, and that icon will go away.  Gone.  Somehow, when you "threw" or removed the older icon from the dock after upgrading, it didn't change the login status of that icon and kept trying to run both versions of Firefox at login.  Problem solved.
When you upgrade and label accordingly, ALWAYS turn off the Login status of the older icon before removing that icon and replacing it with the new one.

A: I solved the problem quickly by doing the following:

*

*Open the Activity Monitor App

*Then enter "Firefox" into the search field.

*Although Firefox was closed, it appeared in the Activity Monitor

*Select Firefox and force quit by clicking the cross symbol in the upper left corner.

After that I was abled to open Firefox again, without doing anything else.

A: If Firefox sees an active instance of itself when it starts, it skips creating another instance of itself with this error.
What do you mean by the statement, "I tried restarting"? Did you reboot and this still persists?
I am not familiar with OS X enough to comment further on its behavior.

A: On OS X, if deleting the .parentlock or killing the process does not work, you may need to edit/delete the profiles.ini file. I encountered the problem while making multiple Firefox profiles and resolved the issue be deleting all but the default profile from the profiles.ini (not the profile dir). I think the cause in my case was the use_last_profile setting was enabled and the last used profile no longer existed (profile dir deleted).

A: The lazy way to delete these lock files:
find ~/Library/Application\ Support/Firefox -name "*lock*" -exec rm {} \;

This will find and delete any file with "lock" in the name.  See the man page for find for more information.


text:
Q: Which Variables in these Questions are Free and Bound? Simplify the following statements. Which variables are free and which are
bound? If the statement has no free variables, say whether it is true or
false.
(a) w ∈ {x ∈ R | 13 − 2x > c}.
(b) 4 ∈ {x ∈ R | 13 − 2x ∈ {y | y is a prime number}}. (It might make
this statement easier to read if we let P = {y | y is a prime number};
using this notation, we could rewrite the statement as 4 ∈ {x ∈ R |
13 − 2x ∈ P}.)
(c) 4 ∈ {x ∈{y | y is a prime number} |13 − 2x > 1}. , {y | y is a prime number} = P
Solutions:
(a) (w ∈ R) ∧ (13 − 2(4) > c) x us bound, c,w are free variablses
(b) (4 ∈ R) ∧  (13 − 2(4) ∈ P) bound variables x, y, no free variables TRUE
(4 ∈ R) ∧ (4 ¬∈ P) ∧ (13 − 2(4) > 1) bound variables x, y, no free varaibles  FALSE

A: The solutions given in the post are correct.


text:
Q: Module not found in Nx project I'm building a monorepo with Nx. I'm a newbie to Nx monorepo.
I've created 5 libs and a single app. When I build the libs, everything works fine, and the libs are built successfully. But as I try to build the app, Nx first builds all the libs that the app depends upon. After that, upon building the app, it fails to find files of libs. I've been debugging the issue since two days. Even tried to recreate the whole thing from scratch, but stuck on same thing. The error stack is quite large, so I'm putting a repo link here.
https://github.com/mwaqar666/sca
The application works fine until this commit:
https://github.com/mwaqar666/sca/tree/f6670477f53c60b25fc46d2ce028c7be202c4ce3
After adding the application, and linking the libs with the application code at this commit:
https://github.com/mwaqar666/sca/tree/5f4b96033ace59e8e59b032b649c77d06c8c35ec
Example error
ERROR in ./libs/sca-command/src/commander/command-loader.ts 5:15-32
Module not found: Error: Can't resolve '~/base' in '/home/mwaqar666/code/sca/libs/sca-command/src/commander'
resolve '~/base' in '/home/mwaqar666/code/sca/libs/sca-command/src/commander'
  Parsed request is a module
  using description file: /home/mwaqar666/code/sca/libs/sca-command/package.json (relative path: ./src/commander)
    resolve as module
      /home/mwaqar666/code/sca/libs/sca-command/src/commander/node_modules doesn't exist or is not a directory
      /home/mwaqar666/code/sca/libs/sca-command/src/node_modules doesn't exist or is not a directory
      /home/mwaqar666/code/sca/libs/sca-command/node_modules doesn't exist or is not a directory
      /home/mwaqar666/code/sca/libs/node_modules doesn't exist or is not a directory
      looking for modules in /home/mwaqar666/code/sca/node_modules
        /home/mwaqar666/code/sca/node_modules/~ doesn't exist
      /home/mwaqar666/code/node_modules doesn't exist or is not a directory
      /home/mwaqar666/node_modules doesn't exist or is not a directory
      /home/node_modules doesn't exist or is not a directory
      /node_modules doesn't exist or is not a directory
 @ ./libs/sca-command/src/commander/index.ts 6:21-48
 @ ./libs/sca-command/src/index.ts 4:21-43
 @ ./libs/sca-db/src/migrator/command-provider/migration.command-provider.ts 4:18-41
 @ ./libs/sca-db/src/migrator/command-provider/index.ts 4:21-60
 @ ./libs/sca-db/src/migrator/index.ts 4:21-50
 @ ./libs/sca-db/src/index.ts 7:21-42
 @ ./apps/sca-be/src/app-module/app.module.ts 9:13-31
 @ ./apps/sca-be/src/main.ts 5:21-55

This is one error from the whole list of stack errors


text:
Q: Multiple dispatchers in the action creators causing issues in unit test Following is my action creator with multiple dispatches
export function getAnalysisById(Id){
  let url = APIEndpoints["getAnalysisById"];
  var dataObject = {
    id: Id
  }
  return dispatch => {
    dispatch ({
                       type:LOADING_ANALYSIS,
                       payload : { isLoading : true}
           });
    const request = axios.post(url, dataObject);
    dispatch ({
                       type:GET_ANALYSIS_BY_ID,
                       payload: request
           });
  };
}

Now following is the testing code written for the above action
var  chai  = require('chai');

var expect = chai.expect;
const actions = require('../../src/actions/index');

import { applyMiddleware } from 'redux'
import thunk from 'redux-thunk'
import nock from 'nock'
import ReduxPromise from 'redux-promise'
const middlewares = [ thunk,ReduxPromise ]

import configureStore from 'redux-mock-store'

const mockStore = configureStore(middlewares)

describe("All actions WITH Asynchronous call",function description(){
  it('should return an action to get All Analysis by id', () => {
  const store = mockStore({})

 // Return the promise
  return store.dispatch(actions.getAnalysisById('costnomics_Actual vs Budjected'))
    .then(() => {
      // const actionss = store.getActions()
       console.log('store',store)

    })
})

});

Running the above test case produces the following error,
TypeError: Cannot read property 'then' of undefined
When I pass plain objects as return value for the action creators instead of dispatcher, everything is working fine. But when mulitple dispatchers are returned from the action creator, it gives me the above error?. Why is this happening?

A: Your thunk function isn't actually returning a promise.  You need to have something like return request at the end so that the promise is returned from the thunk, and from there returned from store.dispatch().


text:
Q: VBA macro crashing Excel 2010 I have an Excel 2010 spreadsheet that I use to maintain tests for an automated test application written with Selenium WebDriver. The spreadsheet has 6 ActiveX buttons that Upload (to a database), Import (from another sheet), Clear All Sheets, Export (to another sheet), Merge (two sheets), and Restore (a test suite from the database). My problem seem to stem from the macro that runs when the Import button is selected
The macro takes two sheets, source and destination, clears the destination sheet and copies the cells and data from the source workbook to the corresponding sheet in the destination workbook. From there, it can either be uploaded to the database or run from the sheet by the testing app
A couple weeks ago when selecting the Import button Excel crashed. I looked on the web and found a solution that worked. It involved disabling all macros, shutting down trust documents and trusted locations, recompiling, and reopening the workbook. This worked for a couple weeks until the same thing happened again this past weekend and the fix did not work anymore.
Here is the code I have:
numSheets = wrkBook.Sheets.Count

appName = wrkSheet.Cells(2, 3).Value

bkPath = Application.GetOpenFilename("Excel Macro-Enabled Workbook (*.xlsm),*.xlsm")

If bkPath <> "False" Then

    Call Clear_All(wrkBook, wrkSheet)

    'get the number of sheets in the source workbook
    destCnt = wrkBook.Sheets.Count

    Set importBook = Workbooks.Open(bkPath)
    For a = 1 To destCnt
        thsShtName = wrkBook.Worksheets(a).Name
        'activate the source workbook
        importBook.Activate

        'get the numer of sheets in the source workbook
        srcCnt = importBook.Sheets.Count

        'loop through each sheet checking title
        For b = 1 To srcCnt
            'get the name of the 'a' sheet
            **srcSheetName = importBook.Worksheets(b).Name**

            'do more stuff with the source sheet
        Next b
Next a
End If

The code is crashing on the following line
    srcSheetName = importBook.Worksheets(b).Name
Here are a few things that I have noticed. Once the importBook variable is set, I cannot expand the variable in a watch window even if the code has not reached the offending line. However, the macro will successfully get the srcCount (number of sheet on the source sheet). Once the macro gets to the offending line it crashes consistently with a message stating simply that Excel has encountered an error and needs to close . No information, Excel closes, and sometimes restarts to a blank workbook

A: OK...I figured this out myself after heeding Siddarth Rout's suggestion about a corrupt spreadsheet. I took the steps that I described above
So here's what I did.
I copied one of the other spreadsheets and cleared it.  As soon as I ran the Import macro, it passed through the line where it was failing before, so a corruption seems to have been the issue. I then stepped through the original code and rewrote the Import macro to simplify the code in it. It now seems to be working just fine
Thanks for the suggestions!!


text:
Q: Can it be shown that there is a unique $R$-Algebra-Homomorphism for any other $R$-Algebra? I want to show that $R[X]/(fX-1)$ is isomorphic to the localization of $R_f:=S^{-1}R$ where $f\in R, S=\{f^n, n\in\mathbb{N}_0\}$
We have previously proved this statement: Let $(A,\gamma)$ be a $R$-Algebra where $\gamma$ sends all Elements in $S$ to units of $A$.
If for any $R$-Algebra $(B,\alpha)$ where $\alpha$ sends all Elements in $S$ to units of $B$ there exists a unique $R$-Algebra-Homomorphism $A\rightarrow B$, then there is a unique $R$-Algebra-Isomorphism $S^{-1}R\stackrel{\sim}{\rightarrow} A$.
I think this result can be used. If we define the map $\gamma$ which sends every Element in $R$ to its constant polynomial (degree $0$), then its remainder $\mod{(fX-1)}$, we have a map which satisfies the conditions.
Can we now show that for all other $R$-Algebras $(B,\alpha)$ as defined above there that there exists a Homomorphism $A\rightarrow B$?

A: Set $A = R[X]/(fX-1)$. Then, for any other $R$-algebra $B$, we have that:
$$ Hom_R(A,B) = \{\phi \in Hom_R(R[X],B) \textrm{ such that }f\phi(X)-1 = 0 \}$$
By the universal property of polynomial rings, $Hom_R(R[X],B) \simeq B$, and the condition avove amounts to saying that $\phi(X)$ is the inverse of $f$, so $Hom_R(A,B)$ is either empty if $f$ has no inverse in $B$, or contains a unique morphism by uniqueness of  the inverse.


text:
Q: IntelliJ Idea: how to dock the java-doc window how can we dock the java-doc window to the IntelliJ IDE?
There is no Docked mode in the window-popup like explained in the IDE help
e.g. it should be like the Structure, Messages, Version Control tool Window.

A: Yes, there is something wrong with this window: by default it shows up in your face, preventing you from getting any work done, and it is not immediately obvious how to dismiss it.  A programmer's first encounter with this window tends to be a rather bad user experience.
The way I dismiss it is as follows:

*

*Click on the gray gear menu (the one at the top, not the blue one right below it)

*Uncheck Floating mode. It will then obtain a "Docked Mode" option.

*Move it to any side you like; it will then stay there.


text:
Q: Vertically align absolute positioned DIV with left value inside TD element in IE11 I have positioned some div element inside the TD element with left value by using position: absolute and left value but i need to align the div vertically in middle without fixed margin and padding value, because my TD height can be anything . I have added sample for reference, any help?

.content {
  position: absolute;
  left: 20px;
  background: grey;
  width: 100px;
  height: 20px;
}

td {
  border: 1px solid grey;
  border-collapse: collapse;
  /* Works in chrome, Firefox, Edge but not in IE 11*/
  display: flex;
  align-items: center;
}

.content2 {
  position: absolute;
  left: 140px;
  background: grey;
  width: 100px;
  height: 20px;
}

Thanks,

A: You could use display: inline-block for the div's and vertical-align:middle for the cell. It then aligns the div's vertical in the middle, no matter how high the table row is.
  .content {
     display: inline-block;
     background: grey;
     width: 100px;
     height: 20px;
     vertical-align: middle;
   }
  tr{
    height: 90px;
  }
   td {
     border: 1px solid grey;
     border-collapse: collapse;
   }

   .div1{
     margin-left: 20px;
   }
   .div2{
     margin-left: 40px;
   }

Fiddle
Note that, unlike float, with inline-block whitespace between the div's will be displayed! So unless you code them as
...

...
 you can see some unwanted extra space.


text:
Q: Assemblers and word alignment Today I learned that if you declare a char variable (which is 1 byte), the assembler actually uses 4 bytes in memory so that the boundaries lie on multiples of the word size.
If a char variable uses 4 bytes anyway, what is the point of declaring it as a char?  Why not declare it as an int?  Don't they use the same amount of memory?

A: When you are writing in assembly language and declare space for a character, the assembler allocates space for one character and no more. (I write in regard to common assemblers.) If you want to align objects in assembly language, you must include assembler directives for that purpose.
When you write in C, and the compiler translates it to assembly and/or machine code, space for a character may be padded. Typically this is not done because of alignment benefits for character objects but because you have several things declared in your program. For example, consider what happens when you declare:
char a;
char b;
int i;
char c;
double d;

A naïve compiler might do this:

*

*Allocate one byte for a at the beginning of the relevant memory, which happens to be aligned to a multiple of, say, 16 bytes.

*Allocate the next byte for b.

*Then it wants to place the int i which needs four bytes. On this machine, int objects must be aligned to multiples of four bytes, or a program that attempts to access them will crash. So the compiler skips two bytes and then sets aside four bytes for i.

*Allocate the next byte for c.

*Skip seven bytes and then set aside eight bytes for d. This makes d aligned to a multiple of eight bytes, which is beneficial on this hypothetical machine.

So, even with a naïve compiler, a character object does not require four whole bytes to itself. It can share with neighbor character objects, or other objects that do not require greater alignment. But there will be some wasted space.
A smarter compiler will do this:

*

*Sort the objects it has to allocate space for according to their alignment requirements.

*Place the most restrictive object first: Set aside eight bytes for d.

*Place the next most restrictive object: Set aside four bytes for i. Note that i is aligned to a multiple of four bytes because it follows d, which is an eight-byte object aligned to a multiple of eight bytes.

*Place the least restrictive objects: Set aside one byte each for a, b, and c.

This sort of reordering avoids wasting space, and any decent compiler will use it for memory that it is free to arrange (such as automatic objects on stack or static objects in global memory).
When you declare members inside a struct, the compiler is required to use the order in which you declare the members, so it cannot perform this reordering to save space. In that case, declaring a mixture of character objects and other objects can waste space.

A: Q: Does a program allocate four bytes for every "char" you declare?
A: No - absolutely not ;)
Q: Is it possible that, if you allocate a single byte, the program might "pad" with extra bytes?
A: Yes - absolutely yes.
The issue is "alignment".  Some computer architectures must access a data value with respect to a particular offset: 16 bits, 32 bits, etc.  Other architectures perform better if they always access a byte with respect to an offset.  Hence "padding":

*

*http://en.wikipedia.org/wiki/Byte_padding#Data_structure_padding

A: There may indeed not be any point in declaring a single char variable.
There may however be many good reasons to want a char-array, where an int-array really wouldn't do the trick!
(Try padding a data structure with ints...)

A: Others have for the most part answered this.  Assuming a char is a single byte, does declaring a char mean that it always pads to an alignment?  Nope, some compilers do by default some dont, and many you can change the default using some sort of command somewhere.  Does this mean you shouldnt use a char?  It depends, first off the padding doesnt always happen so the few wasted bytes dont always happen.  You are programming in a high level language using a compiler so if you think that you have only 3 wasted bytes in your whole binary...think again.  Depending on the architecture using chars can have some savings, for example loading immediates saves you three bytes or more on some architectures.  Other architectures just to do simple operations with the register extra instructions are required to sign extend or clip the larger register to behave like a byte sized register.  If you are on a 32 bit computer and you are using an 8 bit character because you are only counting from 1 to 100, you might want to use a full sized int, in the long run you are probably not saving anyone anything by using the char.  Now if this is an 8086 based pc running dos, that is a different story.  Or an 8 bit microcontroller, then you want to lean toward the 8 bit variables as much as possible.


text:
Q: GAE Python NDB Datastore - No need for memcache.set? The documentation (https://cloud.google.com/appengine/docs/python/ndb/) states that

NDB uses Memcache as a cache service for "hot spots" in the data

I am now using memcache only as follows:
memcache.set(key=(id), value=params, time=0)
That expires (auto flushes) pretty often and so I would like to use NDB Datastore.
I thought I would have to always put the key-value in both NDB and Memcache, then check both.
Is this being done automatically by NDB?
Ie.
ancestor_key = ndb.Key("Book", guestbook_name or "*notitle*")
greetings = Greeting.query_book(ancestor_key).fetch(20)
Would that implicitly set Memcache ?
And when I read from NDB, would it implicitly try a memcache.get(key) first?
Thanks for your patience.
EDIT - What I tried:
As a test I tried something like this:
class Book(ndb.Model):
    content = ndb.StringProperty()

class update(webapp2.RequestHandler):
    def post(self):
        p1='1'
        p2='2'
        p3='3'
        p4='4'
        p5='5'
        id='test'
        paramarray = (p1,p2,p3,p4,p5)

        book = Book(name=id,value=paramarray)
        # OR likes this -  book = Book(ndb.Key(id),value=paramarray)
        book.put()

Both versions error out.
Trying to get a key of the var id with the values of paramarray
EDIT 2 Daniel, Thank you for everything.
Have follow up formatting questions, will ask a new question.

A: Yes; see the full documentation on ndb caching. Basically, every write is cached both in a request-local in-context cache, and in the main memcached store; a get by key will look up in both caches first before falling back to the real datastore.
Edit I can't understand why you think your example would work. You defined a model with a content property, but then try to set name and value properties on it; naturally that will fail.
You should go through the ndb documentation, which gives a good introduction to using the model class.


text:
Q: Silverlight 5 - designing an editor (drag and drop)? I am currently looking to build a workflow editor in Silverlight that will allow user to drag and drop couple of objects from toolbox and draw them on canvas, connect it with connectors - pretty much like a flow chart designer.
I have gone through Silverlight Toolkit and some other links on the web, but not really sure how would I accomplish this.

*

*Is there any built-in functionality in Silverlight, or do I need to use any external libraries for proper drag and drop?

*How good is Silverlight in drawing custom shapes?

For reference, check "SilverDiagram": http://www.silverdiagram.net/Projects/SilverDiagram.aspx
Appreciate some quick & real help in this regard.
Thanks!

A: 1.Is there any built-in functionality in Silverlight, or do I need to use any external libraries for proper drag and drop?
 There is no built in functionality to develop drag and drop in Silverlight. It is always better to develop your own. It is not that difficult.
2.How good is Silverlight in drawing custom shapes?
 Silverlight is your excellent friend in drawing custom shapes. But you need to adapt your thinking you are coming from conventional way of GUI programming like WinForms.


text:
Q: How to eagerly load several attributes (including parent/grandparent/great grandparent attributes) without having duplicate grandparents on a parent I have an object that I want to eagerly load, where I want to eagerly load several parent elements, but also some grandparent elements.  I've set up my select like so:
var events = (from ed in eventRepo._session.Query<EventData>() where idsAsList.Contains(ed.Id) select ed)
                            .FetchMany(ed => ed.Parents)
                            .ThenFetchMany(pa => pa.Grandparents)
                            .ThenFetch(gp => gp.GreatGrandparents)
                            // other fetches here for other attributes
                            .ToList();

My problem is that if I just .FetchMany the parents, I get the right number of elements.  Once I add the grandparents, I get way too many, and that grows even more with great grandparents.
It's clearly doing some kind of cartesian product, so I had a look around and saw that some people use Transformers to solve this.  I had a look at that and tried to implement it, but adding a .TransformUsing() causes a compiler error, since I don't seem to be able to call .TransformUsing() on this type of call.
What is the right way to get the right number of elements from such a call, without duplicates due to computing the cartesian product?

A: Here is a pretty popular post that uses Futures to do this type of loadign to avoid cartesian products.  It isn't as elegant as doing it in a single query but it gets the job done.
Fighting cartesian product (x-join) when using NHibernate 3.0.0
One other possible solution would be to define your collections as sets instead of bags.  This would also avoid cartesian product issues.  I don't really like this solution considering you have to use an nhibernate specific collection type but it is known to work.

A: There is not much you can do about it if you get force NHibernate join explicitly. The database will return same entities multiple times (this is perfectly normal since your query makes Cartesian joins). And NHibernate cannot distinguish if you ask same item multiple times or not. NHibernate does not know your intention. There is a workaround though. You can add the below line
var eventsSet = new HashSet<Events>(events);

Assuming your entity override Equals and GetHashCode, you will end up with unique events.


text:
Q: running an xap (silverlight app) in VS 2005 I've written a small silverlight app in vs 2008.  Now I'd like to plug that app into a site that was developed using vs.net 2005. what are the steps needed to do this.  This is what I've done so far.
In web.config
<compilation debug="true" strict="false" explicit="true">
        <assemblies>
            <add assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
        </assemblies>
    </compilation>

<controls>
            <add tagPrefix="asp" namespace="System.Web.UI.SilverlightControls" assembly="System.Web.Silverlight, Version=2.0.5.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
        </controls>

In the asp page.
<%@ Register Assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
Namespace="System.Web.UI" TagPrefix="asp" %>

<%@ Register TagPrefix="asp" Namespace="System.Web.UI.SilverlightControls" Assembly="System.Web.Silverlight, Version=2.0.5.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" %>

<form id="form1" runat="server">

        Silverlight Test
        <asp:ScriptManager ID="scriptManager" runat="server" />

            <asp:Silverlight ID="silverlightControl" runat="server" Source="~/TypingTestV2.xap"
                MinimumVersion="2.0.31005.0" Width="100%" Height="100%" />

</form>

When i run the app, i get an error in IE

Webpage error details :
  User Agent: Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0; WOW64; Trident/4.0; SLCC1; .NET CLR 2.0.50727; InfoPath.2; .NET CLR 3.5.30729; MS-RTC LM 8; .NET CLR 3.0.30729; OfficeLiveConnector.1.4; OfficeLivePatch.1.3)
  Timestamp: Fri, 7 Aug 2009 13:12:30 UTC
  Message: ASP.NET Ajax client-side framework failed to load.
  Line: 38
  Char: 34
  Code: 0
  URI: htt://localhost:4063/Silverlight.aspx
Message: 'Sys' is undefined
  Line: 48
  Char: 1
  Code: 0
  URI: htt://localhost:4063/Silverlight.aspx
Message: 'Sys' is undefined
  Line: 57
  Char: 1
  Code: 0
  URI: htt://localhost:4063/Silverlight.aspx
Message: 'Sys' is undefined
  Line: 67
  Char: 1
  Code: 0
  URI: htt://localhost:4063/Silverlight.aspx

and in Firefox :

ASP.NET Ajax client-side framework failed to load.
  [Break on this error] if (typeof(Sys) === 'undefined') throw n...ient-side framework failed to load.');\r\n

So i'm not sure what the problem is. although it says AJAX, I'm not sure what the next step would be
(the htt above was http, but the site won't allow me to do more than one hyperlink in the post, so i changed it to htt)
hope someone is willing to help.
Shannon

A: Sliverlight 3 has dropped the asp silverlight server control, hence you would be better off duplicating the content of the test .htm page that VS 2008 creates.  Use the <object> tag directly in your ASP.NET 2.0 app.


text:
Q: 2 following gates, inverse circuit I have a circuit that has 4 wires and 2 following each other Toffoli gates.
The first Toffoli gate occupies 3 wires from above, the following Toffoli gate occupies 3 wires from below.
What will look like the inverse circuit of this entire circuit?

Thanks much!

A: Well, if inverse means "how to undo", you just need to calculate the inverse matrix of the product of the two matrices discussed there:
2 following gates, permutation matrix
Have fun.