text:
Q: Why mfc deadlock when calling a afxmessagebox from propertypage into a extension dll I have a mfc Application an a extension dll with a modal Dialog. In this Dialog is a PropertySheet. One of the Property-Pages is loaded from a extnsion dll. Into the Extension DLL is an other property sheet. If I want to open a AfxMessageBox into the poperty sheet of the dll the application hang.
I think there is an deadlock.
The OS is Windows 7.
IDE Visual-Studio 2012
Here are some lines of the CallStack.
>   mfc110d.dll!_AfxTraceMsg(const char * lpszPrefix, const tagMSG * pMsg) Zeile 302    C++
mfc110d.dll!AfxCallWndProc(CWnd * pWnd, HWND__ * hWnd, unsigned int nMsg, unsigned int wParam, long lParam) Zeile 275   C++
mfc110d.dll!AfxWndProc(HWND__ * hWnd, unsigned int nMsg, unsigned int wParam, long lParam) Zeile 453    C++
mfc110d.dll!AfxWndProcBase(HWND__ * hWnd, unsigned int nMsg, unsigned int wParam, long lParam) Zeile 304    C++
user32.dll!76a362fa()   Unnamed
[The frames below are possible corrupted or not here. No symbols loaded foruser32.dll]
user32.dll!76a36d3a()   Unknown
user32.dll!76a36ce9()   Unknown
user32.dll!76a3966e()   Unknown
user32.dll!76a396d5()   Unknown
user32.dll!76a6104b()   Unknown
user32.dll!76a60d62()   Unknown
user32.dll!76a61089()   Unknown
ntdll.dll!76f91171()    Unknown
user32.dll!76a362fa()   Unknown
ntdll.dll!76f91171()    Unknown
ntdll.dll!76f91171()    Unknown
ntdll.dll!76f91171()    Unknown
ntdll.dll!76f91171()    Unknown
user32.dll!76a36ce9()   Unknown
user32.dll!76a40d37()   Unknown
ntdll.dll!76f91171()    Unknown
ntdll.dll!76f91171()    Unknown
ntdll.dll!76f91171()    Unknown
mfc110d.dll!CWnd::DefWindowProcA(unsigned int nMsg, unsigned int wParam, long lParam) Line 1141 C++
mfc110d.dll!CWnd::Default() Line 323    C++
mfc110d.dll!CWnd::OnActivate(unsigned int __formal, CWnd * __formal, int __formal) Line 368 C++
mfc110d.dll!CMFCPropertyPage::OnActivate(unsigned int nState, CWnd * pWndOther, int bMinimized) Line 73 C++
mfc110d.dll!CWnd::OnWndMsg(unsigned int message, unsigned int wParam, long lParam, long * pResult) Line 2540    C++
mfc110d.dll!CWnd::WindowProc(unsigned int message, unsigned int wParam, long lParam) Line 2137  C++
mfc110d.dll!AfxCallWndProc(CWnd * pWnd, HWND__ * hWnd, unsigned int nMsg, unsigned int wParam, long lParam) Line 290    C++
mfc110d.dll!AfxWndProc(HWND__ * hWnd, unsigned int nMsg, unsigned int wParam, long lParam) Line 453 C++
mfc110d.dll!AfxWndProcBase(HWND__ * hWnd, unsigned int nMsg, unsigned int wParam, long lParam) Line 304 C++
user32.dll!76a362fa()   Unknown
user32.dll!76a36d3a()   Unknown
user32.dll!76a36ce9()   Unknown
comctl32.dll!71f771cb() Unknown
comctl32.dll!71f33770() Unknown
mfc110d.dll!CMapPtrToPtr::HashKey(void * key) Zeile 42  C++
mfc110d.dll!CMapPtrToPtr::GetValueAt(void * key) Zeile 180  C++
0058ca3c()  Unbekannt
user32.dll!76a362fa()   Unknown
user32.dll!76a5f963()   Unknown
user32.dll!76a5f91b()   Unknown
user32.dll!76a5f7a4()   Unknown
ntdll.dll!76f91171()    Unknown
user32.dll!76a362fa()   Unknown
ntdll.dll!76f91171()    Unknown
ntdll.dll!76f91171()    Unknown
ntdll.dll!76f91171()    Unknown
ntdll.dll!76f91171()    Unknown
user32.dll!76a36ce9()   Unknown
user32.dll!76a40d37()   Unknown
ntdll.dll!76f91171()    Unknown
ntdll.dll!76f91171()    Unknown
ntdll.dll!76f91171()    Unknown
mfc110d.dll!CWnd::DefWindowProcA(unsigned int nMsg, unsigned int wParam, long lParam) Zeile 1141    C++
mfc110d.dll!CWnd::WindowProc(unsigned int message, unsigned int wParam, long lParam) Zeile 2138 C++
mfc110d.dll!AfxCallWndProc(CWnd * pWnd, HWND__ * hWnd, unsigned int nMsg, unsigned int wParam, long lParam) Zeile 290   C++
mfc110d.dll!AfxWndProc(HWND__ * hWnd, unsigned int nMsg, unsigned int wParam, long lParam) Zeile 453    C++
mfc110d.dll!AfxWndProcBase(HWND__ * hWnd, unsigned int nMsg, unsigned int wParam, long lParam) Zeile 304    C++
user32.dll!76a362fa()   Unknown
user32.dll!76a36d3a()   Unknown
user32.dll!76a36ce9()   Unknown
user32.dll!76a36ded()   Unknown
user32.dll!76a36e4c()   Unknown
ntdll.dll!76f3011a()    Unknown
user32.dll!76a4219a()   Unknown
user32.dll!76a8ef0a()   Unknown
user32.dll!76a362fa()   Unknown
user32.dll!76a5f9ff()   Unknown
user32.dll!76a5f91b()   Unknown
user32.dll!76a5f7a4()   Unknown
user32.dll!76a4afbc()   Unknown
user32.dll!76a362fa()   Unknown
user32.dll!76a36d3a()   Unknown
user32.dll!76a36ce9()   Unknown
user32.dll!76a40d37()   Unknown
user32.dll!76a4795a()   Unknown
mfc110d.dll!_AfxActivationWndProc(HWND__ * hWnd, unsigned int nMsg, unsigned int wParam, long lParam) Zeile 489 C++
user32.dll!76a362fa()   Unknown
user32.dll!76a36d3a()   Unknown
user32.dll!76a36ce9()   Unknown
user32.dll!76a3966e()   Unknown
user32.dll!76a6208f()   Unknown
user32.dll!76a5cf5b()   Unknown
user32.dll!76a8f808()   Unknown
user32.dll!76a8fae4()   Unknown
user32.dll!76a8fbe7()   Unknown
user32.dll!76a8fc66()   Unknown
user32.dll!76a8fdb9()   Unknown
user32.dll!76a8fdfe()   Unknown
mfc110d.dll!CWinApp::ShowAppMessageBox(CWinApp * pApp, const char * lpszPrompt, unsigned int nType, unsigned int nIDPrompt) Zeile 128   C++
mfc110d.dll!CWinApp::DoMessageBox(const char * lpszPrompt, unsigned int nType, unsigned int nIDPrompt) Zeile 45 C++
mfc110d.dll!AfxMessageBox(const char * lpszText, unsigned int nType, unsigned int nIDHelp) Zeile 147    C++

Here is some Code from the DLL. CPropStkList is derived from CPropertyPage.
    void CPropStkList::OnBnClicked()
{
    //BOOL test = TryEnterCriticalSection(AfxGetThread());
    AfxMessageBox(_T("Hallo Test!!"));

    //CDialog dlg(IDD_DIALOG2);
    //dlg.DoModal();
}

And here is the Code of the Parent-Application where calls the DLL-Dialog.
typedef UINT ( * LPDLLFUNC)(CGlobal *, CMsgSocket *); //Initialize DLL
    typedef CProSeSDialog * ( * GETDLG)(CWnd*, UINT, CString);   //Open Dialog from DLL
    LPDLLFUNC       lpfnDllFunc = NULL;
    GETDLG          getDlg  = NULL;
    HINSTANCE hDLL        = NULL;
    hDLL = AfxLoadLibrary("Stammdaten_DLL.dll");
if(hDLL)
        {
            lpfnDllFunc = (LPDLLFUNC)::GetProcAddress(hDLL,"Init");
            getDlg      = (GETDLG)::GetProcAddress(hDLL, "ShowDlg");
            if (!lpfnDllFunc)
            {
                AfxMessageBox("Function not found in DLL");
                FreeLibrary(hDLL);
                //return;
            }
            if(!getDlg)
            {
                AfxMessageBox("Function getDlg not found in DLL");
                FreeLibrary(hDLL);
            }
            lpfnDllFunc(AfxGetGlobal(), AfxGetGlobalSocket()); //Initialize DLL
            dlg[i=GetNewDlgNr()] = getDlg(this, 1, _T(""));

            m_strText[i] = INTLTXT ("Werkzeugstammdaten") + " DLL";

        }
        else
        {
            AfxMessageBox("Dll not found!");
        }

Creation of the Dialog into the DLL
extern "C" AFX_EXT_API CProSeSDialog* ShowDlg(CWnd *parent, UINT dlgType = 0, CString strKey = _T(""))
{

    new CDynLinkLibrary(Stammdaten_DLLDLL);

    //Lege Einstiegsdaten fest
    CGlobalKeyBuffer &buffer =  CGlobalKeyBuffer::Instance();
    buffer.m_strKey = strKey;

    CViewDlg *test = new CViewDlg(WKZSTAMM);
    test->Create(IDD_DIALOG1, parent);

    return test;
}

UPDATE
After hours of debugging the Application i founnd that the Applicaion Sends some Messages. It never ends with sending messages.
Here are the sended Messages.
    <025111> 001F1316 S WM_GETDLGCODE
<025112> 001F1316 R WM_GETDLGCODE fuDlgCode:DLGC_WANTARROWS | DLGC_HASSETSEL | DLGC_WANTCHARS
<025113> 001F1314 S WM_GETDLGCODE
<025114> 001F1314 R WM_GETDLGCODE fuDlgCode:DLGC_WANTARROWS | DLGC_HASSETSEL | DLGC_WANTCHARS
<025115> 00201312 S WM_GETDLGCODE
<025116> 00201312 R WM_GETDLGCODE fuDlgCode:DLGC_WANTARROWS | DLGC_WANTCHARS
<025117> 001E130C S WM_GETDLGCODE
<025118> 001E130C R WM_GETDLGCODE fuDlgCode:DLGC_WANTARROWS | DLGC_WANTCHARS
<025119> 001F1308 S WM_GETDLGCODE
<025120> 001F1308 R WM_GETDLGCODE fuDlgCode:DLGC_STATIC
<025121> 001F1306 S WM_GETDLGCODE
<025122> 001F1306 R WM_GETDLGCODE fuDlgCode:DLGC_STATIC
<025123> 001E1304 S WM_GETDLGCODE
<025124> 001E1304 R WM_GETDLGCODE fuDlgCode:DLGC_STATIC
<025125> 001F1302 S WM_GETDLGCODE
<025126> 001F1302 R WM_GETDLGCODE fuDlgCode:DLGC_STATIC
<025127> 00211300 S WM_GETDLGCODE
<025128> 00211300 R WM_GETDLGCODE fuDlgCode:DLGC_STATIC
<025129> 001E12FE S WM_GETDLGCODE
<025130> 001E12FE R WM_GETDLGCODE fuDlgCode:DLGC_STATIC
<025131> 001E12FC S WM_GETDLGCODE

A: I found a solution fo my problem.
You have to add to every element (control) that has any children the extern style
WS_EX_CONTROLPARENT.
ModifyStyleEx(0, WS_EX_CONTROLPARENT);

If that doesn't work you have to many subchildren. More than three is very difficult in MFC.


text:
Q: How can I properly unwrap these CLPlacemarks in Swift 2.0? I am converting my Swift 1.2 project into Swift 2.0, and the biggest error so far is that when using reverseGeocodeLocation(), my CLPlacemarks no longer work. Xcode attempts to unwrap them properly but gets stuck. Here is my code that worked in 1.2:
CLGeocoder().reverseGeocodeLocation(savedLocation, completionHandler: { (placemarks, error) -> Void in

            if error != nil {

                print(error)

            } else {

                if let p = CLPlacemark(placemark: (placemarks?[0] as? CLPlacemark))
//The above line is where it's having trouble

                {

                    if p.subThoroughfare != nil {

                        self.address = "\(p.subThoroughfare) \(p.thoroughfare) \(p.locality) \(p.postalCode)"
                        self.annotation.subtitle = self.address

                    }
                }

            }
        })

How can I properly implement them?

A: you should simply be able to do:
if let p = placemarks?[0}

redpajama_set_name: RedPajamaStackExchange


text:
Q: User Interface functionality modelling languages? I am looking for a UI functionality modelling language (UML-alike "thing", but for user interfaces) that is already accepted and maybe has its design patterns and handles the problem better than state or activity diagram.
This question came to mind as a result of a discovery that UML and its diagrams fails at describing complicated UI functionality with event-driven flow of execution (ie. javascript/jQuery big projects)
EDIT:
I've been thinking of using BPMN but It was not created for this purpose.

A: Maybe user interface prototypes or storyboards can be helpful ...
they are not part of a "modelling language" but very well proved techniques for designing GUI ...

A: One thing that comes to mind is Jesse James Garrett's Visual Vocabulary for Information Architecture.

A: I don't think there are any standards out there for that specific purpose (I was thinking of the same thing the other day).  SysML is close, I think, although it is definitely overkill.
Mainly, my thought was that if a UML profile or metamodel is defined with core UI components and events ("text-field", "single-click", etc.), different UI implementations (HTML, Swing, AJAX) could be generated using transformations on an instance model's XMI.  Barring that, at least there would be a more clear and formal way of describing the functionality of a given UI.

A: You can use traditional modeling notations for UI modeling, but this soon ends up with messy and useless models.
You should think to domain-specific models like WebML (soon to become a OMG standard under the name of IFML). In this case you also get a free modeling tool called WebRatio that provides quick prototyping and integration with BPMN specifications.
[Disclaimer: I'm with Politecnico di Milano and WebRatio, and among the inventors of WebML/IFML]

A: I just stumbled onto your question and it's an issue I take seriously. Here's my answer to that question, and I've used it in various forms for over 20 years.
Basically, here are the criteria I seek in such a descriptive language:

*

*The language should not be watered-down and incapable of things like access to data or basic flow-of-control primitives like IF, FOR, and subroutine calls. I accomplish this by building the language on top of the underlying standard language, by means of macros and function definitions. Thus, it requires no parser or interpreter, has direct access to application data, and has the control-flow primitives of the underlying language (but only some of them).
The reason for including flow-control primitives in the descriptive language is for their descriptive utility. The IF(test)-ELSE-END construct is a way of saying that one of two sets of controls is to be displayed depending on the value of (test). The FOR - END construct is a way of saying that a collection of controls to be displayed in a multiplicity, such as a linear array of controls. These can be nested to get a 2-D matrix of controls, if desired. A subroutine (with parameters) can display a set of controls, and can then be invoked in multiple places to replicate that set multiple times. Without such primitives in a DSL, structures like that are difficult to specify.

*The language should not require the person specifying the UI to have to deal with issues that only exist for implementation's sake, such as input event handling, creation, deletion, and naming of controls, and movement of data between controls and application data. So, for example, each edit, button, or other control is a single line of code. Code to handle events such as a button-click is written directly adjacent to the line of code specifying the button (not in a separate function or closure). Binding of controls to application data is handled "underneath" and is not the concern of the UI programmer. In order to make all this work, it is based on a control structure called Differential Execution that I stumbled upon in 1986. It is based on incremental re-execution of a program in such a way that it can incrementally update its output. In this case the output is a collection of controls on the surface of a window. Those controls are automatically created, deleted, moved, or otherwise modified in response to changes in the application state, without the UI programmer having to think in terms of state changes.
I have only used this in desktop UIs, and I have done almost no web development. I'm pretty sure the same principles could be applied to web UIs, and that it hasn't yet been done.


text:
Q: INVALID_ARGUMENT: Failed to parse headers when adding a ServerInterceptor I have a Java gRPC service which is working in production already. I am trying to add a ServerInterceptor to add tracing and logging context to it, but when I add the interceptor, the tests fail with the following error.
io.grpc.StatusRuntimeException: INVALID_ARGUMENT: Failed to parse headers.

    at io.grpc.stub.ClientCalls.toStatusRuntimeException(ClientCalls.java:271)
    at io.grpc.stub.ClientCalls.getUnchecked(ClientCalls.java:252)
    at io.grpc.stub.ClientCalls.blockingUnaryCall(ClientCalls.java:165)

I have tried removing the custom code and just adding barebones, but still the same, so I am convinced that it's not my tracing/logging code, but the way I am creating the interceptor. Any idea what can be improved here?
Here's the interceptor I have created (the bare bones, without the custom code)
public class ObservableServerInterceptor implements ServerInterceptor {

  @Override
  public <ReqT, RespT> ServerCall.Listener<ReqT> interceptCall(
      ServerCall<ReqT, RespT> serverCall,
      Metadata metadata,
      ServerCallHandler<ReqT, RespT> serverCallHandler) {

    return serverCallHandler.startCall(serverCall, metadata);
  }
}

And here's how I am adding it
final GrpcServer grpcServer = environment.resolve(GrpcServer.class);
grpcServer.intercept(new ObservableServerInterceptor());

Edit:
I forgot to add the bit where I am trying to get values from the Metadata and when I comment it out, everything works. Here's the code in my intereceptor for the same
final Map<String, String> contextFromRequest = new HashMap<>();
    metadata.keys().stream()
        .forEach(
            key -> {
              Metadata.Key<String> metadataKey =
                  Metadata.Key.of(key, Metadata.ASCII_STRING_MARSHALLER);
              contextFromRequest.put(key, metadata.get(metadataKey));
            });

So may be it's the way I am extracting the values?


text:
Q: changing a string to double returning one I have stored a value 1/129600.0 in a plist as a string.
I am able to retrieve it as a string but when i am trying to convert it as a double i am getting it as 1.0.I have also tried CFString
NSString *value = [[self array]objectAtIndex:m];
double a = [value doubleValue];
NSLog(@"%@",value);
NSLog(@"%f",a);

and in log the returned values are
 1/129600.0 and 1.0

A: I guess 1/129600.0 is not a valid number.
Try to create an expression and create an NSNumber from it:
NSString *equation = [[self array]objectAtIndex:m];
NSNumber *a = [[NSExpression expressionWithFormat:equation] expressionValueWithObject:nil context:nil];
double a = [result doubleValue];
NSLog(@"%f", a);

A: This code works fine, I tried it in xCode:
NSString *equation = [[self array]objectAtIndex:m];
NSExpression *result = [NSExpression expressionWithFormat:equation];

NSNumber *a = [result expressionValueWithObject:nil context: nil];

NSLog(@"%@",result);
NSLog(@"%.10f",[a doubleValue]);

A: 1/129600.0 is not a valid representation for a number in most programming languages, including ObjC. You need to parse the string and interpret it yourself.

A: Try this
NSString *value = [[self array]objectAtIndex:m];
NSArray *arr = [value componentsSeparatedByString:@"/"];
double a;
if ([arr count] == 2)
{
   a = [arr objectAtIndex:0]/[arr objectAtIndex:1];
}
NSLog(@"%@",value);
NSLog(@"%f",a);


text:
Q: Factory Girl: Set default value of transient attribute to factory I have an FG factory that returns a complex hash, let's call it zhash, because it's defined at the end of the factories (FG loads the files alphabetically).
That hash is stored as a json string on a model (right or wrong, that's how it is). I have an ignore variable (a transient attribute) on that model's factory that allows me to set that attribute to my custom hash, but I'd like to set a default value of that ignore variable to the default for that hash factory.
e.g.
FactoryGirl.define do
  factory :model do
    ignore do
      # this does not work, because the factory has not been defined.
      hash FactoryGirl.create(:zhash)
    end
  end
end

FactoryGirl.define do
  factory :zhash do
    ... #return hash
  end
end

I could just change the name of the zhash file to 0_zhash, but is there a FactoryGirl way to set a factory as the default value for an ignore variable?

A: FactoryGirl.define do
  factory :model do
    ignore do
      zhash
    end
    numeric_attribute zhash.count
  end
end

will not work, but
FactoryGirl.define do
  factory :model do
    ignore do
      zhash
    end
    numeric_attribute { zhash.count }
  end
end

will
(also, "ignore" is deprecated in current factorygirl and is to be replaced by "transient")


text:
Q: Derive the amplitude of superimposed harmonic waves in trigonometric form We have two waves
$\psi_1(x) = a_1\mathrm{cos}(kx-\omega t + \phi_1)$
$\psi_2(x) = a_2\mathrm{cos}(kx-\omega t + \phi_2)$
We know that the superimposed wave can be written as
$\psi(x) = \psi_1(x) + \psi_2(x)$
How can I derive from this that the amplitude of the superimposed wave $\psi(x)$ is
$ \sqrt{a_1^2 + a_2^2 + 2a_1a_2 \mathrm{cos}(\phi_1-\phi_2 )}    $
I'm pretty sure it has something to do with the relation that when you have
$\psi(x,t)=A\mathrm{cos}(kx+ ωt + \phi) = B\mathrm{cos}(kx+ ωt) - C\mathrm{sin}(kx+ ωt)$
you can derive that
${A}^{2} = {B}^{2} + {C}^{2}$;
and
$\mathrm{cos}(\phi) = \frac{B}{A}, \mathrm{sin}(\phi) = \frac{C}{A}$
But I can't figure out how to do it...

A: I'm setting $kx - \omega t = \theta$, for ease of notation.
Let's take your idea: $A \cos ( \theta + \phi ) = A\cos \phi \cos \theta - A\sin \phi \sin \theta$.
Adding the two equations gives:
$(\psi_1 + \psi_2)(\theta) = (a_1\cos \phi_1 + a_2 \cos \phi_2)\cos \theta - (a_1\sin \phi_1 + a_2 \sin \phi_2)\sin \theta$
$ \Rightarrow (\psi_1 + \psi_2)(\theta) = A \cos (\theta + \Phi )$
with $A^2 = (a_1\cos \phi_1 + a_2 \cos \phi_2)^2 + (a_1\sin \phi_1 + a_2 \sin \phi_2)^2$
and $\tan \Phi = \frac{-(a_1\sin \phi_1 + a_2 \sin \phi_2)}{(a_1\cos \phi_1 + a_2 \cos \phi_2)}$
Can you solve the above out to get the new amplitude?
Also, in case you're familiar with complex numbers, a lot of the algebra gets easier with the phasor representation .


text:
Q: Search multiple fields of the same collection using meteor-autocomplete? I am using mizzao/meteor-autcomplete in order to return matched items from a MongoDB collection when you type a query.
I am able to successfully do this if I only search for one field, but it does not let me search multiple fields of the same collection.
I attempted to do it this way:
Template.foo.helpers({
    settings: function() {
            return {
                position: 'bottom',
                limit: 5,
                rules: [
                     {
                         collection: Models,
                         field: 'name',
                         matchAll: true,
                         template: Template.standardLegends,
                    },
                    {
                        collection: Models,
                        field: 'createdBy',
                        matchAll: true,
                        template: Template.standardLegendsOwner,
                    },
                ],
            };
        },
});

I looked through github open issues and there was one similar issue where they say to use the selector function in order to return multiple fields but I wasn't really able to understand what I am supposed to do.
Here is a link to that thread:
https://github.com/mizzao/meteor-autocomplete/issues/13
Any help would be appreciated.
Further Explanation
Here is an example of a dataset that is returned from my Models Collection:
0:
    _id:"KwTZmBC5qBcwK7kzR"
    name:"drillCase.stl"
    units:"mm"
    createdBy:"Bob M"
    createdDate:"Tue Aug 29 2017 03:19:10 GMT-0400 (EDT)"
1:
    _id:"ljknbgwlkejb56"
    name:"cone.stl"
    units:"mm"
    createdBy:"Michael C"
    createdDate:"Tue Aug 29 2017 03:45:10 GMT-0400 (EDT)"

Here is the template I am currently using to display the autocomplete results:
<template name="standardLegendsOwner">
    {{name}}
</template>

So let's say I want to return all of the items that are associated with the 'createdBy' value 'Bob M'. Right now if I type Bob M, I get returned back 'drillCase.stl' instead because we are searching by the 'name' field and in the template we are return the 'name' value.
So my question is, is it possible to setup up a conditional statement inside of the template to say something like, if the field you matched was 'name' return name values, otherwise return 'createdBy' values.
The issue I get right now is, if I type in Bob M. and he is associated with more than one object, then it return first value that matches with him.

A: The selector function basically needs to return the query object that is to be used by .find(). To look at multiple fields you will also need $or:
Template.foo.helpers({
  settings() {
    return {
      position: 'bottom',
      limit: 5,
      rules: [
        {
           collection: Models,
           field: 'name',
           matchAll: true,
           template: Template.standardLegends,
           selector(match) {
             regex = new RegExp(match, 'i')
             return {$or: [{'name': regex}, {'createdBy': regex}]}
           },
         }
       ],
     };
   },
});

I read the documentation for mizzao:autocomplete a bit more and realized that it actually returns all the fields from the matching documents. This means you have a lot of flexibility in your results template. For example you can do:
<template name="standardLegendsOwner">
  {{name}} - {{createdBy}}
</template>

Since you know one of those fields will be a match. You could also write a helper that creates exactly what you want to see.


text:
Q: how to make a discord bot delete what you wrote and send what you originally sent in javascript? it should delete my message and type it as if it has said it itself, im a begginer in discord bot coding pls help

A: It can be done by storing the message in a variable, deleting the message, then sending the variable. An example would be:
client.on('message', async (message) => {
    const content = message.content;
    await message.delete();
    await message.channel.send(content);
});


text:
Q: Can not install Ubuntu Phone on Nexus 4 I follow the instruction
 and everything seemed to work ok but then the phone reboots at the end with a message saying "This phone needs restoring from a PC or service center".
So I can flash back to the Android 4.4.4 "KitKat" and everything works ok.
Actually from the boot I can launch the recovery boot which is the ubuntu one but I am not able to launch the ubuntu OS...
I tried the stable and development channel.
ubuntu-device-flash touch --channel=ubuntu-touch/devel/ubuntu --bootstrap
2016/03/06 11:08:00 Expecting the device to be in the bootloader... waiting
2016/03/06 11:08:00 Device is |mako|
2016/03/06 11:08:00 Flashing version 8 from ubuntu-touch/devel/ubuntu channel and server https://system-image.ubuntu.com to device mako
19.04 MB / 19.04 MB [====================================] 100.00 % 301.97 KB/s
52.43 MB / 52.43 MB [====================================] 100.00 % 408.69 KB/s
288.72 MB / 288.72 MB [==================================] 100.00 % 437.31 KB/s
2016/03/06 11:19:39 Start pushing /home/splater/.cache/ubuntuimages/pool/ubuntu-0144c0d9ab780d8b40477987c3004d4c25d1861e6dd067125e77970c11ec76a1.tar.xz to device
2016/03/06 11:19:39 Start pushing /home/splater/.cache/ubuntuimages/gpg/image-signing.tar.xz to device
2016/03/06 11:19:39 Start pushing /home/splater/.cache/ubuntuimages/pool/custom-9cebce4a630edb99402c79c73a7eb7eed051febe93e66208c6711f29f6d5cf35.tar.xz to device
2016/03/06 11:19:39 Start pushing /home/splater/.cache/ubuntuimages/ubuntu-touch/devel/ubuntu/mako/version-8.tar.xz to device
2016/03/06 11:19:39 Start pushing /home/splater/.cache/ubuntuimages/pool/device-00f7ea9bb6e1b445460b981872b273c4a49cea282a4478831543ccf9d83d7ab2.tar.xz to device
2016/03/06 11:19:39 Start pushing /home/splater/.cache/ubuntuimages/gpg/image-master.tar.xz to device
2016/03/06 11:19:40 Done pushing /home/splater/.cache/ubuntuimages/ubuntu-touch/devel/ubuntu/mako/version-8.tar.xz to device
2016/03/06 11:19:40 Done pushing /home/splater/.cache/ubuntuimages/gpg/image-master.tar.xz to device
2016/03/06 11:19:40 Done pushing /home/splater/.cache/ubuntuimages/gpg/image-signing.tar.xz to device
2016/03/06 11:21:10 Done pushing /home/splater/.cache/ubuntuimages/pool/custom-9cebce4a630edb99402c79c73a7eb7eed051febe93e66208c6711f29f6d5cf35.tar.xz to device
2016/03/06 11:22:56 Done pushing /home/splater/.cache/ubuntuimages/pool/device-00f7ea9bb6e1b445460b981872b273c4a49cea282a4478831543ccf9d83d7ab2.tar.xz to device
2016/03/06 11:29:08 Done pushing /home/splater/.cache/ubuntuimages/pool/ubuntu-0144c0d9ab780d8b40477987c3004d4c25d1861e6dd067125e77970c11ec76a1.tar.xz to device
2016/03/06 11:29:08 Created ubuntu_command: /home/splater/.cache/ubuntuimages/ubuntu_commands129934107
2016/03/06 11:29:08 Rebooting into recovery to flash

On the boot I can see:
Bootloader version MAKOZ30d
SECURE BOOT - enabled
LOCK STATE - unlocked

is the secure boot is the problem?

A: Try the rc channel for mako, or bq aquaris channel (I'm on bq aquaris RC proposed on nexus 4). First flash the latest radio from the android 5.1.1 images. I couldn't get stable to boot when I first installed either.

A: Yes, you answered yourself: the secure boot is the problem. Even if the instructions on developer.ubuntu.com are quite complete, I found these video tutorials more useful.

*

*http://pocketnow.com/2013/02/22/install-ubuntu-nexus-4

*https://www.youtube.com/watch?v=13WFcVmDfZg


text:
Q: Sun distance, temperature changes During winter,  given that over a few days the earth is basically the same distance from the sun,  why can there be such a significant drop in temperature in just one or two days that have equally clear skies?
What are the other variables (cold air wind?) and what causes them on some days but not others?

A: the answer is that barometric air pressure differences cause wind-driven movement of cold and warm air masses over the land. Where I live, we can see a 40 degree F temperature drop overnight if a high-pressure zone parks itself over idaho and western montana and blows icy cold air westward into oregon; then the temperature bounces back when marine air from off the pacific coast blows inland and pushes back on that other air mass.


text:
Q: MSYS2 gcc fatal error in cc1.exe: cygheap base mismatch detected This particular error has come up in multiple other contexts on Stack Overflow, typically regarding Cygwin or git (and involving other executables). I have not seen this in the context of MSYS2 and I am not sure how to address it. This is happening on a brand new install of MSYS2 using pacman -S gcc which installs gcc version 9.3.0. When I go to run my makefile, this is the error that comes up:
0 [main] cc1 (2724) C:\msys64_close\usr\lib\gcc\x86_64-pc-msys\9.3.0\cc1.exe:
*** fatal error - cygheap base mismatch detected - 0x180346408/0x180317408.
This problem is probably due to using incompatible versions of the cygwin DLL.
Search for cygwin1.dll using the Windows Start->Find/Search facility
and delete all but the most recent version.  The most recent version *should*
reside in x:\cygwin\bin, where 'x' is the drive on which you have
installed the cygwin distribution.  Rebooting is also suggested if you
are unable to find another cygwin DLL.

The file cygwin1.dll does not exist anywhere within the msys64 folder. The MSYS2 home page states:

Cygwin provides a runtime library called cygwin1.dll that provides the POSIX compatibility layer where necessary. The MSYS2 variant of this library is called msys-2.0.dll...

I am not sure if the problem resides with gcc or MSYS2. I tried to install older versions of gcc from http://repo.msys2.org/ but every time I try to use a lower version than 9.3.0 I get warnings that gcc cannot be "upgraded" due to unresolved dependencies.
Any assistance would be greatly appreciated.

A: The problem was that the msys-2.0.dll that is required in the same directory as the makefile for the program was not matching the same file in:
msys64/usr/bin

I essentially had an older version of this file, and since they did not match up the above error was produced. If you are met with this problem, you need to copy and paste the newer version from above into the directory where you are compiling your software (for me it was the directory with the makefile). Once that was done the software compiled without error.


text:
Q: ASP.NET Core Dependency Injection error - Unable to resolve service for type "Repository" while attempting to activate "Service" I'm attempting to create an ASP.NET Core app using a generic repository pattern using Entity Framework along with a service layer. However, whenever I start up my project I get hit with this error:

Unable to resolve service for type 'GameSource.Data.Repositories.GameRepository' while attempting to activate 'GameSource.Services.GameService'.

GamesController.cs:
    public class GamesController : Controller
    {
        private IGameService gameService;

        public GamesController(IGameService gameService)
        {
            this.gameService = gameService;
        }
    }

GameService.cs:
    public class GameService : IGameService
    {
        private GameRepository gameRepo;

        public GameService(GameRepository gameRepo)
        {
            this.gameRepo = gameRepo;
        }
    }

GameRepository.cs:
    public class GameRepository : BaseRepository<Game>, IGameRepository
    {
        private GameSource_DBContext context;
        private DbSet<Game> gameEntity;

        public GameRepository(GameSource_DBContext context) : base(context)
        {
            this.context = context;
            gameEntity = context.Set<Game>();
        }
     }

BaseRepository.cs:
    public class BaseRepository<T> : IBaseRepository<T> where T : class
    {
        private GameSource_DBContext context;
        private DbSet<T> entity;

        public BaseRepository(GameSource_DBContext context)
        {
            this.context = context;
            entity = context.Set<T>();
        }
    }

GameSource_DBContext.cs:
    public class GameSource_DBContext : DbContext
    {
        public GameSource_DBContext(DbContextOptions<GameSource_DBContext> options) : base(options)
        {
        }

        public DbSet<Game> Game { get; set; }
        public DbSet<Genre> Genre { get; set; }
        public DbSet<Developer> Developer { get; set; }
        public DbSet<Publisher> Publisher { get; set; }
        public DbSet<Platform> Platform { get; set; }
    }

Startup.cs:
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllersWithViews().AddRazorRuntimeCompilation();

            services.AddDbContext<GameSource_DBContext>(options => options.UseSqlServer(Configuration.GetConnectionString("GameSource_DB")));

            services.AddScoped(typeof(IBaseRepository<>), typeof(BaseRepository<>));
            services.AddScoped<IGameRepository, GameRepository>();
            services.AddScoped<IGameService, GameService>(); //Can't resolve service?
        }

As you can see in the startup, I'm trying to inject my service as well as my repository, but it can't resolve the service for the GameRepository when trying to activate GameService. Am I missing something? Is this the right approach to use with Entity Framework i.e. repo + service layers?
Thank you for your patience.

A: In the GameService change it so it uses the IGameRepository interface like so:
public class GameService : IGameService
{
    private IGameRepository gameRepo;

    public GameService(IGameRepository gameRepo)
    {
        this.gameRepo = gameRepo;
    }
}

FYI, GameRepository can't be resolved because you've configured the dependency injection to inject the repository when the interface IGameRepository is used in the constructor not the concrete implementation.


text:
Q: The value of my variable is changing In another file I got this varible:
var things = $('#box li');

My problem is that the user can change the value in #box. So it contains x different li:s then my var things is not set anymore. How do I change this var? var things is in my index.php file. The place where the user changes the #box is in my change.php file, so I think It's a bit harder.
Probably I duplicate but I dont know what to search so please direct me if you can.

A: Use getElementsByTagName, which will return a live HTMLCollection, which you can select again:

var things = $('#box')[0].getElementsByTagName("li")

console.log($(things).toArray())

$('li').last().remove() //remove last li element

console.log($(things).toArray())

a

b

c


text:
Q: Getting PhaseScriptExecution Bundle\ errors when trying to build using EAS / Expo I've been having issues getting a successful build for a project I'm working on. I keep getting the following error:
 ** ARCHIVE FAILED **
▸ The following build commands failed:
▸   PhaseScriptExecution Bundle\ React\ Native\ code\ and\ images /Users/expo/Library/Developer/Xcode/DerivedData/Brainiac-engdhxyrndsxydamdhbacjdwwrlk/Build/Intermediates.noindex/ArchiveIntermediates/Brainiac/IntermediateBuildFilesPath/Brainiac.build/Release-iphoneos/Brainiac.build/Script-00DD1BFF1BD5951E006B06BC.sh (in target 'Brainiac' from project 'Brainiac')
▸ (1 failure)
** ARCHIVE FAILED **
The following build commands failed:
    PhaseScriptExecution Bundle\ React\ Native\ code\ and\ images /Users/expo/Library/Developer/Xcode/DerivedData/Brainiac-engdhxyrndsxydamdhbacjdwwrlk/Build/Intermediates.noindex/ArchiveIntermediates/Brainiac/IntermediateBuildFilesPath/Brainiac.build/Release-iphoneos/Brainiac.build/Script-00DD1BFF1BD5951E006B06BC.sh (in target 'Brainiac' from project 'Brainiac')
(1 failure)

I've done searches here and tried suggestions in threads but still having trouble eliminating these. Currently running expo-cli 6.1.0 and expo sdk 44. Project is using Node 16.9.0. Any help is appreciated!


text:
Q: How to add percentage to entire table in excel I'm still new to the more advanced methods in excel, so my question seems a little bit simple, but I struggle with it a lot and can't find a solution. So let's say I have an entire table in excel with different prices in each cell. I want to update the whole table with a percent which can be changed from a different cell. For example if I want to increase the prices in all cells in the table by 10% I just type in that designated cell 10% and all the prices are increased with 10%. I tried t he method with Paste Special but I have to paste it again when I want to change the percentage. Any help will be greatly appreciated. Thank you for your time.

A: Let's say your percentage cell is in G2, and the Price Cells that you want to change are in cells a2, b2, and c2.
Say cells a2 price is 2, b2 price is 4, and c2 price is 7, the formula you'd want to put into the cells is =2*g2 for a2, =4*g2 for b2, and =7*g2 for c2. Now everytime you change the value of your percentage cell in g2, your cells will automatically update.

A: If a vba solution is acceptable, you could use the paste special method in the workbook_sheetchange event of ThisWorkbook and use the percentage cell as the target.
Without VBA, you could create a second table that references the original table and the percentage cell in a formula.


text:
Q: how can a user run a protected manual job? there are several jobs in the protected branch. the last job is manual, but regular users cannot run it. how can an ordinary user run a manual job in a protected branch?
in the picture, an ordinary user does not have a play button

A: Only users who can push or merge to a protected branch are allowed to run manual jobs for a pipeline on a protected branch.
See footnote 5: https://docs.gitlab.com/ee/user/permissions.html

[Run CI/CD pipeline for a protected branch] If the user is allowed to merge or push to the protected branch.

Thus, the only way to allow a user to run this job on a protected branch would be to give them permission to either push or merge to the protected branch.

A: There is a workaround.

*

*To allow Developer user to run the manual job you can allow Developer to merge to the particular branch

*And to restrict Developers to merge to this branch add an additional rule with the mask matching the same branch.

*As a result they will not be able to merge/push but will be allowed to run manual jobs.


text:
Q: PHPUnit_Framework_Assert::assertClassHasStaticAttribute() must be a class name I'm just starting out learning PHPUnit. I have a seemingly very simple test;
namespace stats\Test;

use stats\Fetch;

class FetchTest extends \PHPUnit_Framework_TestCase
{

    public function setUp()
    {
        $this->fetch = new Fetch;
    }

    public function testStoresListOfAssets()
    {
        $this->assertClassHasStaticAttribute('paths', 'Fetch'); //line 17
    }

}

My Fetch class is;
namespace stats;

class Fetch
{
    public static $paths = array(
        'jquery' => 'http://code.jquery.com/jquery.js'
    );
}

The error I get when running PHPUnit;
PHPUnit_Framework_Exception: Argument #2 (string#Fetch)of PHPUnit_Framework_Assert::assertClassHasStaticAttribute() must be a class name
It's probably something very silly but I can't understand the problem

A: The PHPUnit_Framework_Assert use the PHP method class_exists to check if the classname you have indicated is correct (check this link to see the full code):
if (!is_string($className) || !class_exists($className, FALSE)) {
  throw PHPUnit_Util_InvalidArgumentHelper::factory(2, 'class name');
}

The problem you have here is the method class_exists doesn't take into account this command:
use stats\Fetch;

So that, you have to indicate the full path to make it work. In this link of stackoverflow you can find more information about that problem. You should change your assert to something like this:
$this->assertClassHasStaticAttribute('paths', '\\stats\\Fetch');

A: You're not supplying the fully qualified class name and in the context of assertClassHasStaticAttribute() or any other method/function outside of the scope of your (test) class the use statement that complements the class name.
If you're using PHP 5.5 or later (which you should ;) use Fetch::class.
In general you should prefer ::class over strings for class names as modern IDEs can help you with refactoring when changing class names which is close to impossible if you use strings.
To sum it up, for your example it would be:
public function testStoresListOfAssets()
{
    $this->assertClassHasStaticAttribute('paths', Fetch::class);
}


text:
Q: How to fix Widget is disposed errer when tryng to open Shell for the second time? When I'm trying to open for the second time a child-shell, occur Widget is disposed error.
I'm trying to create a main Shell and, with menu-bar then child-shell for the functions.
Here the printStackTrace:
org.eclipse.swt.SWTException: Widget is disposed
at org.eclipse.swt.SWT.error(Unknown Source)
at org.eclipse.swt.SWT.error(Unknown Source)
at org.eclipse.swt.SWT.error(Unknown Source)
at org.eclipse.swt.widgets.Widget.error(Unknown Source)
at org.eclipse.swt.widgets.Widget.checkWidget(Unknown Source)
at org.eclipse.swt.widgets.Shell.close(Unknown Source)
at it.anabasibdg.viste.Main$2.widgetSelected(Main.java:108)
at org.eclipse.swt.widgets.TypedListener.handleEvent(Unknown Source)
at org.eclipse.swt.widgets.EventTable.sendEvent(Unknown Source)
at org.eclipse.swt.widgets.Widget.sendEvent(Unknown Source)
at org.eclipse.swt.widgets.Display.runDeferredEvents(Unknown Source)
at org.eclipse.swt.widgets.Display.readAndDispatch(Unknown Source)
at it.anabasibdg.viste.Main.open(Main.java:51)
at it.anabasibdg.viste.Main.main(Main.java:36)

Here the code:
MenuItem mntmInserimento = new MenuItem(menu_2, SWT.NONE);
    mntmInserimento.addSelectionListener(new SelectionAdapter() {
        @Override
        public void widgetSelected(SelectionEvent e) {

            if(cs1.isDisposed() == false) {

            cs1.layout();
            cs1.open();

        }else {

            cs1.open();

        }
    }
        });

A: Once a Shell has been closed the Shell and all the controls it contains are disposed and can't be used again.
You must create a new shell and all its contents from scratch each time you want to use it.


text:
Q: Heartbeat activity for Windows Service I have many Windows Services (written in C# 4.0) that at various intervals connect to a database and do various complex tasks.  Some of these tasks only occur every X hour intervals per day.  However, the server support team would like to know if the Windows Service is actually running as there can be a big interval between tasks.  They would like essentially a heartbeat for each Windows Service.  Every 5 minutes the Windows Service would do something that could be monitored by Microsoft System Center Operation Manager (SCOM).  Any solution must being easily monitored by SCOM as the server support team rely on it.
What is the best way to achieve this type of funcationality?  I thought of using Performance Counters and have SCOM listen for those but not sure if that is that best use of perf counters.
UPDATE (Totally forgot to include): Currently each service writes to a database this action but SCOM is not very good at monitoring databases records and differentiating which service is doing what etc.

A: If your case here is limited to service health check, I am pretty sure this can be done by windows tools such as windows performance monitor. Collecting their data should be an easier task than creating heartbeats in a usually disconnected environment.
There are plenty of server and service monitoring tools. Few of them are also open-source, which you can choose as an initial step.

A: What about simply writing to a DB or event  log?

A: You could add either SNMP or WMI instrumentation to your services - this incidentally will allow you to raise more than just heartbeat messages - for example you could also raise events when you encounter transient faults that require an operation to be retried.
There are plenty of SNMP libraries out there and WMI support is built into the .NET framework.

A: Just FYI, I'm researching this question because how I do it is that the Service application logs a hearbeat message every X seconds when it polls the Db for a new job. At midnight, all heartbeat messages over a week old are deleted from the log. I do have an application scheduled at 7 AM that checks when the last heartbeat message was sent, but it looks like I'm going to have to run it constantly to periodically check ... and notify Solar Winds to send an alert if there is a problem.


text:
Q: How to use ZF2's EventManager over multiple classes (and modules)? I am having the following setup: In a controller I trigger an event and I want to attach multiple listeners to it at other places.
Currently I have the following listener in my onBootstrap:
$e->getApplication()->getServiceManager()->get('EventManager')->attach('*', function($e) {
    var_dump($e->getName());
});

The following piece of code as a factory:
'Application\Controller\Foo' => function(ControllerManager $cm) {
    $eventManager = $cm->getServiceLocator()->get('EventManager');
    $controller = new \Application\Controller\FooController();
    $controller->setEventManager($eventManager);
    return $controller;
},

And finally the following trigger within my controller:
$this->getEventManager()->trigger('foo-finished', 'finishedAction', array(
    'obj' => $foo->someObject()
));

So it should both be the same EventManager as I receive it from the service locator and inject it into the controller. Still I get no output at all. I also tried using $e->getApplication()->getEventManager() when attaching to events, but this only gives me the ZF internal events.
I read about the SharedEventManager, but I do not fully understand why I should pass a context. I tried it like this (which is as I understood it), but still no output.
$e->getApplication()->getServiceManager()->get('EventManager')
    ->getSharedManager()
    ->attach('finishedAction', '*', function() { ... });

So, what am I doing wrong? I just want to trigger events and catch them in possibly different modules, but it seems to be made so complicated...

A: By default the EventManager service is not shared, this means that every time you call $serviceLocator->get('EventManager') you will get a different instance, that's why you should use the SharedEventManager - take a look at @Crisp's link to see how to use it.
One more tip: Don't try to inject the Mvc EventManager in your objects, each object should trigger their own events.

A: The following worked for me (not the order of getEventManager and getSharedManager), also note the order of event name and the context (or identifier).
$e->getApplication()->getEventManager()->getSharedManager()->attach('*', 'finishedAction', function() { ... });

Regards!


text:
Q: Intuition behind why the derivative of $\ln(cx)$ always equals $1/x$, for any $c>0$? I understand how to prove that algebraically using implicit differentiation:
1
However, when I hope to gain an understanding through the graphs, I had a hard time wrapping my head around why the transformed lnx function still has the same slope at every point of x as the parent function.
Graphs of the 3 functions that I talked about

A: It's because of the identity $\ln(ab)=\ln a+\ln b$, which holds for all $a,b>0$.

A: Here's a more general way of asking the question. Let $c\neq0$.
In order for $f(x)$ and $g(x):=f(cx)$ to have the same slope for all $x$, we need $f'(x)\equiv g'(x)\equiv c\cdot f'(cx)$. (The $\equiv$ sign means that these equations need to hold for all values of $x$: in order words, these functions must be equal, not just coincide at a particular point $x$.)
Which functions $h$ have the property that $h(x)\equiv c\cdot h(cx)$? Or, in other words, $h(cx)\equiv c^{-1}\cdot h(x)$?
Geometrically, this last identity says that compressing the graph of $h$ horizontally by a factor of $c$ is the same as stretching the graph of $h$ vertically by a factor of $c^{-1}$.
Algebraically, you can see that any function of the form $ax^{-1}$ solves this functional equation. In fact, any sum of such functions will work, too: we can have $h(x)=\sum a_ix^{-1}$.
Note that you can see clearly that no polynomial will work, though: substituting $cx$ for $x$ in $\sum a_ix^i$ for $i\geq0$ will not allow you to factor $c^{-1}$ out of each term.


text:
Q: IIS7 Web Farm Framework 2.0 Basic Setup Questions On Load Balancing
Possible Duplicate:
IIS7 Web Farm Framework 2.0 Basic Setup Questions On Load Balancing

Pardon the basic questions but I can't seem to find any basic answers.
I'm in the process of standing up a standard server farm using Web Farm Framework 2.0. I set up a controller server and a primary server. When I provisioned my primary server I did so enabling load balancing. I then deployed a basic MVC application on my primary server. I am able to ping my client application when I hit the primary server directly confirming everything is OK on that end. For the sake of kicking tires, what I'd like to do is access that same MVC application through my farm.
For clarity, let's say my environment looks like this: controller (IP: 192.168.0.1), primary (IP: 192.168.0.2).
To access the MVC application through the farm, what address should I be pointing to? I assumed it would be 192.168.0.1/mymvcapplication however that does not work. Keep in mind, by-passing the load balancer (which I presume is my controller server) works fine. Am I missing something in terms of enabling load balancing? Is there something else I'm required to do (on my controller or primary server) beyond just checking the Enable Load Balancing checkbox when provisioning the primary server?
Any tips would be greatly appreciated!

A: In WFF terms:
A controller watches the primary, and rolls configuration changes out to the secondaries.
A primary contains the master copy of everything for that farm.
A secondary is a write-only copy of the primary.
The load balancing state is an indicator that can be used by external load balancers.
What you haven't mentioned, so I assume you haven't installed, is ARR. Application Request Routing is a reverse-proxy (publishing) component you can add to an IIS box - in this case it seems like your intent is to add it to the Controller - to make it publish other sites.
Right now, assuming ARR isn't installed, the load balancing state is just a flag that doesn't do much. You can access the individual server individually (normally I'd write "servers" there, but no secondary :) ...), and if you changed the primary, the controller would replicate that to a secondary, but without a load balancer (external, or sometimes ARR installed on the controller), you've got no publication point.
WFF on its own doesn't do load balancing, just creates a synchronization infrastructure.
ARR 2.5 usually installs WFF 1.0 (so be ready for farm shenanigans if you install it later; I think the WFF version doesn't get rolled back, but haven't tried it in a while), but can be combined with the Controller role in small deployments.


text:
Q: Easiest way to supply a Java webapp with lists of email lists I'm renovating a legacy Java webapp ( servlets and JSPs ) I inherited.  The webapp sends email and it uses about 12 lists of email addresses.  The email addresses are hard coded into the webapp.   Naturally, I want to put those lists of email addresses into a file and have the webapp read them in.
In the old days I would put those lists into a *.properties file in the webapp root directory.
I'm guessing Properties objects and *.propertie files is not the modern Java way to do this.
One choice I have is to put each email list into the web.xml as a <context-param>, with the <param-value>being a comma separated list of email addresses.   I would then retrieve each list, by name, with context.getInitParameter() and then write a function to tokenize the emails and put each list into an ArrayList.    My intuition tells me that is more messy than it has to be.
I would like my config file to be non-tech user friendly like a properties file, with comments, white space,key-value pairs, ie
########################################
##  This file lists the email lists
#########################################

customerList =  joeblow@gmail.com,sara@yahoo.com
managerList  =  jack@biz.com,jane@bigorg.gov

##########################################
##  end of file
##########################################

Such a file would contain 12 such lists with about 10 different email addresses
I know how to use the Properties class to find such a file inside of a WAR and load it into a properties object very easily.
The problem comes in how to elegantly get each of those 12 lists out of the properties object, tokenized and into an individual ArrayList(with a named reference)
Am I right in assuming that the Prooperties class has been made obsolete by the modern collections?   Im guessing the way to go is to use the Scanner class to read and tokenize the file into a Map, with each key being the name of an email list and each value being an ArrayList of email addresses.
I'm not sure how I would put that all together with the type of file I described above.
Any suggestions.
My goal is to do this first in the easiest way and then in the most modern way ( I have a book on collections and generics, but I am still assimilating it ).
Thanks in advance for any help or ideas
Steve

A: The trendy answer is to use the JSON format, but if a .properties file works for your use case, go for it.  Avoid storing it in the web.xml as your data is larger that the standard key value parameter.
This java json lib that has some upvotes.
https://stackoverflow.com/questions/338586/a-better-java-json-library/785066#785066


text:
Q: How to make Fibonacci series to print out single digit Below is a small project for my year one submission. But in that series, an odd number input doesn't print that number of numbers from the series, instead, it adds one to the odd number, which then becomes an even number, then print out that number of numbers from the series. I want to enable it to accept odd numbers too. How do do that? I thought of having two while loops, but i am unsure.
My code (without the header files and the main functions):
                int N;
                printf("Welcome to Fibonacci Series Mode.\n\nEnter how many numbers do you want from the series, from the start (Only Even Numbers): ");
                scanf("%d", &N);
                float x = 0;
                float y = 1;
                float xy;
                int F = 1;
                while ( F <= N ){
                    printf("\n%.0lf", x);
                    Sleep(250);
                    printf("\n%.0lf", y);
                    Sleep(250);
                    xy = x + y;
                    y += xy;
                    x = xy;
                    F++;
                }

A: What I am understanding from your code, and your question also, that is that the current code is printing only even numbers of Fibonacci Numbers. And that is true as you can see that in the while loop, there are two numbers printing in the same iteration. So, if you want an odd number of numbers from the series, you have to print one number at a time.
Also, note what is happening in your code.
Initially x = 0, y = 1
Then, xy = 0 + 1 = 1, (the third number in the Fibonacci Series)
At the next line, y gets one step ahead of xy. That is y = y + xy, that means if the xy variable holds the nth number in the Fibonacci Series, then, after this assignment, variable y holds the n+1th number of the series. And setting x = xy gets the n th term.
So in each iteration of the while loop, you are printing two values of the Fibonacci Series, also the variables x and y are jumping two steps forward at the same time.
To support odd integers, I would do something like following. Note I am using integer type variables as all the numbers in the Fibonacci Series are integers.
void print_first_n_fibo( int n ){
    int x = 0, y = 1;
    if(n == 1){
        printf("0\n");
    }
    else if(n == 2){
        printf("0\n1\n");
    }
    else{
        int current_term = 3;
        while(current_term <= n){
            int xy = x + y;
            printf("%d\n",xy);
            x = y;
            y = xy;
            current_term++;
        }
    }

}

This function is generalized. It prints any first n terms of the Fibonacci Series, regardless of n being even or odd.


text:
Q: Multi Thread Processing with Parallel.Foreach c# .net4.5.1 I have an IEnumerable<customClass> object that has roughly 10-15 entries, so not a lot, but I'm running into a System.IO.FileNotFoundException when I try and do
Parallel.Foreach(..some linq query.., object => { ...stuff....});
with the enumerable. Here is the code I have that sometimes works, other times doesn't:
        IEnumerable<UserIdentifier> userIds = script.Entries.Select(x => x.UserIdentifier).Distinct();

        await Task.Factory.StartNew(() =>
        {
            Parallel.ForEach(userIds, async userId =>
            {
                Stopwatch watch = new Stopwatch();
                watch.Start();

                _Log.InfoFormat("user identifier: {0}", userId);
                await Task.Factory.StartNew(() =>
                {
                    foreach (ScriptEntry se in script.Entries.Where(x => x.UserIdentifier.Equals(userId)))
                    {
                        //    // Run the script //
                        _Log.InfoFormat("waiting {0}", se.Delay);
                        Task.Delay(se.Delay);
                        _Log.InfoFormat("running SelectionInformation{0}", se.SelectionInformation);

                        ExecuteSingleEntry(se);
                        _Log.InfoFormat("[====== SelectionInformation {1} ELAPSED TIME: {0} ======]", watch.Elapsed,
                            se.SelectionInformation.Verb);
                    }

                });

                watch.Stop();
                _Log.InfoFormat("[====== TOTAL ELAPSED TIME: {0} ======]", watch.Elapsed);
            });
        });

When the function ExecuteSingleEntry is ran, there is a function a few calls deep within that function that creates a temp directory and files. It seems to me, that when I run the parallel.foreach the function is getting slammed at once by numerous calls (I'm testing 5 at once currently but need to handle about 10) and isn't creating some of the files I need. But if I hit a break point in the file creation function and just F5 every time it gets hit I don't have any problems with a file not found exception being thrown.
So, my question is, how can I achieve running a subset of my scripts.Entries in parallel based on the user id within the script entries with a delay of 1 second between each different user id entries being started?
and a script entry is like:
UserIdentifier: 141, SelectionInformation: class of stuff, Ids: list of EntryIds, Names: list of Entry Names
And each user identifier can appear 1 or more times in the array. I want to start all the different user identifiers, more or less, at once. Then Task out the different SelectionInformation's tied to a script entry.
scripts.Entries is an array of ScriptEntry, which is as follows:
    [DataMember]
    public TimeSpan Delay { get; set; }

    [DataMember]
    public SelectionInformation Selection { get; set; }

    [DataMember]
    public long[] Ids { get; set; }

    [DataMember]
    public string Names { get; set; }

    [DataMember]
    public long UserIdentifier { get; set; }

I referenced: Parallel.ForEach vs Task.Factory.StartNew to obtain the
Task.Factory.StartNew(() => Parallel.Foreach({ }) ) so my UI doesn't lock up on me

A: There are a few principles to apply:

*

*Prefer Task.Run over Task.Factory.StartNew. I describe on my blog why StartNew is dangerous; Run is a much safer, more modern alternative.

*Don't pass an async lambda to Parallel.ForEach. It doesn't make sense, and it won't work right.

*Task.Delay doesn't do anything by itself. You either have to await it or use the synchronous version (Thread.Sleep).

(In fact, in your case, the internal StartNew is meaningless; it's already parallel, and the code - running on a thread pool thread - is trying to start a new operation on a thread pool thread and immediately asynchronously await it???)
After applying these principles:
await Task.Run(() =>
{
  Parallel.ForEach(userIds, userId =>
  {
    Stopwatch watch = new Stopwatch();
    watch.Start();

    _Log.InfoFormat("user identifier: {0}", userId);
    foreach (ScriptEntry se in script.Entries.Where(x => x.UserIdentifier.Equals(userId)))
    {
      //    // Run the script //
      _Log.InfoFormat("waiting {0}", se.Delay);
      Thread.Sleep(se.Delay);
      _Log.InfoFormat("running SelectionInformation{0}", se.SelectionInformation);

      ExecuteSingleEntry(se);
      _Log.InfoFormat("[====== SelectionInformation {1} ELAPSED TIME: {0} ======]", watch.Elapsed,
          se.SelectionInformation.Verb);
    }

    watch.Stop();
    _Log.InfoFormat("[====== TOTAL ELAPSED TIME: {0} ======]", watch.Elapsed);
  });
});


text:
Q: ListItem Value not updating on ItemUpdated, only after hitting Refresh I am new to Sharepoint.
I have an EventReceiver hooked to an ItemUpdated event and I want to write a text in a field.
When I upload a file the event triggers ok, it goes through the code on debugging, seems to update but my property does not receive the text it's supposed to. However after I hit refresh on the page, I can see the updated value.
Here's my code
    public override void ItemUpdated(SPItemEventProperties properties)
    {
        base.ItemUpdated(properties);

        string folderPath = string.Empty;
        SPListItem item = properties.ListItem;
        if (item.File.ParentFolder != null)
        {
            folderPath = item.File.ParentFolder.ServerRelativeUrl;
        }

        AssignPropertyToField("Folder Name", item, folderPath);
    }

    private void AssignPropertyToField(string fieldName, SPListItem item, string folderPath)
    {
        item[fieldName] = folderPath;

        this.EventFiringEnabled = false;
        item.SystemUpdate();
        this.EventFiringEnabled = true;
    }

Thank you in advance for suggestions,
Regards,

A: If possible, try ItemUpdating instead of ItemUpdated.
Since ItemUpdated is asynchronous, you should not count on it being called before the page is refreshed. With ItemUpdating, note that the list item has not yet been saved so you do not need to call SystemUpdate.
public override void ItemUpdating(SPItemEventProperties properties)
{
    string folderPath = string.Empty;
    SPListItem item = properties.ListItem;
    if (item.File.ParentFolder != null)
    {
        folderPath = item.File.ParentFolder.ServerRelativeUrl;
    }
    properties.AfterProperties["FolderNameInternalName"] = folderPath;
}

In your case, the question is going to be whether you will be able to retrieve the updated parent folder information within the ItemUpdating event. My sample code above will take the previously existing folder information. This code will give you the wrong URL if the file is being moved to a different folder.

A: You can call item.Update() instead of item.SystemUpdate()
Note that this way the ItemUpdated event handler will be called twice, so you need to make sure to only do the update if item[fieldName] is different from folderPath in AssignPropertyToField, to avoid infinite loop.

A: What you can do, is to define in the elements.xml in the definition of the ItemUpdated  receiver that it should be run synchronous. See this http://msdn.microsoft.com/en-us/library/ff512765.aspx


text:
Q: Windows Composite device (usb audio class and custom bulk interface) via libusb? So we're looking to make a device for an internal test fixture that is a composite USB device with a standard audio class interface and a custom bulk interface.  It's primary target is Windows10.
We'd like to use libusb for the custom bulk interface  and the built in usbaudio.sys for the audio interface.
Is this possible to manage?  I've read it wasn't possible 6 years ago, but things may have progressed so I'm asking again.


text:
Q: Load denied by X-Frame-Options: domain.com/attachments/do-upload does not permit framing I was getting an error related to X-frame-Options, After lot of googling i found a solution.
Problem:
Load denied by X-Frame-Options: domain.com/attachments/do-upload does not permit framing

A: I solve this issue by adding

Header always unset X-Frame-Options

Add this to bottom of configuration file ( /etc/apache2/apache2.conf).
And restart the apache. ( service apache2 restart)


text:
Q: HTML5 audio tag not working on react-native-webview on android but works on IOS I have a react-native application where i load this page (https://vibrez-rugby.com/perpignan-en-direct/) in a webview using react-native-webview
I use react-native-webview 10.3.2 and android 7.0 to test
Everything works fine on ios but on android, the audio tag is disabled.
click to see audio tag on android
I can't find the problem, thank you very much for your help.

A: Old question, but I was having the same problem and found an solution for it, just wanted to share what worked for me
The audio src must be an https url, ios was accepting http ones but for android it has to be a secure address, or it won't load the file


text:
Q: php importing csv into database I have a csv file with 65000 records which i need to import into my database.
I have tried following code but real slow.
Is they anyway I can do this faster.
@set_time_limit(1200);
    $file = './csvFiles/aw_Products.csv';
    $handle = fopen( $file , 'r');
    while (($row = fgetcsv($handle)) !== false) {
        if( is_integer($row[0]) || $row[0] != 0 )
        {
            $product = new Product();
            $product->merchant_id       = $row[0];
            $product->merc_product_id   = $row[1];
            $product->product_id        = $row[2];
            $product->product_name      = $row[3];
            $product->product_desc      = htmlentities($row[4]);
            //$product->keywords            = htmlentities($row[6]);
            $product->category_id       = $row[5];
            $product->link_url          = $row[6];
            $product->image_url         = $row[7];
            $product->price             = $row[8];
            $product->delivery_cost     = $row[9];
            //$product->deliveryAvailable   = $row[12];
            //$product->deliveryDetails = $row[13];
            //$product->valid_to            = $row[14];
            //$product->valid_from      = ($row[3] == 'yes') ? 1 : 0;

            if( Product::find_by_id( $row[0] ) )
                $product->updateRecord();
            else
                $product->createRecord();
        }
        sleep (1);
    }
    fclose($handle);

A: sleep() is probably the culprit.  But I am also wondering about this: Product::find_by_id() because it might be doing a SELECT query for every INSERT.  You might think about making a single SELECT query to get all of the existing DB keys into a PHP array, then you can use *in_array()* to check whether to UPDATE or INSERT.  Probably goes without saying, but you will want to add to the PHP array if you INSERT.

A: Give up sleep() and use prepared statements for mysql insert/updates.


text:
Q: -n redundant in command -v tests? When testing for the existence of a command,
[ -n "$(command -v foo)" ]

and
[ "$(command -v foo)" ]

seem functionally equivalent, yet most examples I've seen include the -n test explicitly. I assume that if a command does not exist, that's equivalent to:
[ "" ]

Is it bad practice to omit -n?

A: Regardless of using -n or not, you are testing the output of the command builtin. I would test it's return value:
if command -v "$cmd" >/dev/null 2>&1 ; then
    echo "command $cmd exists"
fi


text:
Q: How to filter a Table type column by values of an adjacent column I want to filter the content of each row of a Table column using values from other columns of the same row of the main table.
I have a table like this, with a Table type column:

Specifically, I want to use the values of FirstLogin to filter the content of the AddIndex tables,  using the column SessionStart.
I thought using Table.SelectRows but it seems that it doesn't differentiate well columns of the main table from the embedded table.
Table.SelectRows([AddIndex], each [SessionStart] > _[FirstLogin])

I would appreciate any idea. Thanks.

A: Assuming your table look like this

Id
FirstLogin
AddIndex

1
01/01/2020
[Table]

2
01/01/2020
[Table]

I have created this calculation. Source is the table above.
let
    Source =
    Table.FromRecords(
        {
        [Id = 1 , FirstLogin = #date(2020,01,01),AddIndex = Table.FromRecords({[SessionId = 1, SessionStart = #date(2020,01,01)],[SessionId = 2, SessionStart = #date(2020,02,01)]})],
        [Id = 2 , FirstLogin = #date(2020,01,01),AddIndex = Table.FromRecords({[SessionId = 1, SessionStart = #date(2020,01,01)],[SessionId = 2, SessionStart = #date(2020,02,01)]})]
        }
        ),

    Step2 = Table.AddColumn(Source, "AddIndexFiltered", (row) => Table.SelectRows(row[AddIndex],each [SessionStart] = row[FirstLogin])),
    #"Expanded AddIndexFiltered" = Table.ExpandTableColumn(Step2, "AddIndexFiltered", {"SessionId", "SessionStart"}, {"SessionId", "SessionStart"})
in
    #"Expanded AddIndexFiltered"

Output

Id
FirstLogin
AddIndex
SessionId
SessionStart

1
01/01/2020
[Table]
1
01/01/2020

2
01/01/2020
[Table]
1
01/01/2020

A: You may use following approach:
filter = Table.ReplaceValue(YourLastStep, each [FirstLogin], 0,(a,b,c)=>
                            Table.SelectRows(a, each [SessionStart] > b),{"AddIndex"})


text:
Q: url hide only domain name show in url my link is www.example.com/#about
I want to hide #about from url.
I have created a html page when I click about then scroll should go at about section on same page.but #about show in url. I want to hide #about. #etc my page working same but hide id after (#etc) only want example.com
not want a www.example.com/#etc.

A: Please find the link to a fiddle I have created. Hope this helps :)
JS File
$(document).ready(function() {
  $('a').on("click", function(e) {

    var scrollTo = e.toElement.text
    console.log($(this).text())
    var posTop = $("#" + scrollTo).offset().top;
    console.log(posTop);
    e.preventDefault();
    e.stopPropagation();
    $('html, body').scrollTop(posTop);
    console.log(window.location);

  });
})


text:
Q: Node CLI Unit Testing I have a node module I am working on, and I want to write unit tests for it, however I am confused on how I would pass arguments (required for the CLI) to node through a testing suite.
Lets assume (for brevity) the module name is J, so I would call it like...
$ j --file test.js --file test2.js

how do i recreate those --file calls when I am writing my testing suite?

A: You can use node's child process module to run additional command line processes. This link can give you more info on syntax; I recommend also checking out the promised version of child-process.
var spawn = require('child_process').spawn;

spawn('j', ['--file', 'test.js', '--file', 'test2.js'])
  .progress(function(childProcess){
    // any logic you want to do here while process is running
  })
  .then(function(result){
    // command was executed
    // write tests here
  })
  .fail(function(err){
    // maybe 1 last test to make sure there was no test
  });

As far as unit-testing suites, I expect anything your comfortable with would work (mocha/chai etc.)


text:
Q: What is the correct way to include my new functions and scripts in WordPress? To include new functions we can write them in the theme's functions.php. But I have to write my own functions in a new file rather altering the theme's function.php. I can write any custom js action in footer.php, but I need to write it in other file. How can I do this? Is there any correct way to do this?

A: You can simply use require, require_once, include or include_once functions to include custom PHP files in your theme.
require( 'folder/custom.php' );

Usually you should keep your custom PHP files in a folder.
Developers vote against using require_once because it is a little slower than require since it requires the system to keep a log of what's already been included/required.

A: For adding JavaScript code in WordPress, you can create a .js file and include it in following way, in your theme's functions.php
/**
 * Proper way to enqueue scripts
 */
function theme_name_scripts() {

    wp_enqueue_script( 'script-name', get_template_directory_uri() . '/js/example.js', array(), '1.0.0', true );
}

add_action( 'wp_enqueue_scripts', 'theme_name_scripts' );

Refer https://codex.wordpress.org/Function_Reference/wp_enqueue_script


text:
Q: Variable assignment before declaration I have this piece of code:
x = 3

if x == 2:
    global L, M, S
    L, M, S =   -1.982373595    ,   16.54777487     ,   0.080127429

elif x == 3:
    global L, M, S
    L, M, S =   -1.419991255    ,   16.00030401     ,   0.072634432

elif x == 4:
    global L, M, S
    L, M, S =   -1.714869347    ,   15.62817269 ,   0.071889214

print(L, M, S)

I always get a SyntaxError for line 7 (SyntaxError: name 'L' is assigned to before global declaration).

A: Just remove global lines from the code. However if you are using a function then use it like this:
L, M, S = 0, 0, 0

def foo(x):
    global L, M, S
    if x == 2:
        L, M, S = -1.982373595,   16.54777487,   0.080127429

    elif x == 3:
        L, M, S = -1.419991255,   16.00030401,   0.072634432

    elif x == 4:
        L, M, S = -1.714869347,   15.62817269,   0.071889214

foo(3)
print(L, M, S)

A: The global declaration is unnecessary. Something like this should solve your problem.
x = 3

if x == 2:
    L, M, S =   -1.982373595    ,   16.54777487     ,   0.080127429

elif x == 3:
    L, M, S =   -1.419991255    ,   16.00030401     ,   0.072634432

elif x == 4:
    L, M, S =   -1.714869347    ,   15.62817269 ,   0.071889214

print(L, M, S)

That being said, you should probably define L,M,S as something in the null case that none of the ifs are called, so that your file never returns them before assignment. Maybe add something like :
...

else:
    L,M,S = none, none, none

print(L, M, S)

Below is a useful resource about the global keyword.
https://www.programiz.com/python-programming/global-keyword


text:
Q: Problema en servidor de correo Actualmente tengo un VPS, con cuentas de CPanel para 3 dominios dentro del que tengo abaco.edu.pe, se realizó la solicitud a Google for Education para que nos otorguen algunas cuentas de correo electrónico gratuitas.
El problema es que, después de haber realizado las configuraciones de Entradas MX y seguido la guía de G Suite for Education para la configuración de correo electrónico en CPanel aún así tengo problemas con la recepción de correos (los correos de salida están OK).
Si envío un correo desde Outlook, Gmail o incluso una misma cuenta del dominio (abaco.edu.pe) me indica que no pudo ser entregado.
Haciendo seguimiento me resulta este error:

The mail server could not deliver mail to xxxxxxxx@abaco.edu.pe. The account or domain may not exist, they may be blacklisted, or missing the proper dns entries.

A: Google Toolbox Check MX es una herramienta para para revisar el funcionamiento de los registros MX.
Para el dominio abaco.edu.pe indica que los registros DKIM y DMARC no están configurados, que falta el registro SPF válido y que no se encontraron intercambiadores de correo de Google. Para cada error se ofrece un enlace con detalles y el enlace al artículo de ayuda correspondiente.


text:
Q: Qt5 and CMake: add headers for AUTOMOC Qt with CMake often leads to trouble during linking.
After reading several posts and tries I found out that AUTOMOC takes source files given with add_executable but ignores my header files inside the include folder given with include_directories( inc ). After adding the header filed to add_executable the build was successful.
But what is the correct way to tell AUTOMOC the header files?
In my CMake CMakeLists.txt I use
set(CMAKE_AUTOMOC ON)
set(CMAKE_INCLUDE_CURRENT_DIR ON)
include_directories( inc )

set(QT5_MODULES Widgets)
find_package(Qt5 REQUIRED COMPONENTS ${QT5_MODULES})

add_definitions( -DQT_NO_KEYWORDS
                 -DQT_CORE_LIB
                 -DQT_GUI_LIB
                 -DQT_WIDGETS_LIB
                 -DQT_NO_DEBUG
                 -DROSCONSOLE_BACKEND_LOG4CXX
                 -fPIC)

add_executable( MyGui
                src/main.cpp
                inc/gui.h src/gui.cpp )

ament_target_dependencies( MyGui )
qt5_use_modules(MyGui ${QT5_MODULES})


text:
Q: Javascript How to use multiple function in html form submission to validate Html form driving me crazy.
I have a function that checks for mismatch passwords and if the username specified is already taken.
If you pass both of these checks then the form should submit, but it isn't.
It's not a db problem. I've checked that and it connects just fine.
The post in checkname and the post in the form both work when removing the double onsubmit argument. If anyone has any ideas please let me know :)
 Here is link  of the project I am currently working :
Functions and form:

function validatePassword() {
  var pass1 = document.getElementById("password").value;
  var pass2 = document.getElementById("confirm_password").value;

  if (pass1 != pass2) {
    alert("Passwords Do not match");
    document.getElementById("password").style.borderColor = "#E34234";
    document.getElementById("confirm_password").style.borderColor = "#E34234";
    return false;
  } else {
    return true;
  }
}

function checkname() {
  var name = document.getElementById("username").value;

  if (name) {
    $.ajax({
      type: 'post',
      url: 'checkdata.php',
      data: {
        user_name: name,
      },
      success: function(response) {
        $('#name_status').html(response);
        if (response == "OK") {
          return true;
        } else {
          return false;
        }
      }
    });
  } else {
    $('#name_status').html("");
    return false;
  }
}

function checkall() {
  var namehtml = document.getElementById("name_status").innerHTML;

  if ((namehtml) == "OK") {
    return true;
  } else {
    return false;
  }
}

Customer sign up
<form name="input" action="customer_insert.php" onsubmit=" return !!(validatePassword() & checkall());" method="post">

 Username: <input type="text" maxlength="45" name="username" id="username" onchange="checkname();" required="required">

 Password: <input type="password" maxlength="128" name="passwd1" id="password" required="required">

 Retype Password: <input type="password" maxlength="128" name="passwd2" id="confirm_password" required="required">

 First Name: <input type="text" maxlength="45" name="firstname" required="required">

 Last Name: <input type="text" maxlength="45" name="lastname" required="required">

 E-mail: <input type="email" name="email" required="required">
  <input type="submit" name="Signup" value="Signup">
</form>

A: Fixed it. Problem was directly using checkname() in the condition results in undefined return and therefor, the condition could never be met. Now I take part of the old checkall() and integrated it with your validate method. This works. Thanks!
function validateForm(){
    var a = validatePassword();
    var b;

    var namehtml=document.getElementById("name_status").innerHTML;

    if(namehtml=="OK")
    {
            b = true;
    }
    else
    {
            b = false;
    }

    if(a && b){

            return true;

    }
    else{

            return false;
    }
}


text:
Q: Clone() system call in linux What happens when I call clone system call by passing 0 as the stack_start?
According to manual pages on clone it should return -EINVAL, but when I do that, it is showing SIGSEGV (11) error.
clone(func,NULL,0,args);

should return -EINVAL, but its failing with SIGSEGV

A: According to linux kernel there is such a call chain:
sys_clone(...stack_start...) -> do_fork
do_fork(...stack_start...) -> copy_process
copy_process(...stack_start...) -> copy_thread
copy_thread(...stack_start...) on X86_32 OR copy_thread(...stack_start...) on X86_64
Looking at the copy_thread leads me to assumption that as this function doesn't check for stack_start correctness (sp argument in code) so after cloning we have a task with invalid stack pointer and first reference at zero address leads to SIGSEGV.
I'll suggest you to look at the glibc wrapper for clone function also.


text:
Q: Getting 0 instead of #ffffff from remote config Firebase at first launch -React-native- I'm using firebase remote config to set the color of an Icon. The first time the app is loaded the value loaded from firebase is 0, if a reload the app i get the correct color value #ffffff.
You can see the result in Xcode console in this screenShot:

Here is my remoteConfig config file:
async getRemoteConfig(t) {
    // const { t, i18n } = useTranslation();
    if (__DEV__) {
      firebase.config().enableDeveloperMode();
      console.log('running in dev mode');
    }

    // Set default values
    firebase.config().setDefaults({
      share_button_color:'#fff'
    });

    firebase
      .config()
      .fetch(0) // call like this fetch(0) to reset cache load new params from firebase,without this it takes 12h
      .then(() => {
        return firebase.config().activateFetched();
      })
      .then(async activated => {
        if (!activated) console.log('Fetched data not activated');
        else console.log('Fetched data activated');
      })
      //   .then(snapshot => {
      //     const hasExperimentalFeature = snapshot.val();

      //     if (hasExperimentalFeature) {
      //       enableSuperCoolFeature();
      //     }

      //     // continue booting app
      //   })
      .catch(console.error);
  },
};

Also here my component:

export default class ShareIcon extends Component {
  constructor(props) {
    super(props);
    this.state = {
      buttonColor: 'white',
    };
  }

  async componentDidMount() {
    await this.getShareButtonColor();
  }

  async getShareButtonColor() {
    const remoteButtonColorData = await firebase
      .config()
      .getValue('share_button_color');
    const buttonColor = remoteButtonColorData.val();
    console.log('buttonColor',buttonColor) // <===this is the console.log we see
    this.setState({buttonColor});          // in screenshot
  }

  render() {
    return (
      <TouchableOpacity
        hitSlop={{top: 10, left: 10, bottom: 10, right: 10}}
        style={styles.container}
        onPress={() => shareApp()}
        style={{marginLeft: 20}}>
        <Icon name="share-2" type="feather" color={this.state.buttonColor} />
      </TouchableOpacity>
    );
  }
}


text:
Q: How to check Internet connection in android every N seconds I want to check state of Internet connection every N seconds
how I can do it
I want to send mail when received SMS in android device

A: Check internet connection every N seconds:
Create a NetworkUtils with isNetworkAvailable() method that returns true or false according to connection status:
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

public class NetworkUtils {
    public static boolean isNetworkAvailable(Context context) {
        ConnectivityManager connectivityManager
                = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
        return activeNetworkInfo != null && activeNetworkInfo.isConnected();
    }
}

Create a CheckConnection() class that checks the connection every N seconds:
class CheckConnection extends TimerTask {
    private Context context;
    public CheckConnection(Context context){
        this.context = context;
    }
    public void run() {
        if(NetworkUtils.isNetworkAvailable(context)){
            //CONNECTED
        }else {
            //DISCONNECTED
        }
    }
}

You can use CheckConnection class from your activity like:
Timer timer = new Timer();
final int MILLISECONDS = 5000; //5 seconds
timer.schedule(new CheckConnection(this), 0, MILLISECONDS);

Hope this helps!


text:
Q: http error: curl error 7: failed to connect to wordpress.org port 80 I freshly installed an Ubuntu server 16.04 with LEMP and wordpress.
But it seems that I have missed a step in the process, as I have the following error on the websites.
http error: curl error 7: failed to connect to wordpress.org port 80.

The sites is working fine beside that it is configure in a virtual machine as I'm developing a website, first on my local machine to test everything in local.
Here is my config file:
server {
        listen 80;
        server_name 192.168.1.3; #ipaddress;
        root /usr/share/nginx/mrupgrade.be/;
        index index.php index.html index.htm;

        error_page 404 /404.html;
        error_page 500 502 503 504 /50x.html;

        location = /50x.html    {
                root /usr/share/nginx/html;
        }
        location / {
                try_files $uri $uri/ /index.php;
        }

        error_page 404 /404.html;
        error_page 500 502 503 504 /50x.html;

        location ~ \.php$ {
                try_files $uri = 404;
                fastcgi_pass unix:/run/php/php7.0-fpm.sock;
                fastcgi_index index.php;
                fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
                include fastcgi_params;
                root /usr/share/nginx/mrupgrade.be/;
                }
        }

Note that I have configured the firewall with those rules:
Thanks in advance for your help.
Chain INPUT (policy ACCEPT)
target     prot opt source               destination
ACCEPT     tcp  --  anywhere             anywhere             state NEW tcp dpt:http
ACCEPT     all  --  anywhere             anywhere             state RELATED,ESTABLISHED

Chain FORWARD (policy ACCEPT)
target     prot opt source               destination

Chain OUTPUT (policy ACCEPT)
target     prot opt source               destination
ACCEPT     all  --  anywhere             anywhere             state RELATED,ESTABLISHED

wp-config.php
<?php
/**
 * The base configuration for WordPress
 *
 * The wp-config.php creation script uses this file during the
 * installation. You don't have to use the web site, you can
 * copy this file to "wp-config.php" and fill in the values.
 *
 * This file contains the following configurations:
 *
 * * MySQL settings
 * * Secret keys
 * * Database table prefix
 * * ABSPATH
 *
 * @link https://codex.wordpress.org/Editing_wp-config.php
 *
 * @package WordPress
 */

// ** MySQL settings - You can get this info from your web host ** //
/** The name of the database for WordPress */
define('DB_NAME', 'mysite_wp_db');

/** MySQL database username */
define('DB_USER', 'mysite_user');

/** MySQL database password */
define('DB_PASSWORD', 'mysite');

/** MySQL hostname */
define('DB_HOST', 'localhost');

/** Database Charset to use in creating database tables. */
define('DB_CHARSET', 'utf8');

/** The Database Collate type. Don't change this if in doubt. */
define('DB_COLLATE', '');

/**#@+
 * Authentication Unique Keys and Salts.
 *
 * Change these to different unique phrases!
 * You can generate these using the {@link https://api.wordpress.org/secret-key/1.1/salt/ WordPress.org secret-key service}
 * You can change these at any point in time to invalidate all existing cookies. This will force all users to have to log in again.
 *
 * @since 2.6.0
 */
define('AUTH_KEY',         'put your unique phrase here');
define('SECURE_AUTH_KEY',  'put your unique phrase here');
define('LOGGED_IN_KEY',    'put your unique phrase here');
define('NONCE_KEY',        'put your unique phrase here');
define('AUTH_SALT',        'put your unique phrase here');
define('SECURE_AUTH_SALT', 'put your unique phrase here');
define('LOGGED_IN_SALT',   'put your unique phrase here');
define('NONCE_SALT',       'put your unique phrase here');

/**#@-*/

/**
 * WordPress Database Table prefix.
 *
 * You can have multiple installations in one database if you give each
 * a unique prefix. Only numbers, letters, and underscores please!
 */
$table_prefix  = 'wp_';

/**
 * For developers: WordPress debugging mode.
 *
 * Change this to true to enable the display of notices during development.
 * It is strongly recommended that plugin and theme developers use WP_DEBUG
 * in their development environments.
 *
 * For information on other constants that can be used for debugging,
 * visit the Codex.
 *
 * @link https://codex.wordpress.org/Debugging_in_WordPress
 */
define('WP_DEBUG', false);

/* That's all, stop editing! Happy blogging. */

/** Absolute path to the WordPress directory. */
if ( !defined('ABSPATH') )
    define('ABSPATH', dirname(__FILE__) . '/');

/** Sets up WordPress vars and included files. */
require_once(ABSPATH . 'wp-settings.php');

/var/www/mrupgrade.be/public_html the site location that's nginx site config
user www-data;
worker_processes auto;
pid /run/nginx.pid;

events {
    worker_connections 768;
    # multi_accept on;
}

http {

    ##
    # Basic Settings
    ##

    sendfile on;
    tcp_nopush on;
    tcp_nodelay on;
    keepalive_timeout 65;
    types_hash_max_size 2048;
    # server_tokens off;

    # server_names_hash_bucket_size 64;
    # server_name_in_redirect off;

    include /etc/nginx/mime.types;
    default_type application/octet-stream;

    ##
    # SSL Settings
    ##

    ssl_protocols TLSv1 TLSv1.1 TLSv1.2; # Dropping SSLv3, ref: POODLE
    ssl_prefer_server_ciphers on;

    ##
    # Logging Settings
    ##

    access_log /var/log/nginx/access.log;
    error_log /var/log/nginx/error.log;

    ##
    # Gzip Settings
    ##

    gzip on;
    gzip_disable "msie6";

    # gzip_vary on;
    # gzip_proxied any;
    # gzip_comp_level 6;
    # gzip_buffers 16 8k;
    # gzip_http_version 1.1;
    # gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;

    ##
    # Virtual Host Configs
    ##

    include /etc/nginx/conf.d/*.conf;
    include /etc/nginx/sites-enabled/*;
}

My /etc/nginx/nginx.conf
#mail {
#   # See sample authentication script at:
#   # http://wiki.nginx.org/ImapAuthenticateWithApachePhpScript
#
#   # auth_http localhost/auth.php;
#   # pop3_capabilities "TOP" "USER";
#   # imap_capabilities "IMAP4rev1" "UIDPLUS";
#
#   server {
#       listen     localhost:110;
#       protocol   pop3;
#       proxy      on;
#   }
#
#   server {
#       listen     localhost:143;
#       protocol   imap;
#       proxy      on;
#   }
#}

So in image everything is fine expect some stuff maybe a lib is missing or I don't know I installed fpm fast cgi.
The wordpress Can't connect to the web eith http request.

I don't really know what it could be any clue would be welcome.
Thanks in advance for your help.

A: Are your server called wordpress.org ?
According to your config file it's:
server_name 192.168.1.3; #ipaddress;

If you want to use a servername locally, you would have to enter ip-address and name into /etc/hosts, and if it must be accessible externally, you must have a hostname and dns-entry by your ISP. And you must set the appopriate port-forwarding in your router.

A: If curl is the problem, I would first try to run it from the console to check if is a network related issue (firewall, etc.)
It seems that if you have SELINUX enabled this could cause the webserver to prevent the requests. As seen here https://wordpress.org/support/topic/error-curl-error-7-3/
If curl works from the console and you don't have SELINUX enabled, I would than test a small php script to verify that curl is working, and for which hosts to better debug this.
Cheers

A: Check for SELinux. It turned itself back on and was interfering with CURL.
To disable the SELinux temporarily until the Linux box is rebooted, execute setenforce 0.


text:
Q: The identifier generation strategy for this entity requires the ID field to be populated before EntityManager#persist() is called I'm tying to create one to many relations
A have class
class Interview {

    /**
     * @OneToMany(targetEntity="Question", mappedBy="question")
     */
    private $questions;

    public function __construct() {
        $this->questions = new ArrayCollection();
    }

    public function __toString() {
        return $this->id;
    }

    /**
     * @return Collection|Question[]
     */
    public function getQuestions() {
        return $this->questions;
    }

    /**
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;
    ......
}

another
class Question {

    /**
     * @ManyToOne(targetEntity="Interview", inversedBy="interview")
     * @JoinColumn(name="interview_id", referencedColumnName="id")
     */
    private $interview;

    public function getInterview() {
        return $this->interview;
    }

    public function setInterview(Interview $interview) {
        $this->interview = $interview;
        return $this;
    }

    /**
     * @ORM\Column(type="integer")
     * @ORM\Id
     */
    private $interview_id;
    ......
}

and Controller for all this
if ($form->isSubmitted() && $form->isValid()) {

        $interview = new Interview();
        $question = new Question();

        $em->persist($interview);

        $question->setInterview($interview);
        $question->setTitle($request->get('title'));
        $em->persist($question);
        $em->flush();

        return $this->redirectToRoute('homepage');
}

i'm receiving an error:

Entity of type AppBundle\Entity\Question is missing an assigned ID for
  field 'interview_id'. The identifier generation strategy for this
  entity requires the ID field to be populated before
  EntityManager#persist() is called. If you want automatically generated
  identifiers instead you need to adjust the metadata mapping
  accordingly.

Don't understand what the problem and how to fix it.

A: To enforce loading objects from the database again instead of serving them from the identity map. You can call $em->clear(); after you did $em->persist($interview);, i.e.
$interview = new Interview();
$em->persist($interview);
$em->clear();

A: It seems like your project config have an error in doctrine mapped part.

If you want automatically generated identifiers instead you need to
  adjust the metadata mapping accordingly.

Try to see full doctrine config and do some manipulation with

auto_mapping:         false
  to true as example or something else...

Also go this , maybe it will be useful.

A: I am sure, its too late to answer but maybe someone else will get this error :-D
You get this error when your linked entity (here, the Interview entity) is null.
Of course, you have already instantiate a new instance of Interview.But, as this entity contains only one field (id), before this entity is persited, its id is equal to NULL. As there is no other field, so doctrine think that this entity is NULL. You can solve it by calling flush() before linking this entity to another entity


text:
Q: In C#, is a dictionary whose keys are of type Type slower than a dictionary whose keys are of type ulong? I currently have the following:
ConcurrentDictionary<ulong, MyEventHandler> eventHandlers;

and an indefinite number of classes:
class MyClass1
{
    public const ulong MyKey = 0;
    ...
}

class MyClass2
{
    public const ulong MyKey = 1;
    ...
}

...etc...
My dictionary is to hold an event handler that corresponds to the type of class. Right now I'm using the MyKey member as the key to my dictionary, which works fine.
However, when other classes are developed now and in the future, I don't want to make the developer worry about having to have a key.
How much slower (if at all) is doing the following:
ConcurrentDictionary<Type, MyEventHandler> eventHandlers;

and then using the typeof operator to get the Type to index into my dictionary?
That way I never have to worry about a key.
I do care a lot about speed, because even though the dictionary likely wont have more than 100 entries, typeof will be called and the dictionary will be accessed thousands of times per second.

A: Types are represented and identified by metadata tokens, which I guess are 32-bit integers. The typeof operator makes a lookup in metadata tables to find the Type represented by the metadata token.
I believe that the JIT compiler will optimize metadata table accesses very well and therefore I don't think that you should notice any performance difference in reality. I would actually not be surprised if using Type as key would even prove to be slightly faster.
Since using Type as key would make the code much easier to maintain I would recommend that approach unless you can prove that the other approach is clearly more performant.

A: If your dictionary is a singleton/multiton you can create a generic type to speed up indexation by this pattern :
static class MyHandler<T>
{
    static public MyEventHandler Value;
}

instead of
CurrentDictionary[typeof(Class1)]

you can do
MyHandler<Class1>.Value

A: This depends on how GetHashCode() is implemented. WHen the .Net framework code "finds" an object in a dictionary, it calls this method to perform the search. Obviously, in any Dictionary that uses a key based on a type where the implementation of GetHashCode() takes substantially longer than simply retrieving the value of a long, or a uLong, that dictionary will exhibit proportionally poorer performance.