text:
Q: Does C++ accept inline virtual function while performing polymorphism? //header.h
#include<iostream>
using namespace std;
struct Base {
    virtual void vf();
};
struct Derived :Base {
    virtual void vf();
};
inline void Base::vf() {
    cout << "Base::vf()" << endl;
}
inline void Derived::vf() {
    cout << "Derived::vf()" << endl;
}

//source.cpp
#include"header.h"
int main() {
    Base *pb = new Derived;
    pb->vf();
}

//source2.cpp
#include"header.h"

It compiles and works in MSVC and g++.
But if I remove both inline keywords, a duplicate definition error will be caught by the linker since I include function definition twice, which will break the ODR.
Since I call the virtual function with a base pointer, it should be decided at run-time, and the compiler will ignore my inlining request, causing the duplicate error.
Do I get something wrong?

A: The One Definition Rule is mandatory. It is required by C++. A given object or a function must be defined exactly once. Removing the inline keyword (in your case) violates this rule, making the resulting program ill-formed.
Runtime polymorphism and virtual function dispatch happens at run time. You can only get to the run time part if your program is well-formed. If it breaks the ODR it is not well-formed, so how runtime polymorphism and virtual function dispatch works becomes a moot point. If your program is ill-formed there won't be anything to run and no base pointer at all.
It is true that an ODR violation does not require a diagnostic, but the resulting code is still broken. Please write a thank-you note to your compiler for alerting you to the problem.

A: As the code is currently written, the member functions are defined in header.h and marked inline. That's okay from the perspective of the language definition: inline means "it's okay to have multiple [identical] definitions of this function". From a maintenance perspective it can make things harder. In particular, when you do this, every time you change the implementation of any of those functions you have to recompile all of the source files that use that header. Putting the definitions of those functions into their own source file[s] means you only have to recompile the file[s] that changed.
If you don't want to mark your functions inline (and you don't want to define them inside the class definition, which makes them implicitly inline), then you have to put each function definition into exactly one source file. A useful first step is to define all of the non-inline member functions of a class in a single source file. So your source2.cpp might look like this (yes, that's member functions from two classes):
#include "header.h"
#include <iostream>

void Base::vf() {
    std::cout << "Base::vf()\n";
}

void Derived::vf() {
    std::cout << "Derived::vf()\n";
}

and you'd remove those definitions from header.h. So now header.h contains only the class definition; source2.cpp has the definitions of the member functions; and source.cpp has the main function.


text:
Q: Allow users to cast multiple votes with increasing cost In question 4012, Trey Jackson asks about the practice of casting down votes for all questions that are not your own. His question lead me to wonder about the current policy of allowing only one vote per answer. Instead of allowing only one vote, why not allow multiple votes with increasing cost? The nth time a user votes for an answer, whether up or down, it will cost m^(n-1) rep, where m is the number of other answers available at the time of the vote. (Or some other cost function). Using an exponential cost function will prevent high-rep users from becoming too strong, but this does give the high-rep user the ability to promote answers that are better (in their judgment).
(Note that I believe the first vote should be free, whereas m^(n-1) makes the first vote cost 1 rep; tweak as necessary, either by limiting the range or subtracting 1.)

A: I think we should keep it at one vote per answer.  By doing that, everyone has an equal say and answers that are up/down voted are voted on by the community and not just someone with rep to spend.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How do I safely pass objects, especially STL objects, to and from a DLL? How do I pass class objects, especially STL objects, to and from a C++ DLL?
My application has to interact with third-party plugins in the form of DLL files, and I can't control what compiler these plugins are built with. I'm aware that there's no guaranteed ABI for STL objects, and I'm concerned about causing instability in my application.

A: @computerfreaker has written a great explanation of why the lack of ABI prevents passing C++ objects across DLL boundaries in the general case, even when the type definitions are under user control and the exact same token sequence is used in both programs.  (There are two cases which do work: standard-layout classes, and pure interfaces)
For object types defined in the C++ Standard (including those adapted from the Standard Template Library), the situation is far, far worse.  The tokens defining these types are NOT the same across multiple compilers, as the C++ Standard does not provide a complete type definition, only minimum requirements. In addition, name lookup of the identifiers that appear in these type definitions don't resolve the same.  Even on systems where there is a C++ ABI, attempting to share such types across module boundaries results in massive undefined behavior due to One Definition Rule violations.
This is something that Linux programmers weren't accustomed to dealing with, because g++'s libstdc++ was a de-facto standard and virtually all programs used it, thus satisfying the ODR.  clang's libc++ broke that assumption, and then C++11 came along with mandatory changes to nearly all Standard library types.
Just don't share Standard library types between modules.  It's undefined behavior.

A: Some of the answers here make passing C++ classes sound really scary, but I'd like to share an alternate point of view.  The pure virtual C++ method mentioned in some of the other responses actually turns out to be cleaner than you might think.  I've built an entire plugin system around the concept and it's been working very well for years.  I have a "PluginManager" class that dynamically loads the dlls from a specified directory using LoadLib() and GetProcAddress() (and the Linux equivalents so the executable to make it cross platform).
Believe it or not, this method is forgiving even if you do some wacky stuff like  add a new function at the end of your pure virtual interface and try to load dlls compiled against the interface without that new function - they'll load just fine. Of course... you'll have to check a version number to make sure your executable only calls the new function for newer dlls that implement the function.  But the good news is: it works! So in a way, you have a crude method for evolving your interface over time.
Another cool thing about pure virtual interfaces - you can inherit as many interfaces as you want and you'll never run into the diamond problem!
I would say the biggest downside to this approach is that you have to be very careful about what types you pass as parameters.  No classes or STL objects without wrapping them with pure virtual interfaces first. No structs (without going through the pragma pack voodoo).  Just primative types and pointers to other interfaces.  Also, you can't overload functions, which is an inconvenience, but not a show-stopper.
The good news is that with a handful of lines of code you can make reusable generic classes and interfaces to wrap STL strings, vectors, and other container classes.  Alternatively, you can add functions to your interface like GetCount() and GetVal(n) to let people loop through lists.
People building plugins for us find it quite easy.  They don't have to be experts on the ABI boundary or anything - they just inherit the interfaces they're interested in, code up the functions they support, and return false for the ones they don't.
The technology that makes all this work isn't based on any standard as far as I know. From what I gather, Microsoft decided to do their virtual tables that way so they could make COM, and other compiler writers decided to follow suit.  This includes GCC, Intel, Borland, and most other major C++ compilers. If you're planning on using an obscure embedded compiler then this approach probably won't work for you. Theoretically any compiler company could change their virtual tables at any time and break things, but considering the massive amount of code written over the years that depends on this technology, I would be very surprised if any of the major players decided to break rank.
So the moral of the story is... With the exception of a few extreme circumstances, you need one person in charge of the interfaces who can make sure the ABI boundary stays clean with primitive types and avoids overloading. If you are OK with that stipulation, then I wouldn't be afraid to share interfaces to classes in DLLs/SOs between compilers.  Sharing classes directly == trouble, but sharing pure virtual interfaces isn't so bad.

A: The short answer to this question is don't. Because there's no standard C++ ABI (application binary interface, a standard for calling conventions, data packing/alignment, type size, etc.), you will have to jump through a lot of hoops to try and enforce a standard way of dealing with class objects in your program. There's not even a guarantee it'll work after you jump through all those hoops, nor is there a guarantee that a solution which works in one compiler release will work in the next.
Just create a plain C interface using extern "C", since the C ABI is well-defined and stable.

If you really, really want to pass C++ objects across a DLL boundary, it's technically possible. Here are some of the factors you'll have to account for:
Data packing/alignment
Within a given class, individual data members will usually be specially placed in memory so their addresses correspond to a multiple of the type's size. For example, an int might be aligned to a 4-byte boundary.
If your DLL is compiled with a different compiler than your EXE, the DLL's version of a given class might have different packing than the EXE's version, so when the EXE passes the class object to the DLL, the DLL might be unable to properly access a given data member within that class. The DLL would attempt to read from the address specified by its own definition of the class, not the EXE's definition, and since the desired data member is not actually stored there, garbage values would result.
You can work around this using the #pragma pack preprocessor directive, which will force the compiler to apply specific packing. The compiler will still apply default packing if you select a pack value bigger than the one the compiler would have chosen, so if you pick a large packing value, a class can still have different packing between compilers. The solution for this is to use #pragma pack(1), which will force the compiler to align data members on a one-byte boundary (essentially, no packing will be applied). This is not a great idea, as it can cause performance issues or even crashes on certain systems. However, it will ensure consistency in the way your class's data members are aligned in memory.
Member reordering
If your class is not standard-layout, the compiler can rearrange its data members in memory. There is no standard for how this is done, so any data rearranging can cause incompatibilities between compilers. Passing data back and forth to a DLL will require standard-layout classes, therefore.
Calling convention
There are multiple calling conventions a given function can have. These calling conventions specify how data is to be passed to functions: are parameters stored in registers or on the stack? What order are arguments pushed onto the stack? Who cleans up any arguments left on the stack after the function finishes?
It's important you maintain a standard calling convention; if you declare a function as _cdecl, the default for C++, and try to call it using _stdcall bad things will happen. _cdecl is the default calling convention for C++ functions, however, so this is one thing that won't break unless you deliberately break it by specifying an _stdcall in one place and a _cdecl in another.
Datatype size
According to this documentation, on Windows, most fundamental datatypes have the same sizes regardless of whether your app is 32-bit or 64-bit. However, since the size of a given datatype is enforced by the compiler, not by any standard (all the standard guarantees is that 1 == sizeof(char) <= sizeof(short) <= sizeof(int) <= sizeof(long) <= sizeof(long long)), it's a good idea to use fixed-size datatypes to ensure datatype size compatibility where possible.
Heap issues
If your DLL links to a different version of the C runtime than your EXE, the two modules will use different heaps. This is an especially likely problem given that the modules are being compiled with different compilers.
To mitigate this, all memory will have to be allocated into a shared heap, and deallocated from the same heap. Fortunately, Windows provides APIs to help with this: GetProcessHeap will let you access the host EXE's heap, and HeapAlloc/HeapFree will let you allocate and free memory within this heap. It is important that you not use normal malloc/free as there is no guarantee they will work the way you expect.
STL issues
The C++ standard library has its own set of ABI issues. There is no guarantee that a given STL type is laid out the same way in memory, nor is there a guarantee that a given STL class has the same size from one implementation to another (in particular, debug builds may put extra debug information into a given STL type). Therefore, any STL container will have to be unpacked into fundamental types before being passed across the DLL boundary and repacked on the other side.
Name mangling
Your DLL will presumably export functions which your EXE will want to call. However, C++ compilers do not have a standard way of mangling function names. This means a function named GetCCDLL might be mangled to _Z8GetCCDLLv in GCC and ?GetCCDLL@@YAPAUCCDLL_v1@@XZ in MSVC.
You already won't be able to guarantee static linking to your DLL, since a DLL produced with GCC won't produce a .lib file and statically linking a DLL in MSVC requires one. Dynamically linking seems like a much cleaner option, but name mangling gets in your way: if you try to GetProcAddress the wrong mangled name, the call will fail and you won't be able to use your DLL. This requires a little bit of hackery to get around, and is a fairly major reason why passing C++ classes across a DLL boundary is a bad idea.
You'll need to build your DLL, then examine the produced .def file (if one is produced; this will vary based on your project options) or use a tool like Dependency Walker to find the mangled name. Then, you'll need to write your own .def file, defining an unmangled alias to the mangled function. As an example, let's use the GetCCDLL function I mentioned a bit further up. On my system, the following .def files work for GCC and MSVC, respectively:
GCC:
EXPORTS
    GetCCDLL=_Z8GetCCDLLv @1

MSVC:
EXPORTS
    GetCCDLL=?GetCCDLL@@YAPAUCCDLL_v1@@XZ @1

Rebuild your DLL, then re-examine the functions it exports. An unmangled function name should be among them. Note that you cannot use overloaded functions this way: the unmangled function name is an alias for one specific function overload as defined by the mangled name. Also note that you'll need to create a new .def file for your DLL every time you change the function declarations, since the mangled names will change. Most importantly, by bypassing the name mangling, you're overriding any protections the linker is trying to offer you with regards to incompatibility issues.
This whole process is simpler if you create an interface for your DLL to follow, since you'll just have one function to define an alias for instead of needing to create an alias for every function in your DLL. However, the same caveats still apply.
Passing class objects to a function
This is probably the most subtle and most dangerous of the issues that plague cross-compiler data passing. Even if you handle everything else, there's no standard for how arguments are passed to a function. This can cause subtle crashes with no apparent reason and no easy way to debug them. You'll need to pass all arguments via pointers, including buffers for any return values. This is clumsy and inconvenient, and is yet another hacky workaround that may or may not work.

Putting together all these workarounds and building on some creative work with templates and operators, we can attempt to safely pass objects across a DLL boundary. Note that C++11 support is mandatory, as is support for #pragma pack and its variants; MSVC 2013 offers this support, as do recent versions of GCC and clang.
//POD_base.h: defines a template base class that wraps and unwraps data types for safe passing across compiler boundaries

//define malloc/free replacements to make use of Windows heap APIs
namespace pod_helpers
{
  void* pod_malloc(size_t size)
  {
    HANDLE heapHandle = GetProcessHeap();
    HANDLE storageHandle = nullptr;

    if (heapHandle == nullptr)
    {
      return nullptr;
    }

    storageHandle = HeapAlloc(heapHandle, 0, size);

    return storageHandle;
  }

  void pod_free(void* ptr)
  {
    HANDLE heapHandle = GetProcessHeap();
    if (heapHandle == nullptr)
    {
      return;
    }

    if (ptr == nullptr)
    {
      return;
    }

    HeapFree(heapHandle, 0, ptr);
  }
}

//define a template base class. We'll specialize this class for each datatype we want to pass across compiler boundaries.
#pragma pack(push, 1)
// All members are protected, because the class *must* be specialized
// for each type
template<typename T>
class pod
{
protected:
  pod();
  pod(const T& value);
  pod(const pod& copy);
  ~pod();

  pod<T>& operator=(pod<T> value);
  operator T() const;

  T get() const;
  void swap(pod<T>& first, pod<T>& second);
};
#pragma pack(pop)

//POD_basic_types.h: holds pod specializations for basic datatypes.
#pragma pack(push, 1)
template<>
class pod<unsigned int>
{
  //these are a couple of convenience typedefs that make the class easier to specialize and understand, since the behind-the-scenes logic is almost entirely the same except for the underlying datatypes in each specialization.
  typedef int original_type;
  typedef std::int32_t safe_type;

public:
  pod() : data(nullptr) {}

  pod(const original_type& value)
  {
    set_from(value);
  }

  pod(const pod<original_type>& copyVal)
  {
    original_type copyData = copyVal.get();
    set_from(copyData);
  }

  ~pod()
  {
    release();
  }

  pod<original_type>& operator=(pod<original_type> value)
  {
    swap(*this, value);

    return *this;
  }

  operator original_type() const
  {
    return get();
  }

protected:
  safe_type* data;

  original_type get() const
  {
    original_type result;

    result = static_cast<original_type>(*data);

    return result;
  }

  void set_from(const original_type& value)
  {
    data = reinterpret_cast<safe_type*>(pod_helpers::pod_malloc(sizeof(safe_type))); //note the pod_malloc call here - we want our memory buffer to go in the process heap, not the possibly-isolated DLL heap.

    if (data == nullptr)
    {
      return;
    }

    new(data) safe_type (value);
  }

  void release()
  {
    if (data)
    {
      pod_helpers::pod_free(data); //pod_free to go with the pod_malloc.
      data = nullptr;
    }
  }

  void swap(pod<original_type>& first, pod<original_type>& second)
  {
    using std::swap;

    swap(first.data, second.data);
  }
};
#pragma pack(pop)

The pod class is specialized for every basic datatype, so that int will automatically be wrapped to int32_t, uint will be wrapped to uint32_t, etc. This all occurs behind the scenes, thanks to the overloaded = and () operators. I have omitted the rest of the basic type specializations since they're almost entirely the same except for the underlying datatypes (the bool specialization has a little bit of extra logic, since it's converted to a int8_t and then the int8_t is compared to 0 to convert back to bool, but this is fairly trivial).
We can also wrap STL types in this way, although it requires a little extra work:
#pragma pack(push, 1)
template<typename charT>
class pod<std::basic_string<charT>> //double template ftw. We're specializing pod for std::basic_string, but we're making this specialization able to be specialized for different types; this way we can support all the basic_string types without needing to create four specializations of pod.
{
  //more comfort typedefs
  typedef std::basic_string<charT> original_type;
  typedef charT safe_type;

public:
  pod() : data(nullptr) {}

  pod(const original_type& value)
  {
    set_from(value);
  }

  pod(const charT* charValue)
  {
    original_type temp(charValue);
    set_from(temp);
  }

  pod(const pod<original_type>& copyVal)
  {
    original_type copyData = copyVal.get();
    set_from(copyData);
  }

  ~pod()
  {
    release();
  }

  pod<original_type>& operator=(pod<original_type> value)
  {
    swap(*this, value);

    return *this;
  }

  operator original_type() const
  {
    return get();
  }

protected:
  //this is almost the same as a basic type specialization, but we have to keep track of the number of elements being stored within the basic_string as well as the elements themselves.
  safe_type* data;
  typename original_type::size_type dataSize;

  original_type get() const
  {
    original_type result;
    result.reserve(dataSize);

    std::copy(data, data + dataSize, std::back_inserter(result));

    return result;
  }

  void set_from(const original_type& value)
  {
    dataSize = value.size();

    data = reinterpret_cast<safe_type*>(pod_helpers::pod_malloc(sizeof(safe_type) * dataSize));

    if (data == nullptr)
    {
      return;
    }

    //figure out where the data to copy starts and stops, then loop through the basic_string and copy each element to our buffer.
    safe_type* dataIterPtr = data;
    safe_type* dataEndPtr = data + dataSize;
    typename original_type::const_iterator iter = value.begin();

    for (; dataIterPtr != dataEndPtr;)
    {
      new(dataIterPtr++) safe_type(*iter++);
    }
  }

  void release()
  {
    if (data)
    {
      pod_helpers::pod_free(data);
      data = nullptr;
      dataSize = 0;
    }
  }

  void swap(pod<original_type>& first, pod<original_type>& second)
  {
    using std::swap;

    swap(first.data, second.data);
    swap(first.dataSize, second.dataSize);
  }
};
#pragma pack(pop)

Now we can create a DLL that makes use of these pod types. First we need an interface, so we'll only have one method to figure out mangling for.
//CCDLL.h: defines a DLL interface for a pod-based DLL
struct CCDLL_v1
{
  virtual void ShowMessage(const pod<std::wstring>* message) = 0;
};

CCDLL_v1* GetCCDLL();

This just creates a basic interface both the DLL and any callers can use. Note that we're passing a pointer to a pod, not a pod itself. Now we need to implement that on the DLL side:
struct CCDLL_v1_implementation: CCDLL_v1
{
  virtual void ShowMessage(const pod<std::wstring>* message) override;
};

CCDLL_v1* GetCCDLL()
{
  static CCDLL_v1_implementation* CCDLL = nullptr;

  if (!CCDLL)
  {
    CCDLL = new CCDLL_v1_implementation;
  }

  return CCDLL;
}

And now let's implement the ShowMessage function:
#include "CCDLL_implementation.h"
void CCDLL_v1_implementation::ShowMessage(const pod<std::wstring>* message)
{
  std::wstring workingMessage = *message;

  MessageBox(NULL, workingMessage.c_str(), TEXT("This is a cross-compiler message"), MB_OK);
}

Nothing too fancy: this just copies the passed pod into a normal wstring and shows it in a messagebox. After all, this is just a POC, not a full utility library.
Now we can build the DLL. Don't forget the special .def files to work around the linker's name mangling. (Note: the CCDLL struct I actually built and ran had more functions than the one I present here. The .def files may not work as expected.)
Now for an EXE to call the DLL:
//main.cpp
#include "../CCDLL/CCDLL.h"

typedef CCDLL_v1*(__cdecl* fnGetCCDLL)();
static fnGetCCDLL Ptr_GetCCDLL = NULL;

int main()
{
  HMODULE ccdll = LoadLibrary(TEXT("D:\\Programming\\C++\\CCDLL\\Debug_VS\\CCDLL.dll")); //I built the DLL with Visual Studio and the EXE with GCC. Your paths may vary.

  Ptr_GetCCDLL = (fnGetCCDLL)GetProcAddress(ccdll, (LPCSTR)"GetCCDLL");
  CCDLL_v1* CCDLL_lib;

  CCDLL_lib = Ptr_GetCCDLL(); //This calls the DLL's GetCCDLL method, which is an alias to the mangled function. By dynamically loading the DLL like this, we're completely bypassing the name mangling, exactly as expected.

  pod<std::wstring> message = TEXT("Hello world!");

  CCDLL_lib->ShowMessage(&message);

  FreeLibrary(ccdll); //unload the library when we're done with it

  return 0;
}

And here are the results. Our DLL works. We've successfully reached past STL ABI issues, past C++ ABI issues, past mangling issues, and our MSVC DLL is working with a GCC EXE.

In conclusion, if you absolutely must pass C++ objects across DLL boundaries, this is how you do it. However, none of this is guaranteed to work with your setup or anyone else's. Any of this may break at any time, and probably will break the day before your software is scheduled to have a major release. This path is full of hacks, risks, and general idiocy that I probably should be shot for. If you do go this route, please test with extreme caution. And really... just don't do this at all.

A: You cannot safely pass STL objects across DLL boundaries, unless all the modules (.EXE and .DLLs) are built with the same C++ compiler version and the same settings and flavors of the CRT, which is highly constraining, and clearly not your case.
If you want to expose an object-oriented interface from your DLL, you should expose C++ pure interfaces (which is similar to what COM does). Consider reading this interesting article on CodeProject:

HowTo: Export C++ classes from a DLL

You may also want to consider exposing a pure C interface at the DLL boundary, and then building a C++ wrapper at the caller site.
This is similar to what happens in Win32: Win32 implementation code is almost C++, but lots of Win32 APIs expose a pure C interface (there are also APIs that expose COM interfaces). Then ATL/WTL and MFC wrap these pure C interfaces with C++ classes and objects.


text:
Q: force:createRecord being called from a Lightning App I followed the instructions in this blog post to create a Lightning component using force:createrecord -
http://www.infallibletechie.com/2017/11/forcecreaterecord-example-in-salesforce.html
I was able to get this to work perfectly fine.  I then created a Lightning app which wrapped the component:

In Dev Console, I then clciked on Preview, and it brought up the button in the component.  But when I clicked the button, the call to force:createRecord failed.  Why is this happening?

A: I have came across this issue recently and found that this is how force:createRecord event works. The error I see when I debug:

This page has an error. You might just need to refresh it.
  Error in $A.getCallback() [Cannot read property 'setParams' of undefined]
  Callback failed: apex://customFieldController/ACTION$getRecId
  Failing descriptor: {c:customComp}

And in the official Documentation, it was mentioned:

This event is handled by the one.app container. It's supported in Lightning Experience, Salesforce app, and Lightning communities.

I bet you will not see this error if you have had this component on a Community page. Because, that's how I finally did my testing for force:createRecord event.


text:
Q: Python: check if an object is NOT an "array-type" I'm looking for a way to test if an object is not of a "list-ish" type, that is - not only that the object is not iterable (e.g. - you can also run iter on a string, or on a simple object that implements iter) but that the object is not in the list family. I define the "list" family as list/tuple/set/frozenset, or anything that inherits from those, however - as there might be something that I'm missing, I would like to find a more general way than running isinstance against all of those types.
I thought of two possible ways to do it, but both seem somewhat awkward as they very much test against every possible list type, and I'm looking for a more general solution.
First option:
return not isinstance( value, (frozenset, list, set, tuple,) )

Second option:
return not hasattr(value, '__iter__')

Is testing for the __iter__ attribute enough? Is there a better way for finding whether an object is not a list-type?
Thanks in advance.
Edit:
(Quoted from comment to @Rosh Oxymoron's Solution):
Thinking about the definition better now, I believe it would be more right to say that I need to find everything that is not array-type in definition, but it can still be a string/other simple object...Checking against collections.Iterable will still give me True for objects which implement the __iter__ method.

A: There is no term 'list-ish' and there is no magic build-in check_if_value_is_an_instance_of_some_i_dont_know_what_set_of_types.
You solution with not isinstance( value, (frozenset, list, set, tuple,) ) is pretty good - it is clear and explicit.

A: There is no such family – it's not well-defined, and naturally there's no way to check for it. The closest thing possible is an iterable that is not a string. You can test if the object for iterability and then explicitly check if it is a string:
if isinstance(ob, collections.Iterable) and not isinstance(ob, types.StringTypes):
    print "An iterable container"

A better approach would be to always ask for an iterable object, and when you need to pass a single string S, pass [S] instead. The ability to pass a string is a feature, e.g.:
alphabet = set('abcdefgijklmopqrstuvwxyz')

If you special-case string, you will:

*

*Break the ability to use your function with the most natural way to pass a collection of characters.

*Create inconsistency for user-defined string types and/or other containers that are string-ish (e.g. array.array can represent a chunk of data, just like string).

A string can be used to represent both a single piece of text and a collection of characters, and because of the second it is also list-ish.


text:
Q: Jquery, remove created div if outside screen width I got this function which adds a div each second. it then moves across the screen, and I'd like for it to remove the divs once they're outside the screen. Is it possible to "attach" such a timer to the divs as I create them?
   function deployRandom(){
        $(".bottomEvents").append("
hello world
")
        $(".floatingDiv").animate({
            marginLeft: "+=250px",
        }, 1000 );
    }

A: The main idea is that:
You must know if your div get out of the range("out of window size").
First you must know window width:
$(window).width();

than you must know your div position to the left
currentDiv.position().left + currentDiv.width()

and than if your div out of range you must hide it.
Here  small example: https://jsfiddle.net/RomanGroovyDev/pyzuLtzd/3/

A: You can append every created div to an array and check for theirs position with a unique dispatcher timer:
var divsArray = [];

function clearOutsideDivs()
{
    var newDivsArray = [];

    for (var i=0; i<divsArray.length; ++i)
    {
        var currentDiv = divsArray[i];
        var currentDivMarginLeft = parseInt(currentDiv.css('margin-left'), 10);

        if (currentDivMarginLeft > $(window).width())
            currentDiv.remove();
        else
            newDivsArray.push(currentDiv);
    }

    divsArray = newDivsArray;
}

function deployRandom(){
    var generatedDiv = $("
hello world
");
    $(".bottomEvents").append(generatedDiv);
    divsArray.push(generatedDiv);

    $(".floatingDiv").animate({
        marginLeft: "+=250px",
    }, 1000, clearOutsideDivs);
}

jsFiddle example here.


text:
Q: Initialization list Classes Hello all I am trying to make a code for a game that I want to make as of right now I am kinda stuck on classes and wanted use the list initialization to make it easier for to enter the players attributes here is my class below this is part of my main code as I did not want to make a header or another .cpp file yet.
class Player {

public:

string name;
int id;
int height;
double closeshot;
double midshot;
double threeshot;
double dribble;
double defense;
double jump;

Player() {};
Player(string a, int b, int c, double d, double e, double f, double g, double h, double i);

}pg1,pg2,sg1,sg2;

Player::Player(string a, int b, int c, double d, double e, double f, double g, double h, double i) {

    name = a;
    id = b;
    height = c;
    closeshot = d;
    midshot = e;
    threeshot = f;
    dribble = g;
    defense = h;
    jump = i;

}
Here is my player initiliaztion list below.
Player pg1( "Player1Home", 1, 61, 10.00, 10.00, 10.00, 10.00, 10.00, 10.00 );
Player pg2( "Player1Away", 6, 72, 10.00, 10.00, 10.00, 10.00, 10.00, 15.00 );
Player sg1( "Player2Home", 2, 61, 10.00, 10.00, 10.00, 10.00, 10.00, 10.00 );
Player sg2( "Player2Away", 7, 71, 10.00, 10.00, 10.00, 10.00, 10.00, 10.00 );

Any help would be appreciate im still relatively new at this.
So I decided to just go back to structs as they are just easier to work with
struct Player {

string name;
int id;
int height;
double closeshot;
double midshot;
double threeshot;
double dribble;
double defense;
double jump;

}pg1,pg2,sg1,sg2;

And this is how I added in my values
        pg1.name = "Player1Home";
        pg1.id = 1;
        pg1.height = 61;
        pg1.closeshot = 10.00;
        pg1.midshot = 10.00;
        pg1.threeshot = 10.00;
        pg1.dribble = 10.00;
        pg1.defense = 10.00;
        pg1.jump = 10.00;

        pg2.name = "Player1Away";
        pg2.id = 6;
        pg2.height = 61;
        pg2.closeshot = 10.00;
        pg2.midshot = 10.00;
        pg2.threeshot = 10.00;
        pg2.dribble = 10.00;
        pg2.defense = 10.00;
        pg2.jump = 10.00;

        sg1.name = "Player2Home";
        sg1.id = 2;
        sg1.height = 61;
        sg1.closeshot = 10.00;
        sg1.midshot = 10.00;
        sg1.threeshot = 10.00;
        sg1.dribble = 10.00;
        sg1.defense = 10.00;
        sg1.jump = 10.00;

        sg2.name = "Player2Away";
        sg2.id = 7;
        sg2.height = 61;
        sg2.closeshot = 10.00;
        sg2.midshot = 10.00;
        sg2.threeshot = 10.00;
        sg2.dribble = 10.00;
        sg2.defense = 10.00;
        sg2.jump = 10.00;

The rest of my code just works better when I leave it this way.


text:
Q: "WorkerProcessRestarting. Initialization timed out and host is shutting down" Azure function app run time error "WorkerProcessRestarting. Initialization timed out and host is shutting down" Azure function app run time error for Isolated function, can someone please help.
I created isolated function app in framework 4.8, not able to debug it locally or run it locally. Visual studio doesn't show any error when i try to debug the function app. It keeps processing without hitting the function and not returning any error.
Then I tried to deploy it Azure, deployment went fine, when i Try to Run it, get below error in 10 secs
"WorkerProcessRestarting. Initialization timed out and host is shutting down"

A: *

*I have reproduced in my environment that VS 2022 is not working with the Azure Functions .NET 4.8 Isolated Project in both debug and running.

*Tried with the VS Code with the same project, it worked only for Run without debugging.

*Debugger Points not hitting the code in VS Code and also in VS 2022:

*

*I have raised the issue  in GitHub - Azure Functions dotnet worker Repository and will update the resolution here.

A: Please refer to the Microsoft sample for Isolated Function App
https://github.com/Azure/azure-functions-dotnet-worker/tree/main/samples/FunctionApp
In my case , by mistake I removed this line .ConfigureFunctionsWorkerDefaults
This is the screenshot of the Program.cs from the url above
This is what I added to Program.cs in my solution and which fixed the issue for me.
Program.cs with minimum code to make it work


text:
Q: Books/resources that teach software developers how to pragmatically use project/bug/task tracking tools Does anyone know of excellent (in your opinion) books/websites that go over in details how to pragmatically use a bug/task/project management tool to help improve software development process? Ideally, I would like "from-the-trench" kind of resource, not theory.
Examples of such mgmt tools are: JIRA/Confluence combo, Visual Studio Team System / Sharepoint, FogBugz, etc.
I think I'm looking for books that are like the 3 Pragmatic book series (source control, unit testing, and build automation) Come to think of it, I wish the pragmatic guys also released a book on how to integrate project mgmt tools to their software development process.
I know of a few that might fit as the answers to my question:
Painless Project Management with FogBugz, Second Edition
Visual Studio Team System: Better Software Development for Agile Teams
Software Engineering with Microsoft Visual Studio Team System
Much like how we learn different programming languages to broaden our thought process, I dont really mind what tool the book/website uses. What I'm most interested in is HOW the tool is integrated into software development process to help improve it.

A: There's Steve McConnells' book Rapid Development
Have you also looked at these books in the Pragmatic Bookshelf:
Manage It!: Your Guide to Modern, Pragmatic Project Management
Ship it! A Practical Guide to Successful Software Projects
Release It!: Design and Deploy Production-Ready Software

A: If you want "from the trenches" it's hard to beat Virtual Labs.  They give you a chance to get hands-on with the technology (VSTS in this case).  There are VSTS labs on change management, managing development efforts, version control and etc.


text:
Q: Postgresql- Trying to get a list of results where a date range is null I'm working on converting results from a MySQL database to a Postgresql one, and finding random syntax issues that searching isn't helping with.
For this one: I am trying to return a list of results for users who have not created a job in our system for over 90 days. I've tried a few variations, but here is where my code is at right now:
 select  law_firms.name as "Law Firm"
from law_firms
left join jobs on jobs.law_firm_id = law_firms.id
  where jobs.id IN (SELECT jobs.created_at::date >= 90) IS NULL
  and law_firms.deleted_at IS NULL
  and law_firms.name not like '%Temp%"'
  and law_firms.name not like '%Individual%'
  GROUP BY law_firms.name

I've tried a few different variations of ::date between and CASTS, but it's coming back with an error message of "ERROR: operator does not exist: date >= integer Hint: No operator matches the given name and argument types. You might need to add explicit type casts"
For reference, the MySQL code that worked in our BI originally was:
where `jobs`.`id` IN (SELECT `jobs`.`created_at` BETWEEN NOW() - INTERVAL 90 DAY AND NOW()) IS NULL

A: As per my comment, isn't this as simple as converting the bracketed subquery
from:
SELECT `jobs`.`created_at` BETWEEN NOW() - INTERVAL 90 DAY AND NOW()

To this:
SELECT jobs.created_at BETWEEN NOW() - interval '90 days' AND NOW()

edit: of course, you need to add WHERE and FROM to match the original subquery, but your example original subquery doesn't include it.
I think it would look like this:
SELECT jobs.created_at
FROM jobs
WHERE jobs.created_at BETWEEN NOW() - INTERVAL '90 DAY' AND NOW()

A: Solving Strategy

*

*Get the most recent jobs for every law firm

*Filter out most recent jobs, that are younger than 90 days

*Join with table law_firm

Most Recent Job per Law Firm
SELECT DISTINCT ON (law_firm_id) law_firm_id, created_at
FROM job
ORDER BY law_firm_id, created_at DESC

*

*SELECT DISTINCT ON (law_firm_id)

*

*Will return every law_firm_id once

*It will select the first row for a law_firm_id in the order of ORDER BY

*ORDER BY [...] created_at DESC will return the youngest job for the law_firm_id

Postgres Docu: https://www.postgresql.org/docs/current/sql-select.html#SQL-DISTINCT
Filter out Law Firms with Jobs younger than 90 days
Calculate the cutoff date in postgres with INTERVAL: NOW() - INTERVAL '90 days'
SELECT j.*
FROM (
   SELECT DISTINCT ON (law_firm_id) law_firm_id, created_at
   FROM job
   ORDER BY law_firm_id, created_at DESC
) as j
WHERE j.created_at < NOW() - INTERVAL '90 days'

*

*NOW() - INTERVAL '90 days' - calculate cutoff timestamp

*created_at assuming it's a timestamp or timestamp with time zone
Postgres Docu: https://www.postgresql.org/docs/current/functions-datetime.html
Final Query
SELECT law_firms.name as "Law Firm"
FROM law_firms
JOIN (
   SELECT DISTINCT ON (law_firm_id) law_firm_id, created_at
   FROM job
   ORDER BY law_firm_id, created_at DESC
) as j
ON j.law_firm_id = law_firms.id
WHERE j.created_at < NOW() - INTERVAL '90 days'
  AND law_firms.deleted_at IS NULL
  AND law_firms.name not like '%Temp%"'
  AND law_firms.name not like '%Individual%'

*

*Query does not use IN, unfortunately the IN is not very fast in postgres (e.g. see: postgres query with IN is very slow)

*I assumed you wanted all firm that had a job at least once. If you needed all law firms with zero jobs, the query would be wrong.

A: Please try below query:
select "Law Firm" from (
select  law_firms.id, law_firms.name "Law Firm", count(jobs.id) "rec_count"
from law_firms
left join jobs on jobs.law_firm_id = law_firms.id
  where jobs.created_at::date between  (current_date- interval '90 days') and current_date
  and law_firms.deleted_at IS NULL
  and law_firms.name not like '%Temp%"'
  and law_firms.name not like '%Individual%'
  GROUP BY 1,2
    ) tab
    where rec_count=0

In above query the sub query will get the count of all JOB IDs law firm wise in last 90 days. then we can filter the records with zero record count the get the desired result.
Apart from this: always use small letters for your column, table etc. naming. otherwise you have to surround it with " always.


text:
Q: Django template CSS/IMG is "off" in the URL I have
/path/to/my/theme/static/css/frontend.css

which is called by base.html
<link rel="stylesheet" type="text/css" href="{{ STATIC_URL }}css/frontend.css" media="all" />

In which I've got a background for the header:
#header-wrapper
        min-width: 960px;
        height: 150px;
        background: transparent url(img/header-bg.png) repeat-x center bottom;
}

The file is
/path/to/my/theme/static/img

I've run manage.py collectstatic to gather the files and almost everything looks correct except the link generated looks like: http://example.com/static/css/img/header-bg.png
In which the image does not show, because the correct URL is: http://example.com/static/img/header-bg.png
Where am I going wrong??

A: url() is relative to the css file's path: Maybe you could use url(../img/header-bg.png)


text:
Q: Error // Usage: rails new APP_PATH [options] // when running 'rails server' Background info:
I'm using GIT to get a repository of a project with Ruby files in it. The project lives in my SITES folder under home directory on my Mac.
I have Ruby: 1.8.7
I have just upgraded Rails to: 3.0.3
All I am trying to accomplish is to be able to render localhost.com:3000 in my browser of the GIT project I've already downloaded so I can work on it locally.
I ran the command 'rails server' and was returned the message below::
Usage:
  rails new APP_PATH [options]

Options:
      [--skip-gemfile]        # Don't create a Gemfile
  -m, [--template=TEMPLATE]   # Path to an application template (can be a filesystem path or URL)
  -d, [--database=DATABASE]   # Preconfigure for selected database (options: mysql/oracle/postgresql/sqlite3/frontbase/ibm_db)
                              # Default: sqlite3
  -O, [--skip-active-record]  # Skip Active Record files
  -J, [--skip-prototype]      # Skip Prototype files
  -T, [--skip-test-unit]      # Skip Test::Unit files
      [--dev]                 # Setup the application with Gemfile pointing to your Rails checkout
  -r, [--ruby=PATH]           # Path to the Ruby binary of your choice
                              # Default: /System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/bin/ruby
  -G, [--skip-git]            # Skip Git ignores and keeps
  -b, [--builder=BUILDER]     # Path to an application builder (can be a filesystem path or URL)
      [--edge]                # Setup the application with Gemfile pointing to Rails repository

Runtime options:
  -f, [--force]    # Overwrite files that already exist
  -s, [--skip]     # Skip files that already exist
  -p, [--pretend]  # Run but do not make any changes
  -q, [--quiet]    # Supress status output

Rails options:
  -h, [--help]     # Show this help message and quit
  -v, [--version]  # Show Rails version number and quit

Description:
    The 'rails new' command creates a new Rails application with a default
    directory structure and configuration at the path you specify.

Example:
    rails new ~/Code/Ruby/weblog

    This generates a skeletal Rails installation in ~/Code/Ruby/weblog.
    See the README in the newly created application to get going.

A: I got this when upgrading from rails 2 to rails 3 also. Then I ran rails new . to replace all the necessary files and it worked after that.

A: Other issue could be:
You must have deleted bin folder from root directory or some files in it. please recover it back and all will work normally.

A: You're running rails server from the wrong directory. Go INTO the directory containing your app and run the command from there. For example, if you ran rails new thingy, you must be in the thingy directory when you use rails server.

A: Your folder director should be in Gemfile,

A: Usually if you clone a repository or if you are using Docker, files like .gitignore or .dockerignore has instructions for doesn't include bin folder, check in both files and simply remove the line with it.
You can execute rails new in another directory and copy the generated bin folder to your project and then push to your repository.


text:
Q: Close pop up Window Python Selenium I'm trying to access a 'download csv' button on this website using Selenium. https://fplreview.com/team-planner/#forecast_table. When I first click on the site I need to enter a 'Team ID' and click submit which is fine but then a popup ad appears and I cannot close it. I've tried a few approaches mainly using XPATH but it says the button is not there eventhough I add a sleep timer to wait for page to load etc. My end goal is to do this using requests but I'm trying to get it working using Selenium first. Thanks. Below is my code
`
    from selenium import webdriver

    driver = webdriver.Chrome()
    driver.get('https://fplreview.com/team-planner/#forecast_table')

    team_id = driver.find_element_by_name('TeamID')
    team_id.send_keys(123)
    team_id.submit()

    # click close button on ad.
    ad_path = '//*[@id="butt"]/html/body/div[2]/div[3]/div/div/div/div[1]/div/article/div[2]/div/div[18]/div/div/div[3]/button'
    button = driver.find_element_by_xpath(ad_path)
    button.click()

    # export csv
    export_button = driver.find_element_by_id('exportbutton')
    export_button.click()

    driver.quit()

`

The error this generates
`
raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":"//*[@id="butt"]/html/body/div[2]/div[3]/div/div/div/div[1]/div/article/div[2]/div/div[18]/div/div/div[3]/button"}

`

A: I tried myself and got the same error. It seems that the program doesnt wait long enough, for me it crashed before the button even got loaded, which probably caused the error. No matter where you set the webdriver.implicitly_wait('time')it crashes before the button loaded. Id suggest to use an explicit wait as shown here: Here. I sadly didnt come to use it myself, so i cant suggest how to do it exactly, but it seems like this is the proper use for this problem

A: Make sure you are finding the right close button. This finds all elements with the id "close" and clicks the second element. Attempting to close the first element will raise an "ElementNotInteractableException".
button = driver.find_elements_by_xpath("//*[@id='close']")
button[1].click()

Using Explicit Wait & Path to Correct Button
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By

path = "//div[@id='orderModal_popop']/div[@class='modal-dialog']/div[@id='teamcolours']/div[@class='modal-header']/button[@id='close']"

button = WebDriverWait(driver, 10).until(
    EC.element_to_be_clickable(
        (By.XPATH, path)
    )
)

This waits 10 seconds for the correct close button to be clickable.

A: Several waits are needed to make it work:
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
import time

driver = webdriver.Chrome()
driver.get('https://fplreview.com/team-planner/#forecast_table')

team_id = driver.find_element_by_name('TeamID')
team_id.send_keys(123)
team_id.submit()

# wait for the ad to load
WebDriverWait(driver, 30).until(EC.visibility_of_element_located((By.ID, 'orderModal_popop')))

# hide the ad
driver.execute_script("jQuery('#orderModal_popop').modal('hide');")

# export csv
WebDriverWait(driver, 30).until(EC.element_to_be_clickable((By.XPATH, '/html/body/div[2]/div[3]/div/div/div/div[1]/div/article/div[2]/div/button[6]')))
export_button = driver.find_element_by_xpath('/html/body/div[2]/div[3]/div/div/div/div[1]/div/article/div[2]/div/button[6]')
export_button.click()

# wait for download
time.sleep(3)

driver.quit()

A: Hey so i tried fixing the ad issue using this
button = driver.find_element_by_xpath("//*[@id='close']")
sleep(1)
button.click()


text:
Q: Programatically position ImageView in the center of the screen I would like to programatically position ImageView in the center of the screen.
In xml, ImageView is positioned in top left corner. I tried to do it in xml, but it was not possible due to some reasons.
ImageView width is 200dp, and height is 220dp.
This is what I have for now:
        DisplayMetrics dm = getApplicationContext().getResources().getDisplayMetrics();
        float dpHeight = dm.heightPixels / dm.density;
        float dpWidth = dm.widthPixels / dm.density;

        RelativeLayout.LayoutParams lp = (RelativeLayout.LayoutParams) imageView.getLayoutParams();
        lp.leftMargin = lp.leftMargin + (int) ((dpWidth / 2) - 100);
        lp.topMargin = lp.topMargin + (int) ((dpHeight / 2) - 110);

A: To do it programatically, you can do it like this.
// get the center point of the screen
Point point = new Point();
WindowManager manager = (WindowManager) getActivity().getSystemService(Context.WINDOW_SERVICE);
manager.getDefaultDisplay().getSize(point);

int centerX = point.x / 2;
int centerY = point.y / 2;

// set the imageview minus half the width and height so its centered
imageview.setTranslationX(centerX - (imageview.getWidth() / 2));
imageview.setTranslationY(centerY - (imageview.getHeight() / 2));

A: Finally I get the result by programmatic way,
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/RL"
>

<ImageView
    android:id="@+id/IV"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:src="@drawable/faleavatar"

     />

Now goto your Java Page
 ImageView iv=(ImageView)findViewById(R.id.IV);

    DisplayMetrics metrics = getResources().getDisplayMetrics();

    int DeviceTotalWidth = metrics.widthPixels;
    int DeviceTotalHeight = metrics.heightPixels;

    RelativeLayout RelativeLayoutImageCenter=(RelativeLayout)findViewById(R.id.RL);
    RelativeLayoutImageCenter.setPadding(DeviceTotalWidth/4,DeviceTotalHeight/4,0,0);

A: Try this with XML :
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center" >

   <ImageView
       android:layout_height="wrap_content"
       android:layout_width="wrap_content"
       android:src="@drawable/ic_launcher"/>

</LinearLayout>

Output :

A: Where do you embed your imageview in xml? You parent layout needs width and height width match_parent.
If so, your image view needs the attribute layout_gravity="center". This should work in xml.

A: First take RelativeLayout and then add rule to it. And Imageview set inside it. Like below.
RelativeLayout.LayoutParams layoutParams =
(RelativeLayout.LayoutParams)myButton.getLayoutParams();
layoutParams.addRule(RelativeLayout.CENTER_IN_PARENT);
image.setLayoutParams(layoutParams);

A: you could do like this :
        LinearLayout.LayoutParams myLayout = new LinearLayout.LayoutParams(
        LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
        myLayout.gravity = Gravity.CENTER;
        imageView.setLayoutParams(myLayout);

A: Try this one:
        The xml code is
    <?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:orientation="vertical" android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/relativeLayout"
       >
    </RelativeLayout>

And in Class file try this:
   RelativeLayout layout=(RelativeLayout)findViewById(R.id.relativeLayout);
        ImageView imageView=new ImageView(this);
        RelativeLayout.LayoutParams params=new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT,RelativeLayout.LayoutParams.WRAP_CONTENT);
        params.width=200;
        params.height=200;
        params.addRule(RelativeLayout.CENTER_IN_PARENT);
        imageView.setLayoutParams(params);
        imageView.setImageResource(R.mipmap.ic_launcher);
        layout.addView(imageView);


text:
Q: How to search and replace string in ruby? I tried the below code to search the string pattern "]]>*/-->" and replace it with "*/-->" using gsub function.
but instead of replacing whole string. it replaces character wise..
File.open('reporttestphp2.xml', 'r+') do |f1|
  while line = f1.gets
    f1.puts line.gsub("]]>*/-->","*/-->")
  end
end

How can I replace the whole string pattern in Ruby?

A: The gsub works fine. You just need to read the file in a different way:
text = File.read("reporttestphp2.xml").gsub("]]>*/-->","*/-->")
File.open("out.xml", "w").write(text)

I hope, that helps.

A: What do you mean by whole string pattern? If you want to use regular expressions, they are written beetween / characers in ruby, e.g. /\w+/
Examples

A: To do this using a ruby regex constant,
gsub(/]]>\*\/-->/, '*/-->')


text:
Q: создать программу, которая спрашивает "сколько вам лет" подскажите пожалуйста, где ошибка. не могу понять. язык с++
#include <stdio.h>
#include <iostream>
#include <string.h>
#include <math.h>
using namespace std;

int main()
{

    printf() << ("How old are you?");
    string myAge;
    scanf >> (myAge);
    printf << ("you are " << myAge << " years old");
    return 0;

}

A: #include <stdio.h>

int main()
{
    printf("How old are you? ");
    int myAge;
    scanf("%d",&myAge);
    printf("You are %d years old",myAge);
}

A: Cмотри, ты совместил несколько типов ввода-вывода
нужно либо
printf("");
scanf();

либо
cout << "";
cin >> ;

если делать прогу через cout, то она будет выглядеть +- вот так
#include <iostream>

using namespace std;

int main()
{

    cout << "How old are you? ";
    string myAge;
    cin >> (myAge);
    cout << "you are " <<  myAge << " years old";
    return 0;

}


text:
Q: Solution for React app implementation of client and server side rendering in an existing app? I have a React app that serves all static files (including React js) from a CDN and uses a Nodejs server as an API.
Now I want to implement server side rendering.
lets say as an example the app is a sale board for cars, where users can publish their car for sale. each car ad will have a "car page" with its details images etc..
So for each car ad to be indexed by search engines, a server side implantation is needed.
Here are the options tested/came to mind:

*

*Use one of the html generators libraries like react-static or react-snap or react-snapshot. Those don't do the trick because pages needs to by updated dynamically, so if user updates his ad the pages needs to be updated and not on the next build. (building on each update and pushing to a CDN seems not right).

*forget about the CDN and move all requests to the server like in this example - How to server-side render React, hydrate it on the client and combine client and server routes. At this point the app is pretty large and changing such a significant deployment aspect will be a shame + don't want to lose CDN advantages.

*Creating a new service server that will be used only for delivering those pages (viewing pages is not behind login). Then deploying Nginx for rerouting traffic with pages path to the server and all other request to the api server. Have not figured out how to combine it with a CDN yet...
Surly Im missing on other solutions but this was what came to mind after some research
Any suggestions and thoughts would be welcomed


text:
Q: Upload multiple videos one by one Can anyone help me to upload multiple videos with a static name.I want to upload multiple videos one by one, which means if the user can upload any video of any type.
<form action="" method="post" enctype="multipart/form-data">
  <input name="vv" type="file" id="file"/>
  <input type="submit" value="UPLOAD" name="submit" id="upload"  style=" background:#03d5fb; color:#00264a; font-size:26px; margin-top:4%; width:23%;" />

 </form>

 <?php
      $resultt=(mysql_query("Select * From aa where email  ='$_SESSION[login_user]'"));
      $rows= (mysql_fetch_array($resultt, MYSQL_ASSOC));
$id=$rows['id'];
      if (isset($_POST['submit'])) {
         if(!is_dir("images/videos".$id.'/')) {
                mkdir("images/videos".$id.'/');
                $filess = $_FILES['vv']['name'];
                $tmppath = $filess ['tmp_name'];
                $target_dir = "images/videos".$id.'/';
                $random=rand(0000, 9999);

                  move_uploaded_file($tmppath, $target_dir.'video'.$random.'.mp4');
                          echo "uploaded ";
           }
           else
           {
                 $filess = $_FILES['vv']['name'];
                 $tmppath = $filess ['tmp_name'];
                 $target_dir = "images/videos".$id.'/';
                 $random=rand(0000, 9999);

                 move_uploaded_file($tmppath, $target_dir.'video'.$random.'.mp4');
                      echo "uploaded ";
            }
    }
 ?>

This is sample code i am trying with no luck. Please give me some solution.
thanks for any help.

A: To allow user to select and upload multiple files, following are some simple tips for code

*

*Input name must be be defined as an array i.e. name="inputName[]"

*Input element must have multiple="multiple" or just multiple. To know
more about this, check the link

*In your PHP file use the syntax
$_FILES['inputElemName']['param'][index]
Now lets come to your code
HTML
<form action="" method="post" enctype="multipart/form-data">
    <input type="file" id="file" name="file[]" multiple="multiple"/>
    <input type="submit" value="UPLOAD" name="submit" id="upload"  style=" background:#03d5fb; color:#00264a; font-size:26px; margin-top:4%; width:23%;" />
</form>

PHP
<?php
    if (isset($_POST['submit']))
    {
        $result = mysql_query("Select * From aa where email = '".$_SESSION[login_user]."'");

        if($result)
        {
            $row = mysql_fetch_array($result);
            $id = $row['id'];

            if(!is_dir("images/videos".$id.'/'))
            {
                mkdir("images/videos".$id.'/');
            }
            $target_dir = "images/videos".$id;

            // setup an array to check errors at the time of file upload
            $errors = array();

            //Loop through each file
            for($i=0; $i<count($_FILES['file']['name']); $i++)
            {
                // set the array of allowed extensions
                $allowed =  array('mp4', 'mkv');

                // extrach the file extension and check if it is valid
                $ext = pathinfo($_FILES['file']['name'][$i], PATHINFO_EXTENSION);
                if(!in_array($ext,$allowed))
                {
                    $errors[] = "Invalid fiel extension.";
                }
                if(empty($errors))
                {
                    // make parts of file name to append timestamp to them to avoid uploading of files with same name
                    $path_parts = pathinfo($_FILES["file"]["name"][$i]);

                    $image_path = $path_parts['filename'].'_'.time().'.'.$path_parts['extension'];

                    //Setup our new file path
                    $newFilePath = $target_dir.'/'.$image_path;

                    //Upload the file into the temp dir
                    if(move_uploaded_file($_FILES["file"]["tmp_name"][$i], $newFilePath))
                    {
                        //Handle other code here
                    }
                }
                else
                {
                    print_r($errors);
                }
            }
            if(empty($errors))
            {
                echo "Success";
            }
        }
        else
        {
            echo "Error while fetching records ".mysql_error();
        }
    }
 ?>

Hope this helps to get your work done.


text:
Q: Como ler um arquivo JSON que está dentro de um pacote? Preciso der um arquivo no caso *.JSON. Entendo que existe uma biblioteca para isso no caso utilizo a json-simple-1.1.1. Como é necessário fazer a leitura do arquivo primeiro e depois trabalhar com ele.
Minha dúvida é a seguinte:
Guardo o arquivo file.json dentro de um pacote com.app.json e preciso acessar esse arquivo.
Qual seria o método mais eficiente para acessar esse arquivo dentro do pacote?
Observação:
Isso deve valer para arquivos .json, .txt, .xml e outros.

A: Me parece que o pacote onde estarão os arquivos será sempre o mesmo. Desta forma, basta utilizar o código abaixo:
Reader in = new InputStreamReader(getClass().getResourceAsStream("/com/app/json/file.json") );
Object o = JSONValue.parse(in);

Caso contrário, você pode escrever uma função que receba o nome do pacote e transforme para um caminho válido dentro do classpath.
Abraços


text:
Q: Creating functions from output of other calculations Apologies in advance if the title is vague, I'm not really sure what to call this.
I have a function (call it 'foo') that generates a largeish polynomial, and it is natural to make the variables be
x[1],x[2],x[3]

and so on, so I get a polynomial, e.g.
x[1]^2 x[2]+x[3]

Now, I'd like to store this as a function
bar[x[1]_,x[2]_,x[3]_]:=foo[whatever]

This doesn't work, of course, but if the variables were e.g.
x1,x2,x3

etc. instead, I could do
bar[x1_,x2_,x3_]:=foo[whatever]

and that would work. I figured some replacement rule would work, e.g.
rule={x_[i_] :> ToExpression@(ToString[x] <> ToString[i])}

which looks like it should work:
x[1]^2 x[2]+x[3]/.rule

gives output
x1^2 x2 + x3

but if I define
bar[x1_,x2_,x3_]:=foo[whatever]/.rule

then
bar[1,2,3]

outputs
x1^2 x2 + x3

instead of 5, which it should.
Obviously, there is something I don't really understand about the way Mathematica handles variable names, and what I'm trying to do to fix this is probably too naive. Is there some better way to get around this problem?
Thanks in advance for any help.

A: One possibility would be to create a pure function from your multivariate polynomial with indexed variables:
bar = Function[Evaluate[x[1]^2 x[2] + x[3] /. x -> Slot]]
   #1^2 #2 + #3 &

bar[1, 2, 3]
   5

A: This works for polynomials in more than one variable set ( x[n_] ... y[n_] ....)
a = y[1] x[1]^2 x[2] + x[3] + y[3]

rule = x_[i_] :> Symbol[ToString[x] <> ToString[i]]
makefun[a_] := Function[Evaluate[Cases[a, x_[i_], Infinity] /. rule], Evaluate[a /. rule]]

s = makefun[a]

s[1, 2, 3, 4, 5]
(* 54 *)

s
(* Function[{x3, x1, x2, y1, y3}, x3 + x1^2 x2 y1 + y3] *)


text:
Q: Velocity of a curve given by parametric equations In standard Cartesian equations, $\frac{dy}{dx}$ is the velocity function because it's the derivative of position.
$$\frac{dx}{dt} = \sin^{-1}\left(\frac{t}{1 + t}\right) \space\space\space\space\space\space\space\space \frac{dy}{dt} = \ln(t^{2} + 1)$$
Given the derivatives of the parameters, why must one calculate the magnitude of a vector at a certain time $t$ to calculate speed? Can't you just divide $\frac{dy}{dt}$ by $\frac{dx}{dt}$ to get $\frac{dy}{dx}$ which is the slope and velocity at a given time. Then take the absolute value for speed.

A: The problem with reasoning is not with your formulas but your intuition. If we have a particle whose position is given by $x(t)$, its derivative $x'(t)$ is the velocity. If we have a curve in the plane given by $y=f(x)$, the slope of the curve is given by $dy/dx$. The problem is that this slope is not the 'velocity' of this curve. It gives the slope of the curve at a point, which gives the direction a particle traveling along this curve is traveling at that moment, not the speed of the particle at that point. Intuitively, you can't think about speed for a curve given by $y=f(x)$ because there is no time variable $t$. Using parametric equations however, we introduce this value of $t$, given a speed and a direction to the curve.
Simply put, $dy/dx$ is not the slope and the velocity of a curve at a given point, just the slope.

A: $\frac{dy}{dx} = \frac{\frac{dy}{dt}}{\frac{dx}{dt}}$ is valid as you said.
As for the context, it's usually not a matter of why but more of what you are given and what you must do with it. Often, it may be the case that $\frac{dx}{dt}$ and $\frac{dy}{dt}$ are easier to calculate or find than directly going for $\frac{dy}{dx}$. This is especially so if you're just given the parametric equations.


text:
Q: Adding a list of objects to my Firestore collection I have a list of a model of mine called GroupMemberEntity.
I want to set that list into my collection, each one getting its own unique ID using UUID.
My current implementation is the following -
suspend fun addGroupMembers(
        groupId: String,
        users: List<GroupMemberEntity>
    ) = suspendCoroutine<ResponseHandler.Resource<Any>> { continuation ->
        var insertCounter = 1
        users.forEach { entity ->
            FIRESTORE_DATABASE.collection(ACTIVITIES_COLLECTION)
                .document(UUID.randomUUID().toString())
                .set(entity)
                .addOnSuccessListener {
                    insertCounter++
                    if (insertCounter != users.size) return@addOnSuccessListener
                    continuation.resume(responseHandler.handleSuccess())

                }
                .addOnFailureListener { exception ->
                    continuation.resume(responseHandler.handleException(exception))
                }
        }
    }

I have a feeling this can be improved by not using the forEach loop, but I'm not sure how. doing a network call in a loop seems like a bad idea in general.
Any advice would be helpful.

A: If you want each entity to have its own document, than you need to use the for-each approach:
suspend fun addGroupMember(groupId: String, user: List<GroupMemberEntity>) {
   users.forEach {
       FIRESTORE_DATABASE.collection(ACTIVITIES_COLLECTION)
                .document(UUID.randomUUID().toString())
                .set(entity)
                .await()
   }
}

Another, maybe easier approach would be to just post the entire list in one document. You can later retrieve or (I think) query within this document for a specific field. For this, I would add a uuid to your GroupMemberEntity. But I am not 100% sure if this works.


text:
Q: Disabling modules of PayaraMicro at startup Is it possible to disable internal modules at startup, for example,
Hazelcast, to allow a faster boot of the app? I need this in development time.

A: Hazelcast can be easily disabled by the --nocluster command line option. There's no easy way to disable other services on command line - though most of them aren't started unless deployed applications need them.
When disabling Hazelcast, note that some services depend on it and wouldn't work. For example distributed CDI event bus, persistent timers, integrated JCache resources.


text:
Q: RxSwift - UICollectionView does not update after updating I have a UITabBarController with 2 controllers.

*

*In the first VC user have a list of articles. A user can add some article to favourite (realm database)

*The second VC it is a list with realm query (favourite article).
When 2 controllers created (user tap to both of them), and in the first VC add article to favourite in the second collectionView does not show new item.

My favouriteVC collectionView binding
 private func setupBinds(){
    self.favArticleCollectionView.register(UINib(nibName: "PreviewItemVCell", bundle: nil), forCellWithReuseIdentifier: PreviewItemVCell.identifier)

    viewModel
        .articlesSubject
        .observeOn(MainScheduler.instance)
        .bind(to:
        self.favArticleCollectionView.rx.items(cellIdentifier: PreviewItemVCell.identifier, cellType: PreviewItemVCell.self)) { (item, article,cell) in
            cell.article =  article
    }.disposed(by: disposeBag)

and my favouriteViewModel which make a query from db
class FavouriteViewModel {
let articlesSubject: PublishSubject<[ArticleModel]> = PublishSubject()

func fetchDateFromDb(){
    print(Realm.Configuration.defaultConfiguration.fileURL!)
    let articleList = DatabaseManager.shared.getAllArticle().toArray()

    articlesSubject.onNext(articleList)
}}

Problem: When the controller has created, he does not update. How I can update it?

A: The problem was with my custom layout for collection view.
It is the right answer
enter link description here


text:
Q: is there a way to parse or read the directory as a file? This might be sort of trivial question but in any case, i was wondering if there is a way to read a directory as a file which one will be using open(), close(), read() instead of opendir(), closedir(), readdir()...
I might be wrong, however, i'm thinking that this can speed-up directory traversing.
Thanks

A: This actually was how Unix directories worked, originally.  The directory really was just a plain file like any other, and you read out a flat array of (IIRC) 16-byte records containing a 4 byte inode number and a 12 byte file name.  opendir() and readdir() were simply library functions around that interface.
But starting with Sun's introduction of VFS in the mid-80's, there wasn't just one filesystem anymore.  opendir and readdir became system calls instead, and the ability to read the "raw" content of a directory disappeared.
In any case, the filesystem authors have worked very (!) hard to make their code fast.  There's nothing you can do externally to "speed up" directory traversal at this level.  Try using fewer files, I guess.

A: No. Unless you're reading from the output of ls.


text:
Q: AWS Lambda function missing request body from API Gateway proxy integration I have an API Gateway method which needs to forward requests to a Lambda proxy integration. The file I'm POSTing (via Postman) is a CSV, which is processed and returns a list of objects.
The API resource/method etc. values were set automatically as part of the Lambda function creation (via the AWS console).
The (partial) lambda
public async Task<APIGatewayProxyResponse> ProcessReviews(
    APIGatewayProxyRequest request,
    ILambdaContext context)
{
    var response = new APIGatewayProxyResponse
    {
        Headers = new Dictionary<string, string> { { "Content-Type", "application/json" } },
        IsBase64Encoded = true,
    };

    var config = new CsvConfiguration(CultureInfo.InvariantCulture)
    {
        PrepareHeaderForMatch = args => CultureInfo.CurrentCulture.TextInfo.ToTitleCase(args.Header)
    };

    var streamReader = new StreamReader(request.Body);
    // Fails here as the request.Body is always null

The method works locally when called via Postman so it has to be a problem with settings for API Gateway, the Lambda, or the integration.
I've tried adding various Binary Media Types to the API settings and Postman headers, such as application/octet-stream, text/csv, and wildcard */* to see if that's the issue, but with no luck and I've not been able to find anything to indicate what else I might be missing from the configuration.
IIRC the only other settings I changed on API Gateway were the addition of a model, and setting it as the method's response object (application/json).
Any ideas where I might be going wrong?


text:
Q: Prevent $.ajax from encoding forward slashes I have an API I am working with, and they expect a certain parameter to be /on/ or /off/. If I use the standard jQuery $.ajax it encodes to %2Fon%2F which fails on the API. Since I don't have access to the API to make it decode, how can I prevent jQuery from encoding the slashes?
The API uses GET, and here is a sample call:
$.ajax({
    url: "api.website.com",
    data: {id: id, stuff: stuff, device: device},
    type: "GET",
    dataType: "html"
})

A: jQuery will try to encode the query string because that's what you are supposed to do. So those / characters are going to get encoded. The only way around it is to build the query string yourself appended to the url. Luckily, or maybe not, you only actually need to do that for the parameters that are going to have the offending characters (stuff in your example):
$.ajax({
    url: "http://api.website.com?stuff=" + stuff,
    data: {id: id, device: device},
    type: "GET",
    dataType: "html"
})


text:
Q: How do I make my Sprite appear in my window? I have made an enemy sprite within my game, however it is not displayed on the screen. I am wondering how I would be able to make it appear?
Tried updating the pygame display in the class but it still won't show the image. I plan on making the sprite appear in order to allow it to move to the end of the grid line (horizontally), then shift down vertically when it reaches the end of a horizontal point.
import pygame
pygame.init()

window = pygame.display.set_mode((650, 630))

pygame.display.set_caption("PeaShooters")

avatar = pygame.image.load('Sprite 1 Red.png')
background = pygame.image.load('Bg.jpg')
white = (255, 255, 255)

class player(object):
    def __init__(self, x, y, width, height, shots):
        self.x = 300
        self.y = 500
        self.width = 40
        self.height = 60
        self.vel = shots

def drawGrid():
    window.blit(background, (0,0))
    window.blit(avatar, (av.x, av.y))
    pygame.draw.line(window, white, [50,50], [50, 600], 5)
    pygame.draw.line(window, white, [50,50], [600, 50], 5)
    pygame.draw.line(window, white, [600,600], [600, 50], 5)
    pygame.draw.line(window, white, [50,600], [600, 600], 5)
    pygame.draw.line(window, white, [50,450], [600, 450], 5)
    for bullet in bullets:
        bullet.draw(window)
    pygame.display.update()

class shots(object):
    def __init__(self, x, y, radius, colour):
        self.x = x
        self.y = y
        self.radius = radius
        self.colour = colour
        self.vel = shots

    def draw(self, window):
        pygame.draw.circle(window, self.colour, (self.x,self.y), self.radius)

class enemy(object):
    enemy = pygame.image.load('Sprite 3 Red.png')
    pygame.display.update()

    def __init__(self, x, y, width, height, end):
        self.x = x
        self.y = y
        self.width = width
        self.height = height
        self.end = end
        self.path = [self. x, self.end]
        self.vel = 4

    def draw(self,window):
        self.move()
        pass

    def move(self):
        pass

av = player(300, 500, 40, 60, 9)
bullets = []
running = True
while running:
    pygame.time.delay(100)

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

    for bullet in bullets:
        if bullet.y < 600 and bullet.y > 70:
            bullet.y -= 8
        else:
            bullets.pop(bullets.index(bullet))

    keys = pygame.key.get_pressed()

    if keys[pygame.K_w] and av.y > 440:
        av.y -= av.vel

    if keys[pygame.K_a] and av.x > 65:
        av.x -= av.vel

    if keys[pygame.K_s] and av.y < 535:
        av.y += av.vel

    if keys[pygame.K_d] and av.x < 530:
        av.x += av.vel

    if keys[pygame.K_SPACE]:
        if len(bullets) < 5:
            bullets.append(shots(round(av.x + av.width//2), round(av.y + av.height//2), 6, (0,0,0)))

    drawGrid()

window.blit(avatar, (x,y))

pygame.quit()

I expect the avatar to appear on the screen so I can allow it to move.

A: All drawing should be done in the while loop. Or you call directly the window.blit function on the various sprites, or you wrap it in a sprite method which is called during the loop (I see you have a draw() method but right now it does nothing). Choose one way and follow that. I personally prefer the second one, it's more object oriented, but it is my opinion.
And remember to clear the previous position if you want to give a sense of motion.
display.update() should be called once per iteration, usually at the end, after all the sprites have been blit.
Your enemy does not appear because you never blit it's image. Actually, you never create an enemy, you have defined the class only.
So first create an enemy adding a line such that en = enemy(ex, ey, w, h, end). ex and ey here should be the position of the enemy on the screen, choose what you prefer. w and h the width and height of the image. end I do not know (your class, you added it, you should know what is its purpose). You can add this line just after you create the avatar.
Then remove the display.update() from the class, and add a call window.blit(en, (en.x, en.y)) in the while loop. Or in drawGrid(), which actually is drawing everithing and not the grid only.
To move the enemy, you should edit its position (en.x and en.y) in the while loop as you do for the avatar, but not in response to a key press. Just set some sort of path. At each iteration, the enemy coordinates should change to follow this path, something like en.x += en.vel or whatever. The real path may be more complex, but this is up to you. The logic is: change the enemy coordinate each iteration of the loop.


text:
Q: HDP on Windows Server 2012 R2 Single Node Installation Error I am trying to install Hortonworks Data Platform (HDP) 2.2.6.0 for Hadoop on Windows Server 2012 R2, by following the Quick Start for a Single Node, but I am failing.
Settings
I am using Virtual Box for the Windows Server 2012 R2. Java, Python, etc. are set. I am running from the Administrator account. I have run the installer using cmd.exe as Admin.
I un-checked "Install Ranger" from the installer. I also ignored this part of the installation (by also un-checking LZO codec in the installer):

When deploying HDP with LZO compression enabled, add the following three files (in the HDP for Windows Installation zip) to the directory that contains the HDP for Windows Installer and the cluster properties file:
  - hadoop-lzo-0.4.19.2.2.6.0-2060
  - gplcompression.dll
  - lzo2.dll

The cluster proprieties txt can be found here: https://pastebin.mozilla.org/8838912.
Error
From the install log, I see this error:
CREATE-USER: Creating user hadoop
CREATE-USER: Setting password for hadoop
HDP-PS FAILURE: Write-Log : CREATE-USER FAILURE: Exception calling "SetInfo" with "0"
HDP-PS FAILURE: argument(s): "The password does not meet the password policy requirements.
HDP-PS FAILURE: Check the minimum password length, password complexity and password history
HDP-PS FAILURE: requirements.
HDP-PS FAILURE: "
HDP-PS FAILURE: At C:\HadoopInstallFiles\HadoopPackages\hdp-2.2.6.0-winpkg\scripts\create_hadoo
HDP-PS FAILURE: p_user.ps1:220 char:2
HDP-PS FAILURE: +     Write-Log $_.Exception.Message "Failure" $_
HDP-PS FAILURE: +     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
HDP-PS FAILURE:     + CategoryInfo          : NotSpecified: (:) [Write-Error], WriteErrorExcep
HDP-PS FAILURE:    tion
HDP-PS FAILURE:     + FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorExceptio
HDP-PS FAILURE:    n,Write-Log
HDP-PS FAILURE:
HDP FAILURE: Command "C:\HadoopInstallFiles\HadoopPackages\hdp-2.2.6.0-winpkg\scripts\create_hadoop_user.ps1 -username hadoop -passwordBase64 **** failed with exit code  1. Output is  "CREATE-USER: Logging to existing log C:\HadoopInstallFiles\HadoopSetupTools\hdp-2.2.6.0.winpkg.install.log CREATE-USER: Logging to C:\HadoopInstallFiles\HadoopSetupTools\hdp-2.2.6.0.winpkg.install.log CREATE-USER: HDP_INSTALL_PATH: C:\HadoopInstallFiles\HadoopPackages\hdp-2.2.6.0-winpkg\scripts CREATE-USER: HDP_RESOURCES_DIR: C:\HadoopInstallFiles\HadoopPackages\hdp-2.2.6.0-winpkg\resources CREATE-USER: UserGroup not provided. Using default UserGroup HadoopUsers. CREATE-USER: Creating user hadoop CREATE-USER: Setting password for hadoop Write-Log : CREATE-USER FAILURE: Exception calling "SetInfo" with "0"  argument(s): "The password does not meet the password policy requirements.
 Check the minimum password length, password complexity and password history
 requirements.
 "
 At C:\HadoopInstallFiles\HadoopPackages\hdp-2.2.6.0-winpkg\scripts\create_hadoo
 p_user.ps1:220 char:2
 +     Write-Log $_.Exception.Message "Failure" $_
 +     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     + CategoryInfo: NotSpecified: (:) [Write-Error], WriteErrorExcep
    tion
     + FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorExceptio
    n,Write-Log
"
At C:\HadoopInstallFiles\HadoopPackages\hdp-2.2.6.0-winpkg\resources\Winpkg.Utils.psm1:130 char:9
+         throw "Command `"$command`" failed with exit code  $captureExitCode. Out ...

The full install log can be found here: https://pastebin.mozilla.org/8838911
Same problem. Different ppl
I saw this problem already on other forums or this one. I have also tried a complex password, I changed the policy in Widows. Nope..
Help
Can you help get rid of this error and continue the installation of HDP?


text:
Q: Autocomplete для vim Подскажите плагин который будет делать автокомплит по проекту, не просто по языку, к примеру я создал класс, и когда его использую то vim будет подсказывать медоты и свойства это класса

A: Упомянутый выше
https://github.com/ycm-core/YouCompleteMe
достаточно монструозный и автодополняет всё ко всему.
Для начала попробуйте просто в .vimrc прописать
au FileType php setl ofu=phpcomplete#CompletePHP

или какой вам язык нужен и вызывать по

crtl n

Лучше подходить со стороны языка и искать комплит для него.
Так же не плохой плагин для JS https://github.com/ternjs/tern_for_vim
node и npm должны быть установленны в системе
В любом случае если вы определите объекты через фасад или свойства будут содержать объекты переопределённые по родителю или трэйту, то никакая автокомплитка вам не поможет.

A: YouCompleteMe
Поддержка многих языков, + того что ты хочешь


text:
Q: Performance issues with JBoss 7.1.1 and ActiveMQ
*

*We upgraded our application from "JBoss 5.1 with JBoss Messaging" to "JBoss 7.1.1 Final with ActiveMQ 5.8.0". We were expecting performance improvement but we saw 20 to 30% of performance loss.

*We are using JDBC persistence for ActiveMQ and our MDB's do good amount of DB transactions which slows them down. But this set up is same for JBoss 5.1 and JBoss 7.1.1

*When we configure Active MQ as JCA using activemq.rar we see around 50 % loss in performance.

*When we configure Active MQ embedded we still see around 50 % loss in performance.

*When we run ActiveMQ external as standalone the performance loss is around 15 to 20 %.

*We have also tested ActiveMQ and JBoss 5.1 combination and we don't see any performance loss.

*We searched through forums and JBoss bug tracking system and we don't see any issue of this type reported against JBoss 7.1.1 or fixed for JBoss 7.2
Are we missing something? We need to make this work with JBoss 7.1.1
Any pointers will be helpful
Thanks in Advance
Nitesh


text:
Q: Can I create a domain-wide singleton service in Weblogic? We currently have a clustered Weblogic setup for several pieces of our application to reach the usual guarantees in load balancing, fail-over, and so on. Recently, we've added a singleton service implementing weblogic.cluster...SingletonService, which does the job it was designed for, but it seems not the job we require of it. In the current setup there are multiple clusters under the same domain that would need to access the singleton service, but it seems that this does not work.
How can we set up a singleton service domain-wide, that is, for multiple clusters concurrently?
Sanity test: is our observation that the Weblogic SingletonService can not be used domain-wide correct?

A: The documentation states

"A singleton service is a service running on a managed server that is
  available on only one member of a cluster at a time"

so yes, your sanity test is ok.
There isn't any domain-wide singleton functionality in WebLogic. I can imagine some workarounds:

*

*Using JMX to inspect which servers are running, retrieving the server name from System properties and running your logic only if the first running managed server name and the current server name matches.

*Setup a domain wide Coherence cluster, and compare the local member with the oldest member of the cluster and use that to decide which server is the leader and runs your logic.

*Setup some horrible semaphore logic using the JNDI tree, which is a domain wide resource.


text:
Q: Simple XML Question Alright, using my XML editor to check the validation I'm getting "Validation stopped at line 2, column 8: no declaration found for element 'Staff'. Does anyone know why this is?
Also, every three staff members are of a different type and each type include different elements (Adjunct staff members only have email, name, position for instance, while FullTime types have information for all of the elements.) Is it bad form to have element data left blank? If they're StaffMembers of a different type, is it alright to get rid of the extra elements or does every StaffMember need the same elements all the way through? Thanks!
<Staff>

    <StaffMember type="FullTime">
        <Name>Richard Baskerville</Name>
        <Position>Professor</Position>
        <OfficePhone>(404) 413-7362</OfficePhone>
        <Building>Robinson College</Building>
        <Room>919</Room>
        <URL>www.cis.gsu.edu/~rbaskerv</URL>
        <Email>rbaskerville@cis.gsu.edu</Email>
        <DegreeInfo>Ph. D., M.S., B.S.</DegreeInfo>
        <Research> Information systems security, interaction of information systems and organizations, qualitative research methods,      diffusion of IT innovations, knowledge management</Research>
    </StaffMember>

    <StaffMember type ="FullTime">
        <Name>Michael Gallivan</Name>
        <Position>Associate Professor</Position>
        <OfficePhone>(404) 413-7363</OfficePhone>
        <Building>Robinson College</Building>
        <Room>935</Room>
        <URL>www.cis.gsu.edu/~mgalliva</URL>
        <Email>mgalliva@cis.gsu.edu</Email>
        <DegreeInfo>Ph. D., M.B.A., M.P.H., B.A.</DegreeInfo>
        <Research> IT human resource management, management of IT outsourcing, adoption and diffusion of innovations, organizational learning from innovations </Research>
    </StaffMember>

      <StaffMember type ="FullTime">
        <Name>Sidney Harris</Name>
        <Position>Professor</Position>
        <OfficePhone>(404) 413-7017</OfficePhone>
        <Building>Robinson College</Building>
        <Room>427</Room>
        <URL>www2.gsu.edu/~wwwseh/</URL>
        <Email>sidneyharris@gsu.edu</Email>
        <DegreeInfo>Ph. D., M.S., B.S.</DegreeInfo>
        <Research> Strategic management of technology, global practices in technological innovation and management, regional studies on China and Asia culture of high performance organization</Research>
    </StaffMember>

      <StaffMember type ="Adjunct">
        <Name>Arash Akhlaghi</Name>
        <Position>Adjunct Professor</Position>
        <OfficePhone></OfficePhone>
        <Building></Building>
        <Room></Room>
        <URL></URL>
        <Email>aakhlaghi1@student.gsu.edu</Email>
        <DegreeInfo></DegreeInfo>
        <Research></Research>
    </StaffMember>

    <StaffMember type="Adjunct">
        <Name>Catherine Baird</Name>
        <Position>Adjunct Professor</Position>
        <OfficePhone></OfficePhone>
        <Building></Building>
        <Room></Room>
        <URL></URL>
        <Email>cbaird@cis.gsu.edu</Email>
        <DegreeInfo></DegreeInfo>
        <Research></Research>
    </StaffMember>

    <StaffMember type="Adjunct">
        <Name>David Bloomquist</Name>
        <Position>Adjunct Professor</Position>
        <OfficePhone></OfficePhone>
        <Building></Building>
        <Room></Room>
        <URL></URL>
        <Email>dbloomquist@cis.gsu.edu</Email>
        <DegreeInfo></DegreeInfo>
        <Research></Research>
    </StaffMember>

    <StaffMember type="Staff">
        <Name>Desiree Plummer</Name>
        <Position>PC System Specialist</Position>
        <OfficePhone>(404) 413-7440></OfficePhone>
        <Building>Robinson College</Building>
        <Room>908</Room>
        <URL></URL>
        <Email>dplummer@cis.gsu.edu</Email>
        <DegreeInfo></DegreeInfo>
        <Research></Research>
    </StaffMember>

    <StaffMember type="Staff">
        <Name>Walter Rich</Name>
        <Position>Manager, CIS External Affairs</Position>
        <OfficePhone>(404) 413-7398></OfficePhone>
        <Building>Robinson College</Building>
        <Room>929</Room>
        <URL></URL>
        <Email>wrich@cis.gsu.edu</Email>
        <DegreeInfo></DegreeInfo>
        <Research></Research>
    </StaffMember>

    <StaffMember type="Staff">
        <Name>James Sneed</Name>
        <Position>Information Technology Department Manager</Position>
        <OfficePhone>(404) 413-7383></OfficePhone>
        <Building>Robinson College</Building>
        <Room>907</Room>
        <URL></URL>
        <Email>jsneed@cis.gsu.edu</Email>
        <DegreeInfo></DegreeInfo>
        <Research></Research>
    </StaffMember>

  <StaffMember type="Ph.D">
        <Name>Anouck Adrot</Name>
        <Position></Position>
        <OfficePhone>(404) 413-7389></OfficePhone>
        <Building>Robinson College</Building>
        <Room>910</Room>
        <URL></URL>
        <Email>aadrot1@student.gsu.edu</Email>
        <DegreeInfo></DegreeInfo>
        <Research></Research>
    </StaffMember>

    <StaffMember type="Ph.D">
        <Name>Chad Anderson</Name>
        <Position></Position>
        <OfficePhone>(404) 413-7389></OfficePhone>
        <Building>Robinson College</Building>
        <Room>910</Room>
        <URL></URL>
        <Email>canderson32@comcast.net</Email>
        <DegreeInfo></DegreeInfo>
        <Research></Research>
    </StaffMember>

    <StaffMember type="Ph.D">
        <Name>Mathieu Chauvet</Name>
        <Position></Position>
        <OfficePhone>(404) 413-7389></OfficePhone>
        <Building>Robinson College</Building>
        <Room>910</Room>
        <URL></URL>
        <Email>mchauvet1@student.gsu.edu</Email>
        <DegreeInfo></DegreeInfo>
        <Research></Research>
    </StaffMember>

</Staff>

A: This XML validator doesn't give any error with your xml.
Anyway, if you use a schema or a DTD to validate, you may have an error (if it doesn't correspond to the specification).
For your second point, you can have empty node but the use depends on your needs, on the specification if you use one and the code that will use this xml. You can delete them if you're not using a schema or a DTD like I suspect or if the code to parse it afterward take care of it.

A:
"Validation stopped at line 2, column
  8: no declaration found for element
  'Staff'. Does anyone know why this is?

Because you have not declared a schema (XML Schema, DTD, RNG, etc.) against which to validate. I don't know what XML editor you're using ... Apparently you told it to validate, and it's trying to say that it's unable to validate because there is no schema to validate against. That does not mean your XML is invalid: instead it means that validity has no meaning for your XML (until you associate a schema with it).


text:
Q: How to make Dash dropdown options depend upon another DCC inputs selection Lets say I have some code as follows below:
import pandas as pd
import plotly.express as px
import dash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output
import helper
from datetime import date

app = dash.Dash(__name__)

# import data

app.layout = html.Div(children=[

    dcc.Dropdown(
        id='slct_dataset',
        options= ['dataset1', 'dataset2'],
        placeholder="Select a dataset",
        multi=False,
        style={'width': '40%'}
                 ),

    dcc.DatePickerRange(
        id='slct_date',
        #todo make: below below depend upon dataset selection
        min_date_allowed=date(1980, 1, 1),
        max_date_allowed=date(2021, 1, 1),
        initial_visible_month=date(2017, 8, 5),
        end_date=date(2017, 8, 25)

    ),

    html.Div(id='output_container', children=[], style={
        'textAlign': 'center'
    }),
    html.Br(),

    dcc.Graph(id='my_graph', figure={})

])

#callback to produce graph
@app.callback(
    [
        Output(component_id='output_container', component_property='children'),
        Output(component_id='my_series_graph', component_property='figure')
    ],
    [
        Input(component_id='slct_dataset', component_property='value'),
        Input(component_id='slct_date', component_property='start_date'),
        Input(component_id='slct_date', component_property='end_date')
    ]
)

def update_graph(dataset_slctd, start_date_slctd, end_date_slctd):

    container = 'Dataset: {}'.format(dataset_slctd) +\
                '. Start date: {}'.format(start_date_slctd) + \
                '. End date: {}'.format(end_date_slctd)

    dff = helper.get_dataset(dataset_slctd, start_date_slctd, end_date_slctd)

    dff['Datetime'] = dff.index
    fig = px.line(dff, x='Datetime', y='Value', title=dataset_slctd)

    return container, fig

if __name__ == '__main__':
    app.run_server(debug=False)

Right now I have min and max date allowed hard coded as this
min_date_allowed=date(1980, 1, 1) in date picker range. How can I define a date range dynamically based on the selection of a dataset in the first dropdown? Eg. lets say I have 01-01-2000/01-01-2001 as my min/max dataset for dataset1, and I have 02-02-2000/02-02-2001 as my min/max daterange for dataset2. How can I make my datepickerrange dynamically update based on whether I select dataset1 or dataset2 in my slct_dataset dropdown? As I understand this might depend on using a callback, but I can't really find what the standard way to do this is. Let me know if any more information can make the question more clear- I basically took the code I am actually writing and simplified it as much as possible so hopefully its clear what Im trying to do here. thanks for the help.

A: You can take the dropdown as an input to a callback and output to the date ranges of the datepicker based on the selected value. The signature should look like this:
@app.callback(
    [
        Output(component_id='slct_date', component_property='min_date_allowed'),
        Output(component_id='slct_date', component_property='max_date_allowed'),
    ],
    [
        Input(component_id='slct_dataset', component_property='value'),
    ]
)


text:
Q: Requesting Data on Socket in C In my C application, I wait for data on the socket in the following way:
printf("Opening socket and wait for data.\n");
while (i < 5)
   while((connection_fd = accept(socket_fd,
                            (struct sockaddr *) &address,
                            &address_length)) > -1)
   {
    bzero(buffer, 64);
    n = read(connection_fd,buffer,64);
    if (n < 0) printf("ERROR reading from socket");
    printf("Here is the message of length %d bytes:\n\n", n);
    for (int i = 0; i < n; i++)
    {
      printf("%02X", buffer[i]);
    }
    printf("\n\n");
    break;
    }
 i++
 }

That means I read 5 times data from the Socket, however, by the looks of it I seem to be opening 5 different connections is that right? Is it possible to open the connection just once, keep it alive, and then check whether there is any data available on this connection?
Thanks, Patrick!

A: your code needs some restructuring, you should only accept once for each new connection:
while (1) {
    connection_fd = accept(socket_fd, ...);

    /* check for errors */
    if (connection_fd < 0) {
      /* handle error */
    }

    /* note this could block, if you don't want
       that use non-blocking I/O and select */
    while ((n=read(connection_fd, buf, ...)) > 0) {
        /* do some work */
    }

    /* close fd */
    close(fd);
}

A: Sure.
To do so you might like to exchange the arguments to the two while() loops:
while ((connection_fd = accept(socket_fd,
                          (struct sockaddr *) &address,
                          &address_length)) > -1)
  while (i < 5)
  {
    ...

A: Yes. Remove the while (i<5) bit. After the read you can read more data if required.

A: It's simple. Move the statement calling accept function outside your loop and then call read using the same socket descriptor.

A: if (n < 0) printf("ERROR reading from socket");

Why you are going ahead? either break; the loop or continue; for new connection.