How to design flexible wcf service which will work in lan and internet

Question: i am new in wcf service. still reading books to acquire knowledge. my company has many offices in our city but one head office. my company has one static IP. my company plan to host a wcf service in HQ server which can be reach by static IP over the internet and other office is connected each other by VPN. our company want me to develop a wcf service which will be using to handle company data among all the pc of HQ and also among all the pc of other offices. also people can outside will be able to connect to that wcf service.
company want that when any one try to connect to our service from HQ office then HQ lan will be used to connect to that service.
when any one try to connect to our service from our other offices then WAN or VPN connection will be used.
when any one try to connect to our service from other place or home then connection will be made through internet.
i am new in WCF so not being able to think how to design this kind of service with WCF which will be hosted in our HQ server which has static IP.
so guide me is there any tweak requited in coding or in config file where we specify various bindings.
i guess that we need to specify various binding in service config file. so just guide me how do i design or write the config file for service end which can be requested over the LAN, VPN and as well as internet. if possible give me a sample copy of config file for service end. thanks
Comment: As long as your firewall and security allows communication on the ports you configure in your bindings, it will work. This question is too open to have a discrete answer. If this is new work, and using HTTP is ok, use Web API instead. http://stackoverflow.com/q/9348639/659190
Answer: LAN vs WAN vs VPN is at a too lower newtork level for WCF. Assuming you use say basicHttpBinding and host your WCF service in IIS that runs in the server in HQ that has a static IP, your internet users will be able to come to your service using the external IP (static IP) or the domain name if there is one. For intranet (LAN, WAN, etc), the users can use the internal IP, which you can get by pinging the server from within your network. Again assuming that the path between the computers where WCF will be consumed and where WCF service runs does not cut across firewalls and stuff, you can use a netTcp binding which can be slightly more performant but not worth the trouble if your organization has lots of red tape to opening ports and stuff if there are firewalls in between. Generally, 80 and 443 are not blocked.
Comment: just tell me do i need to handle this at wcf client end or server end in config file.can u please give me sample config entry for wcf service server end & client end.
how do i detect that when client end will connect then it is using internet or lan ?
Comment: How it is typically done is as follows. When you create a service reference for your WCF service, the URI details are added to the config in the client side. For intranet clients, you will use the internal IP and for the external ones, you will use the static IP. It is possible to detect intranet versus internet but is a complex thing to do and the installation normally takes care of this part and the correct address is put in as part of installation. I'm assuming more like a thick client, .NET ofcourse.
Comment: do u mean that user need to change Endpoint IP address in config before run from LAN? please discuss this issue. thanks
Comment: No, I did not mean that. I meant the IP will be put into the config file at the time of installation by the installer. I was assuming same installation will not be used from both intranet and internet. If my assumption is not correct, it gets tricky. In that case, you will be better of connecting to the WCF endpoint without using svcutil and dynamically determine the address to use. For example, you can call Dns.GetHostAddresses("www.yourdomain.com") to see if it resolves and connect or fallback to your internal IP.
Comment: @Thomas - Thomas I think you are asking the wrong question i.e. "how do I access WCF from my LAN?"  The answer is you never want to use WCF over your lan because it is typically much slower than just getting data over ADO.  Use the architecture I posted and you can make a service layer that gets data from WCF when necessary or from ADO (much faster).
Answer: We are working on a large project right now which I believe is similar to what you are working on.  We have many users who will be accessing this app from their desktop PC's as well as their mobile devices.  I designed a service layer that is very flexible that delivers optimal performance depending on if the user is local or remote (note that VPN = local).
I cannot give you every detail due to lack of space but here are the big pieces:
Create three Visual studio projects (or one solution with three projects): 1) Your app, 2) A service project (.dll), 3) A WCF project.
Your service project is where the action is.
In your service project, create an interface called something like IMyServices (this is standard WCF stuff):
[ServiceContract]
public interface IMyServices : IDisposable
{
    [OperationContract]
    IEnumerable<Allocation> GetAllocations();
}

Next, add a class like what you see below.  I call it ServiceRouter because if the user is remote, it routes the request to WCF but if the user is local it just gets data using ADO over the LAN.  Note that this class implments IMyServices.
public class ServiceRouter : IMyServices
{
    private readonly string ServiceURI;

    ///
    /// Routes data requests over the LAN if the client is connected locally or over a WCF service if the client is remote. Use this constructor to route data requests over the LAN.
    ///
    /// http://msdn.microsoft.com/en-us/library/ms735103.aspx
    ///
    public ServiceRouter()
    {
        ServiceURI = null;
    }

    ///
    /// Routes data requests over the LAN if the client is connected locally or over a WCF service if the client is remote.
    ///
    /// <param name="serviceURI">Fully qualified URI of a WCF server if the user is remote.  Pass null if the user authenticated on the LAN (including using VPN)</param>
    /// http://msdn.microsoft.com/en-us/library/ms735103.aspx
    ///
    public ServiceRouter(string serviceURI)
    {
        ServiceURI = serviceURI;
    }

    public IEnumerable<Allocation> GetAllocations()
    {
        IMyServices client = GetClient();
        var result = client.GetAllocations().ToList();
        CloseClient(client);
        return result;
    }

      #region WCFClient
    private IMyServices GetClient()
    {
        IMyServices _client;

        if (string.IsNullOrEmpty(ServiceURI))
            _client = new MYServices();
        else
        {
            _client = ChannelFactory<IMyServices>.CreateChannel(new BasicHttpBinding(), new EndpointAddress(ServiceURI));
            ((ICommunicationObject)_client).Open();
        }
        return _client;
    }

    private void CloseClient(IMyServices client)
    {
        ICommunicationObject wcfClient = client as ICommunicationObject;

        if (wcfClient != null)
        {
            if (wcfClient.State == CommunicationState.Faulted)
                wcfClient.Abort();
            else
                wcfClient.Close();
        }
        else
            ((IDisposable)client).Dispose();
    }
    #endregion
}

Next, in your service project, create a class for your services that implements IMyServices like this:
internal partial class MyServices : IMyServices
{
    public IEnumerable<Allocation> GetAllocations()
    {
        // access your db here
    }

Now here is how you you expose your services using WCF.    You will need to configure your web.config and you will need to reference the .dll file from your service project.
In your WCF project add a WCF service like what you see below.  Note this class inherits from ServiceRouter, which implements IMyService.  The code below is the ONLY code in the WCF project!  All this code does is create an instance of your ServiceRouter, passing it a null uri which tells it to get its data over the LAN.  Your WCF server and you DB server need to be able to communicate over the LAN for this to work of course.
public class MyWCFService : MyServiceProject.ServiceRouter
{
    public MyWCFService() : base()
    {
        // Since the WCF server is running on the local area network, this class only needs to create an instance of
        // the service router in local mode and retrive the requested data.  WCF serializes the data and sends it
        // back over the wire.
    }
}

Here is a fragment of how your web.config might look:
<service name="MyWCFService" behaviorConfiguration="xxx">
        <endpoint address="" binding="basicHttpBinding" bindingNamespace="http://blah.com" contract="MyServiceProject.IMyServices">

In your app project, add a reference to your service .dll file.  Look at your user's IP address and if it is local, use create instances of ServiceRouter passing null to the constructor.  If the user is remote, pass the URI of your wcf server when you create insances of Service router: i.e. ServiceRouter router = new ServiceRouter(myServerName);
Comment: thanks for answer.u said " Look at your user's IP address and if it is local" so i just like to know how do i know that user is local by IP address or not ?
Comment: I suggest you look on stackoverflow for that as it is a different question and there many different ways to do it.  There are no doubt many answers that are more detailed than what I can provide in these comments.
Answer: Thats a simple question of network configuration. Your service has one or more endpoints. So simple route the requests from the various networks to that/them.
Comment: just tell me do i need to handle this at wcf client end or server end in config file.can u please give me sample config entry for wcf service server end & client end.
how do i detect that when client end will connect then it is using internet or lan ?
Answer: Your question is a bit "tl;dr" and open-ended but can I suggest you learn the "ABC's" of WCF endpoints: Address, Binding, Contract?
If you'd like to use both HTTP and TCP for a single service endpoint can configure both binding types to the same endpoint.
From the article:

It is important to note is that these three elements are independent.
  A contract can     support many bindings and a binding can support
  many contracts. A service can have many endpoints (contract bound to
  address) coexisting and available at the same time. So if you want to
  expose your service via HTTP and use SOAP 1.1 for maximum
  interoperability, and also want to expose it via TCP using a binary
  wire encoding for maximum performance, the two resulting endpoints can
  reside side-by-side on top of the very same service.


How can I add a CC field to webform email send?

Question: Does anyone have a solution to adding a CC field to the /node/[nid]/webform/emails/xxx interface?
I have a client that wants to use a decently complex conditional email send solution in Drupal 7 webform, where based on various select lists, it will send an email to two places.

"firstname.lastname@example.com"
"email@example.com"

Allowing a real person to be notified and respond via REPLY-ALL to the email, and having the ticket system be updated with the communication in real time.
The ticket system can't handle getting a reply-to with both addresses in the single "TO:" line.
to: firstname.lastname@example.com,email@example.com breaks the system.
Has anyone solved this? built a module?  Have guidance on how to solve?
Thank you!
Answer: I have done some similar thing to send the email to another email-address. You can use the following solution for changing the content of the email or to add an attachment or things like this...
/**
 * Implements hook_mail_alter().
 */
function MYMODULE_mail_alter(&$message) {
  // Check message id
  if ($message['id'] == '...') {
    $email_key = 'new_email_key_if_you_want';

    // Block email which is sending right now.
    $message['send'] = FALSE;

    // send original email
    drupal_mail('MYMODULE', $email_key, $message['to'], language_default(), $message['params'], $message['from']);

    // send copy of the email.
    drupal_mail('MYMODULE', $email_key, 'email@example.com', language_default(), $message['params'], $message['from']);
  }
}

You can add this in an own module, in the MYMODULE.module.
Comment: Thank you.

Does `if($message['id']...)` allow me to define different CC addresses based on the which webform email condition is triggered?
Comment: Hi @alphex
Mh i'm not sure. Probably yes: each type of email in drupal gets a individual key. Either it is an email-key based on the webforms (each type of webform gets an own key) or, (and this would be bad for you) the key is based just on the module webform. You have to try.
Answer: I have done this by adding the below code to my custom module.
Use hook_mail_alter().
function mymodule_mail_alter(&$message) {
   if ($message['id'] == 'webform_submission') {
     if ($message['params']['node']->nid == 'webform_node_id') {
    $message['headers']['CC'] = 'firstname.lastname@example.com';
     }
   }
 }


rpivotTable not fitting in my Shiny Dashboard page

Question: I am using rpivoTable package in my shiny dashboard.
The problem is that my tables has close to 25 variables (columns) whereas I am only able to view 10 columns. Rest are out of view and there's no slider also to view them.
Best,
Answer: I find one way -- add css to that pivot
tags$head(tags$style( type = 'text/css',  '#pivot{ overflow-x: scroll; }')),
          rpivotTableOutput('pivot', width = "100%", height = "500px")

for example
UI
library(shiny)
library(rpivotTable)
library(shinydashboard)
shinyUI(dashboardPage(
  dashboardHeader(title = "example"),
  dashboardSidebar(disable = T),
  dashboardBody(

      tags$head(tags$style( type = 'text/css',  '#pivot{ overflow-x: scroll; }')),
      rpivotTableOutput('pivot', width = "100%", height = "500px")
  )

))

server
df=data.frame(lapply(1:25,function(i)i=rnorm(20)))
colnames(df)=as.character(letters[1:25])

shinyServer(function(input, output,session) {

  output$pivot <- renderRpivotTable({
    rpivotTable(data = df)
  })

})

Comment: @StevenBeaupré If i understand right you need somethink like `---
title: "Test"
output:
  flexdashboard::flex_dashboard:
    css: styles.css
---

```{r}
library(rpivotTable)
rpivotTable(iris)
``` ` in markdown  and `.rpivotTable{ overflow-x: scroll; }` in styles.css
Comment: Thanks for the prompt reply. But my output is not just a table its complete pivot structure. This is my output ....  output$pivot <- renderRpivotTable({
    rpivotTable(mydata)
  })
Comment: how you use it in ui ( or server part of UI)? add css where you code how to show your `output$pivot`
Comment: Add example to my answer
Comment: I am adding this pivot in a dashboard tab..
tabItem(tabName = "trains",
              fluidRow(br(),rpivotTable::rpivotTableOutput('pivot'))
      )
Comment: try `tabItem(tabName = "trains", fluidRow(br() ,
                                     tags$head(tags$style( type = 'text/css',  '#pivot{ overflow-x: scroll; }'))
                                     ,rpivotTable::rpivotTableOutput('pivot')) )`  or see my edit
Comment: @Batanichek Would it be possible to do the same without using `shiny` ? (how to pass custom `css` directly to a chunk in `flexdashboard`)


Find the limit of fraction powered by n

Question: $$\lim_{n\to\infty} \left({\frac{2n+1}{3n+2}}\right)^{n} = ?  $$
Simple method gives an indeterminate expression. Any idea how to think out this case?
Answer: HINT: $$0<\frac{2n+1}{3n+2}<\frac23$$ for $n\ge 1$.
Comment: Probably sounds quit cheesy, but officially your solution is much better than mine)
Comment: @Alex: Apparently not for the OP! Yours does have a certain baroque impressiveness. :-)
Answer: Brian's answer is right on the money. Another way to see it is noting the algebraic equality
$$\left(\frac{2n+1}{3n+2}\right)^n=e^{n\log\frac{2n+1}{3n+2}}$$
But
$$n\log\frac{2n+1}{3n+2}\xrightarrow [n\to\infty]{}-\infty$$
since $\,\log\frac{2}{3}<0\,$ , so the limit's like
$$\lim_{m\to-\infty}e^m=0$$
But I'd choose Brian's answer as it is way simpler...:)
Answer: if f(n) is less then a constant k which is less then 1, for large enough n, and all proceeding n, then as n tends to infinity $f(n)^n$=0, so the limit of your expression is zero.
Comment: Maybe could change to less than $k$ which is less than $1$, to make sure the criterion is not used on, for example,  $(1-1/n)^n$.
Answer: Probably a bit cumbersome but straightforward:
$$
\lim_{n \to \infty} \bigg(\frac{2n +1}{3n+2} \bigg)^n=\lim_{n \to \infty}\bigg( \frac{2}{3} \cdot \bigg(\frac{n+\frac{1}{2}}{n+\frac{2}{3}} \bigg)\bigg)^n = \lim_{n \to \infty}\bigg( \frac{2}{3} \cdot \bigg(\frac{n+\frac{2}{3}-\frac{1}{6}}{n+\frac{2}{3}}\bigg)\bigg)^n
=\lim_{n \to \infty}\bigg( \frac{2}{3} \cdot \bigg(1-\frac{1}{6n+4} \bigg)\bigg)^n= \lim_{n \to \infty}\bigg( \frac{2}{3} \bigg)^n \lim_{n \to \infty} \bigg(1-\frac{1}{6n+4} \bigg)^{(6n +4-4)\cdot \frac{1}{6}}=0 \cdot e^{-\frac{1}{6}} \cdot 1
= 0
$$

Find the limit of fraction powered by n


Does Composer patch core automatically?

Question: I am using Composer on a Lightning drupal distro. In my composer.json file I set enable-patching true. And I added one core patch for /patches/core-file_upload_ajax_message-1489692-68.patch. WHen I run composer update it applys 3 other patches. See output. Is Composer doing this by itself?
Applying patches for drupal/core
./patches/core-file_upload_ajax_message-1489692-68.patch (Incorrect handling of file upload limit exceeded - file widget disappears)
https://www.drupal.org/files/issues/no_hook_to_edit-2822460-2.patch (multi-value field widget hook)
https://www.drupal.org/files/issues/2652138-41.patch (2652138 - ImageFormatter does not support SVGs)
https://www.drupal.org/files/issues/1356276-303.patch (1356276 - Allow profiles to provide a base/parent profile and load them in the correct order)

Answer: Composer doesn't patch core automatically, but the cweagans/composer-patches plugin allows dependencies to patch other dependencies if:

You have enable-patching set to true in the "extra" section of your root composer.json file, or
You have at least one patch defined in your root composer.json file

In your case, it looks like Lightning is pulling in those other core patches.
Comment: Thank you. Now I see cweagans/composer-patches in composer.json, and enable patching is true in composer.json.

Does Composer patch core automatically?


Unsupported architecture error on initializing React Native app

Question: It's so weird, yesterday morning everything works well, but after trying to install on a physical iOS device, I even cannot initiate a React Native project, right after the npx react-native init MyNewApp command I get this error:
clang: warning: using sysroot for 'iPhoneOS' but targeting 'MacOSX' [-Wincompatible-sysroot]
ld: warning: ignoring file /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS13.5.sdk/usr/lib/libc++.tbd, missing required architecture x86_64 in file /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS13.5.sdk/usr/lib/libc++.tbd (4 slices)
ld: warning: ignoring file /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS13.5.sdk/usr/lib/libSystem.tbd, missing required architecture x86_64 in file /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS13.5.sdk/usr/lib/libSystem.tbd (4 slices)
clang: warning: using sysroot for 'iPhoneOS' but targeting 'MacOSX' [-Wincompatible-sysroot]
In file included from ../fsevents.cc:6:
In file included from ../../nan/nan.h:55:
In file included from /Users/amerllica/Library/Caches/node-gyp/12.18.0/include/node/uv.h:52:
In file included from /Users/amerllica/Library/Caches/node-gyp/12.18.0/include/node/uv/errno.h:25:
In file included from /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../include/c++/v1/errno.h:31:
In file included from /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS13.5.sdk/usr/include/errno.h:23:
In file included from /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS13.5.sdk/usr/include/sys/errno.h:72:
/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS13.5.sdk/usr/include/sys/cdefs.h:807:2: error: Unsupported architecture
#error Unsupported architecture
 ^
In file included from ../fsevents.cc:6:
In file included from ../../nan/nan.h:55:
In file included from /Users/amerllica/Library/Caches/node-gyp/12.18.0/include/node/uv.h:55:
In file included from /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../include/c++/v1/stdio.h:107:
In file included from /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS13.5.sdk/usr/include/stdio.h:64:
In file included from /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS13.5.sdk/usr/include/_stdio.h:71:
In file included from /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS13.5.sdk/usr/include/_types.h:27:
In file included from /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS13.5.sdk/usr/include/sys/_types.h:33:
/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS13.5.sdk/usr/include/machine/_types.h:34:2: error: architecture not supported
#error architecture not supported
 ^
In file included from ../fsevents.cc:6:
In file included from ../../nan/nan.h:55:
In file included from /Users/amerllica/Library/Caches/node-gyp/12.18.0/include/node/uv.h:55:
In file included from /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../include/c++/v1/stdio.h:107:
In file included from /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS13.5.sdk/usr/include/stdio.h:64:
In file included from /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS13.5.sdk/usr/include/_stdio.h:71:
In file included from /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS13.5.sdk/usr/include/_types.h:27:
/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS13.5.sdk/usr/include/sys/_types.h:55:9: error: unknown type name '__int64_t'; did you mean
      '__int128_t'?
typedef __int64_t       __darwin_blkcnt_t;      /* total blocks */
        ^
note: '__int128_t' declared here
/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS13.5.sdk/usr/include/sys/_types.h:56:9: error: unknown type name '__int32_t'; did you mean
      '__int128_t'?
typedef __int32_t       __darwin_blksize_t;     /* preferred block size */
        ^
note: '__int128_t' declared here
/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS13.5.sdk/usr/include/sys/_types.h:57:9: error: unknown type name '__int32_t'; did you mean
      '__int128_t'?
typedef __int32_t       __darwin_dev_t;         /* dev_t */
        ^
note: '__int128_t' declared here
/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS13.5.sdk/usr/include/sys/_types.h:60:9: error: unknown type name '__uint32_t'; did you mean
      '__uint128_t'?
typedef __uint32_t      __darwin_gid_t;         /* [???] process and group IDs */
        ^
note: '__uint128_t' declared here
/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS13.5.sdk/usr/include/sys/_types.h:61:9: error: unknown type name '__uint32_t'; did you mean
      '__uint128_t'?
typedef __uint32_t      __darwin_id_t;          /* [XSI] pid_t, uid_t, or gid_t*/
        ^
note: '__uint128_t' declared here
/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS13.5.sdk/usr/include/sys/_types.h:62:9: error: unknown type name '__uint64_t'; did you mean
      '__uint128_t'?
typedef __uint64_t      __darwin_ino64_t;       /* [???] Used for 64 bit inodes */
        ^
note: '__uint128_t' declared here
/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS13.5.sdk/usr/include/sys/_types.h:68:9: error: unknown type name '__darwin_natural_t'
typedef __darwin_natural_t __darwin_mach_port_name_t; /* Used by mach */
        ^
/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS13.5.sdk/usr/include/sys/_types.h:70:9: error: unknown type name '__uint16_t'; did you mean
      '__uint128_t'?
typedef __uint16_t      __darwin_mode_t;        /* [???] Some file attributes */
        ^
note: '__uint128_t' declared here
/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS13.5.sdk/usr/include/sys/_types.h:71:9: error: unknown type name '__int64_t'; did you mean
      '__int128_t'?
typedef __int64_t       __darwin_off_t;         /* [???] Used for file sizes */
        ^
note: '__int128_t' declared here
/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS13.5.sdk/usr/include/sys/_types.h:72:9: error: unknown type name '__int32_t'; did you mean
      '__int128_t'?
typedef __int32_t       __darwin_pid_t;         /* [???] process and group IDs */
        ^
note: '__int128_t' declared here
/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS13.5.sdk/usr/include/sys/_types.h:73:9: error: unknown type name '__uint32_t'; did you mean
      '__uint128_t'?
typedef __uint32_t      __darwin_sigset_t;      /* [???] signal set */
        ^
note: '__uint128_t' declared here
/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS13.5.sdk/usr/include/sys/_types.h:74:9: error: unknown type name '__int32_t'; did you mean
      '__int128_t'?
typedef __int32_t       __darwin_suseconds_t;   /* [???] microseconds */
        ^
note: '__int128_t' declared here
/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS13.5.sdk/usr/include/sys/_types.h:75:9: error: unknown type name '__uint32_t'; did you mean
      '__uint128_t'?
typedef __uint32_t      __darwin_uid_t;         /* [???] user IDs */
        ^
note: '__uint128_t' declared here
/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS13.5.sdk/usr/include/sys/_types.h:76:9: error: unknown type name '__uint32_t'; did you mean
      '__uint128_t'?
typedef __uint32_t      __darwin_useconds_t;    /* [???] microseconds */
        ^
note: '__uint128_t' declared here
In file included from ../fsevents.cc:6:
In file included from ../../nan/nan.h:55:
In file included from /Users/amerllica/Library/Caches/node-gyp/12.18.0/include/node/uv.h:55:
In file included from /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../include/c++/v1/stdio.h:107:
In file included from /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS13.5.sdk/usr/include/stdio.h:64:
In file included from /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS13.5.sdk/usr/include/_stdio.h:71:
/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS13.5.sdk/usr/include/_types.h:43:9: error: unknown type name '__uint32_t'; did you mean
      '__uint128_t'?
typedef __uint32_t      __darwin_wctype_t;
        ^
note: '__uint128_t' declared here
In file included from ../fsevents.cc:6:
In file included from ../../nan/nan.h:55:
In file included from /Users/amerllica/Library/Caches/node-gyp/12.18.0/include/node/uv.h:55:
In file included from /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../include/c++/v1/stdio.h:107:
In file included from /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS13.5.sdk/usr/include/stdio.h:64:
In file included from /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS13.5.sdk/usr/include/_stdio.h:75:
In file included from /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS13.5.sdk/usr/include/sys/_types/_va_list.h:31:
/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS13.5.sdk/usr/include/machine/types.h:37:2: error: architecture not supported
#error architecture not supported
 ^
In file included from ../fsevents.cc:6:
In file included from ../../nan/nan.h:55:
In file included from /Users/amerllica/Library/Caches/node-gyp/12.18.0/include/node/uv.h:55:
In file included from /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../include/c++/v1/stdio.h:107:
In file included from /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS13.5.sdk/usr/include/stdio.h:64:
In file included from /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS13.5.sdk/usr/include/_stdio.h:75:
/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS13.5.sdk/usr/include/sys/_types/_va_list.h:32:9: error: unknown type name
      '__darwin_va_list'
typedef __darwin_va_list va_list;
        ^
fatal error: too many errors emitted, stopping now [-ferror-limit=]
20 errors generated.
make: *** [Release/obj.target/fse/fsevents.o] Error 1
gyp ERR! build error
gyp ERR! stack Error: `make` failed with exit code: 2
gyp ERR! stack     at ChildProcess.onExit (/Users/amerllica/.nvm/versions/node/v12.18.0/lib/node_modules/npm/node_modules/node-gyp/lib/build.js:194:23)
gyp ERR! stack     at ChildProcess.emit (events.js:315:20)
gyp ERR! stack     at Process.ChildProcess._handle.onexit (internal/child_process.js:275:12)
gyp ERR! System Darwin 19.5.0
gyp ERR! command "/Users/amerllica/.nvm/versions/node/v12.18.0/bin/node" "/Users/amerllica/.nvm/versions/node/v12.18.0/lib/node_modules/npm/node_modules/node-gyp/bin/node-gyp.js" "rebuild"
gyp ERR! cwd /Users/amerllica/.npm/_npx/15892/lib/node_modules/react-native/node_modules/fsevents
gyp ERR! node -v v12.18.0
gyp ERR! node-gyp -v v5.1.0
gyp ERR! not ok

I tried many ways, even I uninstall XCode and then re-install XCode. set everything from scratch but I get this error for initializing React Native application.
Answer: With the following steps everything back on track:

Logging out
Restarting

It's so weird, but fully shut down the system without keeping open programs states was the solution.


Want to route all internet traffic through VPN

Question: I want to route all internet traffic through a VPN client, so if the VPN somehow lose connection, nobody can find my real IP. So if VPS goes down, so my internet access.
I'm using OpenVPN with this VPN provider : http://vpnsecure.me/ on a XP virtual machine (Vbox)
Side question ;
This client requires password to connect, is there anyway that it can autoconnect on startup ?
Answer: Maybe it's sufficient to disable DHCP for your ethernet connection and not specify a gateway (or configure your DHCP server to not push the standard gateway if that is possible), then you should not have internet access by default. Then you need to configure your OpenVPN connection with the redirect-gateway option to route all traffic through the VPN. That might do the trick (not tested though).
Answer: You can push openvpn redirect-gateway option to the client. There are some drawbacks (including performance degradation) and an explanation of how to do it: openVPN-redirect
Don't disable your DHCP or default gateway or you won't be able to reach the openVPN server so the VPN will not happen. Let openVPN do that after connecting.
Another option that seems better to me if you want to hide your personnal IP would be to install a proxy on your VPS and connect to the internet through it.
Answer: You can use openSSL to remove the password.
openssl rsa -in key.pem -out newkey.pem

If you don't have openSSL installed on your machine, ask vpnsecure.me support to remove the password for you.
You could also make a couple of batch file scripts, one to connect and one to disconnect. This will basically null and void your default gateway on disconnect.
i.e something like the following..
protectme.bat ----> has the following line
netsh interface ip set address name="Local Area Connection" gateway=10.0.0.1 gwmetric=0

where

name= The name of your Network connection.
  gateway= A NULL gateway IP, i.e if your current default gateway is 10.1.1.1, change it to the above so that way when the VPN disconnects it cannot access the internet as it's pointed to the incorrect Default Gateway.

enableme.bat ---> has the following line
netsh interface ip set address name="Local Area Connection" gateway=10.5.1.1 gwmetric=0

where

name= the name of your Network connection
  gateway= The real gateway IP address!

I've tested these commands in windows XP, but they might be slightly different for Vista or 7.
So, if you did the above, the process would work like this.

Connect to VPN.
Run Protectme.bat
VPN Disconnects.
Run enableme.bat

It's not the best solution, however it will do what you wish.


PHP: 2 Domain names, 1 session

Question: I've got a site hosted with Heroku. Heroku assigns my site a domain name of someName.herokuapp.com. I've got a custom domain name www.someName.com which points to someName.herokuapp.com. For consistency purposes in my config file I have a variable:
$ServerPath = "somename.herokuapp.com/";

That way when I need to reference a some file I could just go $ServerPath.$fileName
Here's the problem. When the user logs in from www.somename.com a session is created on the server. However if at any time the user clicks some link which is tied to $ServerPath the user is redirected to somename.herokuapp.com and on THAT domain the session seems to be non-existant and the user is logged out.
Is there any way to keep my $ServerPath var as someName.herokuapp.com and have the session to be open on both www.someName.com and someName.herokuapp.com?
Comment: Sessions are tied to cookies, and cookies don't go across domains.
Answer: Unfortunately, this is the expected behavior for (session) cookies. You request a certain domain and the browser will send it's cookies for that domain (i.e. www.somename.com). Now you click a link: somename.herokuapp.com. The browser does not send ANY cookie from www.somename.com
There are 2 possible solutions:

automaticly redirect somename.herokuapp.com to www.somename.com (or visa versa), so everything is always on the same (sub)domain.
Create a session-transfer via the URL. You could use session.use-trans-sid or anything similar. See http://www.php.net/manual/en/session.configuration.php#ini.session.use-trans-sid. This approach also has downsides.
Answer: You can redirect user using .htaccess
RewriteEngine On
RewriteBase /
RewriteRule ^(.*)$ http://www.someName.com [R=301,L]

He will be redirected from url's other than http://www.someName.com

PHP: 2 Domain names, 1 session


Alternatives to Journal of Statistical Software?

Question: I have developed an R package for a general class of regression models with applications in survival analysis. I have prepared a paper describing the package and the methods, and the applications. One possible outlet for this publication is JSS. However, it is well known that their reviewing process is very slow, taking even years to publish something there, which is rather bad for a computational contribution as things move faster than in theoretical statistics.
https://ntguardian.wordpress.com/2018/08/05/time-to-accept-it-publishing-in-the-journal-of-statistical-software/
What alternative journals are there?
Edit: I just came across the R Journal, and I am currently having a look at it. It looks like a good alternative choice.
Answer: You can try JOSS: Journal of Open Source Software, that is an academic journal (ISSN 2475-9066) with a formal peer review process that is designed to improve the quality of the software submitted.
They create a DOI after publication, follow the Covenant code of conduct and are affiliated of the Open Source Initiative.
Comment: Thanks for the edit. lt would be useful to explain what it is about the journal that make it a good choice.


Free Text Entry in Angular Material mdAutoComplete

Question: I want my angular material autocomplete to be a list of suggestions but not requirements. However I'm not sure how to implement as their is no clear example from the Angular Material docs.
In the example below my model is $ctrl.item.category
Clearly the example below is wrong, as my model is linked to md-selected-item, but this only works if I select an item. I want the user to be able to free enter the text if the item is not in the list. Basically how autocomplete already works in most browsers.
I see plenty of questions on how to disable this, but they are not trying to disable so much as clean up the left over text when an item is not selected. In these cases when an item is not selected then the model value is null, but text is left in the input.
I want the text left int he input to be the model value if the person does not select (or a match is not made).
md-autocomplete(
  md-floating-label="Category Name"
  flex="50"
  md-input-name="category"
  md-selected-item="$ctrl.item.category"
  md-search-text="catSearch"
  md-items="category in $ctrl.categories"
  md-item-text="category"
  md-min-length="0"
  md-select-on-match=""
  md-match-case-insensitive=""
  required=""
  )
  md-item-template
    span(md-highlight-text="catSearch" md-highlight-flags="^i") {{category}}

My options ($ctrl.categories) is an array of strings ['Food','Liqour'] and I wan the user to be able to use one of those or free enter Tables as their choice.
Answer: In this case you should link md-search-text to your model.
If you want to implement fuzzy search you have to write the filter method yourself. Look at this example:
template:
  <md-autocomplete
    md-items="item in $ctrl.itemsFilter()"
    md-item-text="item.label"
    md-search-text="$ctrl.query"
    md-selected-item="$ctrl.selected"
    >
    <md-item-template>
      {{item.label}}
    </md-item-template>

     <md-not-found>
        No item matching "{{$ctrl.query}}" were found.
     </md-not-found>

Min 2 characters

Required value

  </md-autocomplete>

controller:
var items = [ ... ];
ctrl.itemsFilter = function itemsFilter() {
    return ctrl.query ? filterMyItems(ctrl.query) : items;
};
ctrl.myValidator = function (value) {
  return {
    short: value && value.length < 2,
    required : value && value.length < 1,
  };
};

then you just need to add filterMyItems method to filter your items
Comment: Thanks for the response. This approach does not work, because the input is not tied to any of the validation hooks. If you use `required` then and selection must be made and the text in the box is not sufficient.
Comment: It looks like md-autoselect uses **md-selected-item** when validating. You can validate/invalidate fields manually using something like `$scope.formName.inputName.$setValidity(errorKey, isValid)`
Comment: from what it looks like there are a couple of PRs that look to be pushing through that might solve this issue. Based on what I can tell mdAutocomplete was never meant to be a suggestion box as traditionally used in a browser, but more of a select box with a text input filter.
Comment: I've added two validation options you can use. **md-not-found** will tell you when no items matches entered text (still in md-search-text). There is also example how to implement custom error messages.
Comment: I believe that `md-require-match` should be responsible for that (see [issue #2492](https://github.com/angular/material/issues/2492)). I would think that if that option is not set to `true` (and by default it is `false`), the functionality for free text in text box should just work. But it does not. Maybe someone could paste a complete example to jsfiddle.net?
Answer: To improve the answer of @masitko, I have implemented the filter in a way, that it adds the query to the filtered list. So it becomes selectable and a valid option. So it's possible to make the autocomplete a suggestion box.
I'm using ES6 in my projects. But it should be easily adaptable to ES5 code.
myFilter() {
    if (!this.query) return this.items;

    const
        query = this.query.toLowerCase(),
        // filter items where the query is a substing
        filtered = this.items.filter(item => {
            if (!item) return false;
            return item.toLowerCase().includes(query);
        });

    // add search query to filtered list, to make it selectable
    // (only if no exact match).
    if (filtered.length !== 1 || filtered[0].toLowerCase() !== query) {
        filtered.push(this.query);
    }

    return filtered;
}


Query on $3^x \pm 2^{x-a}$ with relation to prime and semiprime

Question: While doing some research(more closer to some playing) with the formula $3^x\pm2^{x-a}$ for $x\in \mathbb{N}$ and $ \{a\mid a \in \mathbb{Z}_{\geq 0},\hspace{1mm} a\le (x-1)\}$ I've become to observe that there are many primes and semiprimes for each $x$ of the formula.
For example when $x=22$, we can find that $3^{22}-2^{x-a}$ being semiprime for $(x-a)\in\{21,19,9\}$, and $3^{22}+2^{x-a}$ being semiprime for $(x-a)\in\{22,20,18,17,15,14,13,8,6,5\}$.
Also we can find that $3^{22}-2^{15}$, $3^{22}-2^{7}$, $3^{22}-2^{3}$,$3^{22}-2^{1}$, $3^{22}+2^{2}$, $3^{22}+2^{19}$ being prime when $x=22$.
So I've come to expect the following two statements.

For $x\in \mathbb{N}$ and $ \{a\mid a \in \mathbb{Z}_{\geq 0},\hspace{1mm} a\le (x-1)\}$, there are at least one semiprime for every $x$ among each set of $\{semiprime\in 3^x-2^{x-a}\}$ and $\{semiprime\in 3^x+2^{x-a}\}$.

For $x\in \mathbb{N}$ and $ \{a\mid a \in \mathbb{Z}_{\geq 0},\hspace{1mm} a\le (x-1)\}$, there are at least one prime for every $x$ among the set of $\{\mathbb{P} \in 3^x\pm2^{x-a}\}$.

I've seen a lot of people who have astonishing mathematical abilities in this site so I've become to ask for some opinions with the statements above, of which I wouldn't be able to handle them since they are out of my reach otherwise.
Comment: Note that numbers of the form $3^m\pm 2^n$ with positive integers $m,n$ are coprime to $6$. Small numbers with this property have a good chance to be prime. Conjectures like the one you formulated are usually out of reach for a proof , but maybe heuristic arguments can be made. First step is checking the conjectures upto some limit. Did you do that ?
Comment: For the primes, the first counterexample is $m=28$. The smallest nonnegative integer $n$ such that $3^{28}\cdot 2^n+1$ is prime is $n=29$ whereas for $3^{28}\cdot 2^n-1$ is it $n=347$. But even the existence of a prime of the form $3^m\cdot 2^n\pm 1$ is not clear. If $m=634$ , for example, we must go until $n=1299$ to find a prime. I think chances for the semiprime-conjectures to hold (or at least to hold for sufficient large $m$) are better.
Comment: @Peter: Yup, that is why I did make the statement for the second one as being $\{\mathbb{P} \in 3^x\pm2^{x-a}\}$, not as the semiprime version which I've divided the set into $+$ one and $-$ one.
Comment: @Peter: Thanks. I've seen your list of questions and answers and they were impressive. Can you tell me how long have you been studied numbers?? Also could you share your information on what coding program fits you best for doing research on numbers? (Python, Fortran, Sagemath, etc...)  You don't have to reply these but I just wondered. Anyway, many thanks!
Comment: $(1)$ I use PARI/GP for number theory calculations (factoring , primality checking and similar things) $(2)$ I always was interested in numbers , I am in particular excited of the huge numbers (that do not occur in "daily life math") $(3)$ Shall I continue with the semiprimes ? For larger $m$, I think the search can be accelerated if we do not want to find the smallest example. Are you content with that ?
Comment: @Peter Why not? It would be my pleasure. I am happy to be refuted by some counterexample so I can forget it and move on to some other topic!
Answer: The semiprime-version is promising. I arrived at the following conjecture

Suppose , $\ n\ge 4\ $ is an integer. Then

there is an integer $\ m\ $ with $\ 0<m<n\ $ such that $\ 3^n\cdot 2^m-1\ $ is a semiprime.
there is an integer $\ m\ $ with $\ 0<m<n\ $ such that $\ 3^n\cdot 2^m+1\ $ is a semiprime.
If we allow also $\ m=0\ $ , the only counterexample for positive integer $\ n\ $ is the minus-case for $\ n=1\ $

The conjecture is true upto $\ n=100\ $
The smallest solutions are listed below.
gp > for(n=4,100,m=1;while(bigomega(3^n*2^m-1)<>2,m=m+1);print(n,"  ",m))

4  1
5  1
6  1
7  3
8  3
9  1
10  1
11  5
12  5
13  1
14  1
15  4
16  3
17  2
18  1
19  1
20  6
21  1
22  3
23  2
24  1
25  3
26  7
27  2
28  1
29  2
30  1
31  5
32  1
33  2
34  15
35  3
36  1
37  7
38  1
39  1
40  9
41  5
42  19
43  1
44  9
45  1
46  11
47  3
48  5
49  2
50  13
51  4
52  25
53  2
54  1
55  1
56  7
57  2
58  23
59  2
60  7
61  2
62  27
63  1
64  3
65  3
66  13
67  2
68  7
69  2
70  29
71  1
72  5
73  3
74  3
75  14
76  11
77  2
78  1
79  4
80  1
81  20
82  23
83  9
84  1
85  4
86  7
87  1
88  5
89  1
90  1
91  1
92  9
93  7
94  11
95  8
96  55
97  2
98  3
99  14
100  29
gp >
gp > for(n=4,100,m=1;while(bigomega(3^n*2^m+1)<>2,m=m+1);print(n,"  ",m))

4  3
5  2
6  3
7  2
8  1
9  2
10  1
11  3
12  1
13  8
14  1
15  1
16  3
17  2
18  1
19  2
20  3
21  4
22  1
23  2
24  5
25  2
26  1
27  2
28  3
29  4
30  7
31  10
32  1
33  7
34  1
35  3
36  23
37  6
38  5
39  7
40  11
41  1
42  2
43  5
44  7
45  1
46  1
47  6
48  1
49  24
50  1
51  4
52  8
53  3
54  10
55  18
56  1
57  5
58  10
59  1
60  4
61  5
62  1
63  2
64  1
65  4
66  13
67  3
68  1
69  1
70  1
71  1
72  4
73  5
74  7
75  2
76  1
77  13
78  2
79  5
80  8
81  2
82  1
83  7
84  1
85  8
86  6
87  2
88  5
89  1
90  17
91  31
92  1
93  20
94  7
95  3
96  15
97  12
98  25
99  1
100  3
gp >
To check larger $\ n\ $ , I have to program a more efficient version to find a solution. I will update the post , if I have arrived at a new milestone.
Comment: Great done!!!!! I hope more people in this site could see your outcome. In my opinion, the constantly occurring semiprimes imply some hidden algebraic structure that may reveal itself someday!!!
Comment: The conjecture is still true upto $\ n=200\ $. Nevertheless, I am not sure whether it is true. With increasing $\ n\ $ , the chance for a semiprime will decrease and whether this is compensated by the number of chances is not clear.
Comment: I also see what you've said is well worth considering. Thank you for your work!


Regex returning last character of string?

Question: 'Ello, so I'm using Rainmeter and I just want to get the last character of a string using Regex. Rainmeter uses Perl regex. The string is just two characters long, it's just minutes (so just two numbers) and I need the second digit.
This is what I have for getting just the first digit.
[MeasureMinutePrefix]
Measure=Time
Format=%M
RegExpSubstitute=1
Substitute="^(.{1,1}).+$":"\1"

Thanks!
Answer: I don't know Rainmeter, but extrapolating from your example, this should do it:
Substitute="^.*(.)$":"\1"

BTW, there's no need for {1,1} in the regexp. That's the normal meaning of any non-quantified pattern, it matches exactly once.
Comment: Note that `^(.).$` for the first digit and `^.(.)$` for the second would also work.  The quantifiers let you generalize to more than two-digit numbers, though; no matter how many characters there are, `^(.).*$` gets the first and `^.*(.)$` gets the last.
Answer: Substitute="^.{1}(.{1,1})$":"\1"

or
Substitute="^\d(\d)$":"\1"

Comment: So? Is that a wrong solution? It works. I tried to keep same format that currently is there and offered another solution.
Comment: Fair enough, Andrey.  I didn't say it was wrong, nor was my comment related to your downvote.  I just think some consistency would be better.  A more exact parallel to the original code would be `^.+(.{1,1})$`, for example. If you're going to restrict it to exactly two characters, as stated in the problem but not in the code, then it would have made more sense to me to reuse the `{1,1}`, or get rid of both instances of it; introducing `{1}` to the mix just seems confusing for no benefit.


Alternative proof of the generalized associative law for groups

Question: The generalized associative law for groups claims that the value of  $a_1\star a_2\star ... \star a_n$ is independent of how it is bracketed, where the symbols denote the usual notations of group theory.
While attempting a proof on my own, I discovered a method that seems right to me but does not appear anywhere as a standard proof. Please comment on the validity of this proof, since it is likely I messed up somewhere.
Throughout the proof we consider elements belonging to a group $G$.
We attempt a proof by induction on the number of elements in the expression. The base cases of 1,2,3 are seen to be true trivially or by the associative property. Now assume that the value of any n-element expression is independent of how the expression is bracketed. (Induction Hypothesis)
Now consider any $(n+1)$-element expression given by $a_1\star a_2\star ... \star a_n\star a_{n+1}$. All bracketings of this expression may be divided into $n$ types as follows (these types are not necessarily disjoint):

bracketings containing $(a_1\star a_2)$

bracketings containing $(a_2\star a_3)$
.
.
.

n. bracketings containing $(a_n\star a_{n+1})$
Let $(a_i\star a_{i+1})$ = $a_{(i,i+1)}$, which is also an element of $G$ (where $i$ ranges from $1$ to $n$).
Now for any type $i$ considered above, the corresponding $(n+1)$ - element expression can be reduced to an $n$ - element expression by substituting $a_{(i,i+1)}$ instead of $(a_i\star a_{i+1})$. Then by IH, all bracketings of this type evaluate to a bracketing- independent value which we shall call $A_i$.
It remains to show that $A_1 = A_2 = A_3 = .... = A_n$.
But note that for any $i$,
$A_i$ = $(..((a_1\star a_2)\star a_3)..\star a_{i-1}) \star ((a_{i}\star a_{i+1})\star a_{i+2})\star(..((a_{i+3}\star a_{i+4})\star a_{i+5})..\star a_{n+1})$ = $(..((a_1\star a_2)\star a_3)..\star a_{i-1}) \star (a_{i}\star( a_{i+1}\star a_{i+2}))\star(..((a_{i+3}\star a_{i+4})\star a_{i+5})..\star a_{n+1})$ = $A_{i+1}$.
So for all $i$ from $1$ to $n$, $A_i$ = $A_{i+1}$. This implies
$A_1 = A_2 = A_3 = .... = A_n$, as required. This proves the result for the case of $n+1$. The result is then true by induction for all natural $n$.
Comment: Welcome to MSE. For some basic information about writing mathematics at this site see, *e.g.*, [basic help on mathjax notation](/help/notation), [mathjax tutorial and quick reference](//math.meta.stackexchange.com/q/5020), [main meta site math tutorial](//meta.stackexchange.com/a/70559) and [equation editing how-to](//math.meta.stackexchange.com/q/1773).
Comment: Thank you. I modified my post
Comment: I don't understand this proof. First, you say that two adjacent elements must be bracketed together. Fine. Then you say that any bracketing is "equivalent" to such a bracketing. Why equivalent? (What does that even mean?) It IS such a bracketing, as you just claimed! Anyway, not a big problem, just redundant.

You then consider the case when $a_1$ and $a_2$ are bracketed together. But you never consider cases when they are not. (Which can occur.) Even in this case, you assume that $((a_1a_2)a_3)$ appears, which is not necessarily true, what about for example $(a_1a_2)(a_3a_4)$?
Comment: Your 'proof' boils down to the statement that you can move from any bracketing of $n$ terms to any other bracketing of $n$ terms by successive applications of associativity. This is true (it is equivalent to generalized associativity) but you do not show it. For example, you cannot deal with $((ab)(cd))e$ using your method, because $(ab)$ is not bracketed with a single other term, but another bracket.
Comment: You will be able to do every special case because the result is true. But your above 'proof' does not prove each of these special cases, or at least I am not convinced that it does. And: "I am not simply using "successive applications of associativity" but also the induction hypothesis." Literally you are, because your IH uses successive applications of associativity. IH = successive applications. That's a general statement.
Comment: @RuwimalPathiraja I say 'I think your general argument above does not prove all cases. One possible case is x'. You say 'x is also true, because of .' This means that x is true. It does not mean that your original argument proves x.
Comment: What I meant was that any bracketing in which no two adjacent elements are explicitly bracketed together is equivalent (equal in value and the placing of other brackets) to a bracketing in which some two adjacent elements ARE bracketed together (because any simplification of the expression must start with some two adjacent terms being "multiplied"). If $a_1$ and $a_2$ are not together, there must be some two adjacent elements that ARE bracketed together. In the last part I show that all bracketings where $a_1$ and $a_2$ are together are equal to ones in which $a_i$ and $a_{i+1}$ are together.
Comment: $((a_1a_2)a_3)$ is part of an expression in which $a_1$ and $a_2$ are bracketed together, which is an n-element expression and so by my induction hypothesis is equal to any expression in which $a_1$ and $a_2$ are bracketed together. I believe I have shown that bracketings of $a_1$ and $a_2$ are equal to bracketings of $a_2$ and $a_3$ which are then equal to bracketings of $a_3$ and $a_4$ and so on for all adjacent elements (refer last part of proof). I'm sorry if that wasn't clear
Comment: Most of my comments still apply. For example, you have proved that, in any bracketing, two adjacent elements are bracketed together. Yet, both in your main post and your latest comment, you consider the case where "no two adjacent elements are bracketed together", a case you just explained does not even occur. The whole proof is similarly confused IMO. In fact, I wouldn't really call it a proof.
Comment: The fact that any bracketing of the expression must include a bracket containing two adjacent elements is trivially seen to be true and should have been omitted anyway. My bad. I still don't see a mistake in the way I use the induction hypothesis, how the "product" of two adjacent elements can be considered a single element in order to reduce the n+1 case to an n-element product and how the associative property can be used to equate expressions in which different adjacent elements are bracketed.
Comment: How about having another go at it, editing your post with my comments in mind?
Comment: Thanks for the suggestion. The original post has been edited.
Comment: Knock Knock Knock
Comment: In the last para there are too many "proceeding similarly" and "and so on". You need a proper induction here as well to complete your proof.
Comment: Thank you for the reply. I edited my post to include more details in the last para. I understand that the proof has not been presented formally, but I don't see a flaw in the reasoning of the induction. Could you specifically point out any mistake you spotted?
Comment: $((ab)(cd))e$ can be dealt with using the induction hypothesis for $n=4$. Suppose $ab = t$, which reduces the expression to $(t(cd))e$. Since this is a bracketing of $tcde$, by the induction step, it is equal to any other bracketing of $tcde$, specifically, it is equal to $((tc)d)e$. But $((tc)d)e = (((ab)c)d)e = ((a(bc))d)e$ (the second equality comes from the ordinary associative law), and so $((ab)(cd))e = ((a(bc))d)e$. This allows us to switch to a different bracketing. I am not simply using "successive applications of associativity" but also the induction hypothesis.
Comment: "You will be able to do every special case because the result is true". This is a little confusing. Are you saying that I've assumed the truth of the result before proving it? I only assume its truth for n elements and prove for (n+1), which is what induction does usually. And "You will be able to do every special case" vs "does not prove each of these special cases" suggests that "doing" and "proving" are different somehow?
Comment: By refusing to write out all the steps you are concealing a possible gap in your proof. Just saying "we may use another induction here" isn't enough. These inductions may be different depending on the "shape" of the product. Write down explicitly what your inductive hypothesis is, and write out the proof.
Comment: I rewrote the proof in a different way. Hope this makes it clearer.
Comment: I think that the question would be greatly improved if you did three things: (i) write down clearly what it means to "bracket" a string; (ii) write down explicitly what proposition $P(n)$ you are proving by induction; (iii) write your proof without any use of "$\dots$".
Comment: @ancientmathematician The following is an excerpt from Dummit and Foote's Abstract Algebra (page 18):
"for any $a_1 , a_2, .. , a_n$ in G the value of $a_1\star a_2\star ... \star a_n$ is independent of how
the expression is bracketed (this is called the generalized associative law)."
And on page 19 the induction hypothesis is stated as:
"Next assume for any $k<n$ that any bracketing of a product of  $k$ elements, $b_1\star b_2\star ... \star b_k$ can be reduced (without altering the value of the product) to
an expression of the form
$b_1\star(b_2\star(b_3\star(...\star b_k))...)$".
Comment: @ancientmathematician If a standard textbook finds it suitable to use the same terms and language ("bracketing", induction hypothesis, use of "…") , I don't see why you should find them so mysterious.
Comment: Thanks. I think the IH should make clear it is being assumed for every choice of the $b_i$, not just for $b_1,b_2, \dots, b_k$. And a bit disappointing that the issue of what we mean by bracketting  is not tackled - until you clarify that it is  not even clear that one of your products of adjacent elements even exists. BTW congratz on exploring this alternative proof!
Answer: Your proof looks OK to me, apart from a couple of typos in the big formula showing $A_i=A_{i+1}$. That formula has an unintended "=" at the end of the first line, and it has "$=A_{i+1}$" at the end of the next-to-last line whereas it should be at the end of the last line.
I think what confused some of the commenters is that you're using $A_i$ initially to denote any of numerous bracketings, and you prove later that they're all equivalent. Let me write out a version of your proof intended to un-confuse that point.
Let $C_i$ be the class of those bracketings of $n+1$ factors in which $a_i$ and $a_{i+1}$ are bracketed together. (In the tree picture, this means that those two leaves have the same immediate predecessor.) These bracketings can be viewed as bracketings of $n$ factors, by treating the combination $(a_i*a_{i+1})$ as a single factor. (Chop those two leaves off the tree but retain their predecessor.)  By induction hypothesis, all of the bracketings in $C_i$ are equivalent, meaning their equality is provable from the associative law.
So to complete the proof of the generalized associative law, it suffices to show that some bracketing in $C_i$ is equivalent to some bracketing in $C_{i+1}$. For this purpose, use a bracketing in $C_i$ that contains the segment $((a_i*a_{i+1})*a_{i+2})$ and the bracketing in $C_{i+1}$ that is the same except for changing that one segment to $(a_i*(a_{i+1}*a_{i+2}))$. These are equivalent because the only change was one application of the associative law.
I claim that this is a proof, that the commenters would accept it as a proof, and that it's really the same as your proof.
Comment: @RuwimalPathiraja Indeed, a systematic development of this material would need a definition of "bracketing" or at least an axiomatic specification of the basic facts about bracketings that can be assumed. But in most contexts, one can assume that these things are understood, just as one assumes the basic facts about real numbers, without giving the definition or axioms. Of course, if it turned out that people disagreed about what bracketings are, then one would have to specify such information explicitly.
Comment: Thanks a lot for the detailed reply! This is indeed what I was trying to say. The original post was edited many times and rewritten once with the help of the commenters' suggestions. I think one of the objections of @ancientmathematician was that "bracketing" needs to be explicitly defined.
Answer: What we know is that for any 3 elements $a,b,c \in G$ we have $(a * b) * c = a  * (b * c)$.
What we want to show is that given any two binary trees with the same elements of $G$ in order at the leaves, e.g:
<code>    /\                /\
   / \               / /\
  /\  \             / / /\
 /\ \ /\           / / / /\
a b c d e     and a b c d e
</code>
that they map to equal expressions when you replace branching with $*$. These trees map to $((a*b)*c)*(d*e)$ and $(a*(b*(c*(d*e)))$
We are all familiar with induction on the natural numbers, but to prove the generalized associativity you will need to use induction on trees.
Comment: The last sentence is false, the result is provable by a suitable induction on natural numbers. Which isn't to say that structural induction isn't a good idea.
Comment: @ancientmathematician would you be able to demonstrate this?
Comment: Yes, any structural induction can be re-written (less clearly) using inductions on the natural numbers.


NSURLConnection and ProgressBar Crash when try to convert to float

Question: i am trying to use progressbar while downloading using NSUrlConnection
am missing somthing but dont know what
see my code
in my .h i have
NSMutableData *receivedData;

    NSNumber  *FileSize;

which i use to calculate a precent for progressbar
in my .m
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response

{
    [receivedData setLength:0];

    FileSize = [NSNumber numberWithLongLong:[response expectedContentLength]];
}

and
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data

{

    [receivedData appendData:data];

    NSNumber *resourceLength = [NSNumber numberWithUnsignedInteger:[receivedData length]];
    NSLog(@"resourceData length: %d ", [resourceLength intValue]);

    NSNumber *progress = [NSNumber numberWithFloat:([resourceLength floatValue] / [FileSize floatValue])];
    updateProgressBar.progress = [progress floatValue];
}

When its reach the line with FileSize float its crash
2010-10-05 22:32:19.924 Quran[2067:207] resourceData length: 1090
Program received signal:  "EXC_BAD_ACCESS".
Answer: I believe that FileSize = [NSNumber numberWithLongLong:[response expectedContentLength]]; is giving you an autoreleased NSNumber that you need to retain somewhere. Maybe you are doing that somewhere else in the code, but that is a probable place you could be getting an EXC_BAD_ACCESS.
Comment: Yes i think Thats right , i try NSLog(@"TotalFileSize : %@",FileSize); and i got the EXC_BAD_ACCESS how i can retain it
Comment: You could try `[FileSize retain]` after you create it.
Comment: Thanks its work now your answer is really help and save me time


Is the statement also true in infinite dimensional vector spaces?

Question: I am trying to prove that:
"A basis is equivalent to a maximal linearly independent set"
I am wondering if this statement is true for infinite dimensional vector spaces.
Can someone help me answer this question please?
Comment: What's the definition of basis that you are working with?
Comment: The confusion might be that in the infinite-dimensional case, you need Zorn's Lemma or similar to conclude that such a maximal set (and thus a basis) must exist.
Comment: @anomaly how is that? are you saying that the solution below is incomplete? Can you add your solution below please?
Answer: If you define a basis as a linearly independent set which spans the entire space, then the answer is yes.
Suppose $B$ is a basis for a vector space $V$. Let $B \subseteq B' \subseteq V$ be arbitrary. Then for any $b \in B'\setminus B$ by definition of a basis we have $b \in \operatorname{span} B$ so $B'$ cannot be linearly independent. Therefore $B$ is a maximal linearly independent set in $V$.
Conversely, let $B\subseteq V$ be a maximal linearly independent set in $V$. Let $x \in V$ be arbitrary. If $x \notin \operatorname{span} B$, then $B\cup \{x\}$ would be a linearly independent set containing $B$, contradicting the maximality of $B$. Therefore $x \in \operatorname{span} B$. Since $x \in V$ was arbitrary, we conclude that $\operatorname{span} B = V$ so $B$ is a basis for $V$.
Comment: So this statement is also true if $V$ is infinite dimensional?
Comment: I did not understand what is exactly arbitrary in the following statement "Let $B \subseteq B' \subseteq V$ be arbitrary" ..... could you clarify this please?
Comment: @Secretly Yes, it's true for all vector spaces $V$. In that sentence the set $B'$ is meant to represent an arbitrary subset of $V$ which contains $B$. The conclusion is that every such set $B'$ is necessarily linearly dependent. Therefore, a linearly independent set which strictly contains $B$ cannot exist so $B$ is maximal.
Comment: have you seen the comment of anomaly above? does this comment affects your solution?
Comment: @Secretly Yes, the proof of existence of a basis for an infinite-dimensional vector space is nontrivial and depends on the axiom of choice. It doesn't affect my solution though, I'm only showing that a set $B$ is a basis if and only if it is a maximal linearly independent set, I'm not claiming such a set $B$ exists.
Comment: Oh I see, so your proof is correct anyway whether we are speaking about finite or infinite dimensional vector space.
Comment: @Secretly Yes, the cardinality is not used in the proof.


Trocar classe de input quando este estiver preenchido

Question: Estou fazendo um formulário utilizando primefaces, e queria que meu input trocasse de classe quando estivesse preenchido, só voltando a classe anterior caso o usuário apagasse o conteúdo. Isso é para fazer com que o outputLabel saia de dentro do input e fique vísivel conforme a figura que anexei.

A primeira figura é como é inicialmente;
  A segunda figura é como é pra ficar;
  A terceira é como está ficando.

Alguém sabe um jeito de fazer isso? o meu aqui não está dando certo...
Comment: Se entendi bem a sua dúvida, a forma de fazer isso usando Primefaces é com Watermark. Veja aqui: https://www.primefaces.org/showcase/ui/misc/watermark.xhtml
Comment: Luan, poste o código também, fica mais fácil de analisar, inclusive o código que vc está tentando.
Answer: Você pode fazer uma verificação no blur do input.
Veja qual a classe existente na label quando ela fica em cima do input (com o efeito que vc quer) e faça o seguinte:
SE ESTIVER USANDO JQUERY
$('#selector_input').on('blur', function(){
    var _self = $(this);

   if(_self.val() != null){
      $('#selector_label').addClass('class-do-efeito');
   }else{
      $('#selector_label').removeClass('class-do-efeito');
   }
})

SE ESTIVER USANDO JAVASCRIPT PURO
var input = document.getElementById('id_input');
var label = document.getElementById('id_label');

input.onblur = verifyInput(input);

function verifyInput(input){

   if(input.value != null){
      label.classList.add('class-do-efeito');
   }else{
      label.classList.remove('class-do-efeito');
   }
}

Comment: Não estou usando jquery :(
Comment: @LuanSilva atualizei a resposta com a solução usando javascript puro. Boa sorte ;)
Comment: ainda não funcionou!! acho que pode ser o lugar onde estou colocando... é preciso chamar essa função?? E eu ponho onde? num script dentro da mesma página ou em outro externo (se fazer diferença)
Comment: @LuanSilva, atualizei o código novamente. Veja se agora funciona :)
Você pode colocar num arquivo externo (se já houver um) ou no mesmo arquivo, como é um código relativamente pequeno, recomendo colocar no mesmo arquivo (tag script antes do fechamento do body).
Comment: ta quase lá... ele já está vindo com a classe mesmo sem ter nada escrito
Comment: Poderia postar o seu código no JsFiddle? Acho que seria melhor para dar suporte
Comment: Já consegui resolver... obrigadão!!
Answer: Se for apenas trocar a classe do input (conforme pergunta), use oninput (o oninput é mais eficiente porque detecta quaisquer alterações no campo):

Exemplo:

var el = document.querySelector("#id_do_input");
el.oninput = function(){
   this.value ? this.classList.remove('nome_da_class') : this.classList.add('nome_da_class');
}
.nome_da_class{
  background: yellow;
}
<input placeholder="Nome" type="text" class="nome_da_class" id="id_do_input" />
Comment: não tem o "oninput" pro inputText do primefaces
Comment: @LuanSilva Atualizei a resposta. Abs!
Comment: Eu consegui resolver mudando o seu onInput pra onChange... Está funcionando. Obrigado!


Saber a direção entre pontos através de coordenada latitude e longitude com php

Question: Galera seguinte tenho 3 cidades que vamos chama de ponto  (A) (B) (C)  todas com latitude e longitude a topologia de fica mais ou menos assim:
A = -3.3105, -60.1694

B = -3.3242, -60.6281

C = -3.5970, -61.3930

Direções (A) <--Barco Viajando--> (B) <--Barco Viajando--> (C)

Obs: Entre o ponto A ao C tenho tenho um barco viajando, e tenho latitude e longitude "coordenada" a cada 2 minutos desse barco:
Agora vem questão que eu quero saber, se tem como saber se ele esta indo do ponto para qual ponto tipo assim:
(A) --> (B)

(C) --> (B)

(B) --> (A)

Espero tenham me entendido peço que se alguem pode me ajudar agradeço muito mesmo !
Comment: Qual é a fórmula para esse cálculo ? Porque para "separar os valores" e ver a diferença, é só usar um `explode`, assim separa LA de LO.
Answer: [Update 2]
Script final (ainda pode ser melhorado):
// Detalhes
$n_pontoA = "Iranduba"; // Nome do ponto A
$n_pontoB = "Manaus";   // Nome do ponto B

// Coordenadas
$c1_barco = '-3.3105, -60.1694'; // Posição anterior do barco
$c2_barco = '-3.3137, -60.3477'; // Posição atual do barco
$c_pontoA = '-3.3242, -60.6281'; // Ponto A
$c_pontoB = '-3.5970, -61.3930'; // Ponto B

function quebra($coordenadas) {

    // Separa os valores
    $v = explode(",",$coordenadas);

    return $v;
}

// https://www.geodatasource.com/developers/php
function distance($lat1, $lon1, $lat2, $lon2, $unit) {

    $theta = $lon1 - $lon2;
    $dist = sin(deg2rad($lat1)) * sin(deg2rad($lat2)) +  cos(deg2rad($lat1)) * cos(deg2rad($lat2)) * cos(deg2rad($theta));
    $dist = acos($dist);
    $dist = rad2deg($dist);
    $miles = $dist * 60 * 1.1515;
    $unit = strtoupper($unit);

    if ($unit == "K") {
        return ($miles * 1.609344);
    } else if ($unit == "N") {
        return ($miles * 0.8684);
    } else {
        return $miles;
    }
}

function calcula($c1Barco, $c2Barco, $cPontoA, $cPontoB) {

    // Quebra Latitude de Longitude
    $barcoC1 = quebra($c1Barco);
    $barcoC2 = quebra($c2Barco);
    $pontoA = quebra($cPontoA);
    $pontoB = quebra($cPontoB);

    // Calcula a distância entre os pontos
    $db1a = round(distance($barcoC1[0],$barcoC1[1],$pontoA[0],$pontoA[1],"K"),2);
    $db1b = round(distance($barcoC1[0],$barcoC1[1],$pontoB[0],$pontoB[1],"K"),2);
    $db2a = round(distance($barcoC2[0],$barcoC2[1],$pontoA[0],$pontoA[1],"K"),2);
    $db2b = round(distance($barcoC2[0],$barcoC2[1],$pontoB[0],$pontoB[1],"K"),2);

    // Tira a diferença da posição barco x pontos
    $dPA = $db1a - $db2a;
    $dPB = $db1b - $db2b;

    // Verifica a maior distância percorrida
    if ($dPA > $dPB)
        return "A";
    else
        return "B";
}

// Executa a função passando as variáveis
$resultado = calcula($c1_barco, $c2_barco, $c_pontoA, $c_pontoB);

if ($resultado == "A")
    echo "Destino: " . $n_pontoA;
else if ($resultado == "B")
    echo "Destino: " . $n_pontoB;
else
    echo "Erro!";

[Resposta 1]
Primeiro você precisa ter bem definida a fórmula da distância, pois elas podem conter valores positivos e/ou negativos, mas poderá resolver de forma simples.
Se irá calcular "velocidade média", é um pouco mais complexo do que parece, pois como terá 3 pontos, ao invés de 1, teria que fazer o cálculo separadamente.
Feito isso, você quebra os 2 valores, faz os cálculos conforme sua definição, e depois simplesmente faz a diferença entre eles.
Exemplo das funções:
// Coordenadas
$A = '-3.3105, -60.1694';
$B = '-3.3242, -60.6281';
$C = '-3.5970, -61.3930';

function distancia($ponto1, $ponto2) {

    // Separa os valores
    $p1 = explode(",",$ponto1);
    $p2 = explode(",",$ponto2);

    // Calcula a diferença
    $dLA = $p1[0] - $p2[0];
    $dLO = $p1[1] - $p2[1];

    echo '
 LA: ' . $dLA . ' | LO: ' . $dLO;
}

distancia($A,$B);
distancia($B,$A);
distancia($A,$C);

Resultado:
LA: 0.0137 | LO: 0.4587
LA: -0.0137 | LO: -0.4587
LA: 0.2865 | LO: 1.2236

Função separando cada coordenada para trabalhar com elas fora de uma função:
function distancia2($ponto1, $ponto2) {

    // Separa os valores
    $p1 = explode(",",$ponto1);
    $p2 = explode(",",$ponto2);

    // Calcula a diferença
    $d["LA"] = $p1[0] - $p2[0];
    $d["LO"] = $p1[1] - $p2[1];

    return $d;
}

$dA_B = distancia2($A,$B);
$dB_C = distancia2($B,$C);
$dA_C = distancia2($A,$C);

echo '
' . $dA_B["LA"];
echo '
' . $dB_C["LA"];
echo '
' . $dA_C["LA"];
echo '
' . $dA_B["LO"];
echo '
' . $dB_C["LO"];
echo '
' . $dA_C["LO"];

Comment: Tem um problema sério aí: vocês estão calculando como se o planeta fosse plano. Sugiro estudarem geodésicas
Comment: Mas você tendo as coordenadas e fazendo a diferença entre elas, você terá a posição do barco. Com essa 2a função, é só jogar na fórmula dele.
Comment: Diretor da uma olhada ai nessa url http://grupoleopardo.com/app/kibarco/expresso-crystal-i/
Comment: @GrupoLeopardo Muito bacana ! A parte de "velocidade" já é algo mais delicado. Vou postar na resposta
Comment: Aqui na frente que eu queria colocar na frente para onde esta indo http://grupoleopardo.com/app/kibarco
Comment: a parte da velocidade ja esta ok
Comment: tem como agente falar pelo chat pode ser?
Comment: Essa aplicação já é sua então ? Achei que estava começando, e queria reproduzi-la. Mas então, você precisa ter sua fórmula para poder aplicar no script. Vamos supor que você hoje iria calcular na mão, no papel e caneta. Como você faria para calcular isso ? Tendo isso em mãos, já facilitaria demais o que você precisa. Em vista você terá 6 variáveis de posição (3 LA e 3 LO), e 6 de distância (3 distâncias calculadas, 3 distâncias anteriores).
Comment: Sim, só não sei como criar chat ! rs
Comment: Tenho pouca reputação ainda começando agora mais aqui abaixo apareceu pra mim mais não posso iniciar devido minha reputação ser baixa ainda eu acho rsrsss tenta ai
Comment: @Bacco eu ia falar sobre isso, pois uma vez estava vendo sobre APP com GPS, e sorte que o Android tem classe pronta para isso, já considerando a curvatura da terra. Isso vale para velocidade correto !?
Comment: @Bacco seguinte: tenho no banco todos as coordenada do barco data e hora a cada 2 min isso no caso me ajuda a chegar onde quero ?
Comment: https://chat.stackexchange.com/rooms/77036/roomw1d1d1wr4yw46u2


Can these data be aggregated into a proportion for a binomial glm?

Question: We asked 60 people to list as many restaurant franchises in Atlanta as they could.  The overall list included over 70 restaurants, but we eliminated those that were mentioned by fewer than 10% of the people, leaving us with 45.  For these 45, we calculated the proportion of informants who listed the franchise, and we're interested in modeling this proportion as a function of the franchises's (log-transformed) advertising budget and years since becoming a franchise.
So I wrote this code:
model <- glm ( cbind (listed, 55-listed) ~ log.budget + years, family = binomial, data = list.45)

As predicted, both variables exhibit strong, significant effects.
But even though I know that proportional data should never be modeled with OLS regression, I subsequently wrote this code:
model.lm <- lm ( proportion.55 ~ log.budget + years, data = list.45)

In this case, "budget" is still a significant predictor, but "years" is relatively weak and not significant.
It makes me worried that the confidence in the estimates is artificially inflated by the aggregation.  Doesn't the binomial glm essentially vectorize the data such that the model is based on 45 * 55 = 2,475 rows?  Is that appropriate given that there are really only 45 restaurants and 55 informants?  Would this call for mixed-effects modeling?
Comment: hint: see what happens with `family=quasibinomial`
Comment: Exactly. There are a variety of differences between `lm` and `glm(...,family=binomial)`, but one of the important ones is that a binomial GLM makes strong assumptions about the variance. If the data are *not* overdispersed, then aggregating/disaggregating makes no difference.
Comment: Interesting.  The estimated coefficients are the same, but standard errors are more conservative (and years is not significant in the quasibinomial model).  I'm looking up the help files for quasibinomial, but can you explain what's going on?  My impression has been that quasibinomial is used primarily for overdispersion . . .
Comment: The R output shows that the dispersion paramater is taken to be 8.7.  I'm trying to figure out what this says about overdispersion.  Meanwhile, Ben, I see that you've got quite a lot of background with mixed models.  Am I safe using a binomial glm without mixed effects for either informant or franchise (in which case I would presumably have to vectorize all of the data while adding a column for "Informant ID")?
Answer: For proportional data, one can take the logarithm of the dependent variable before fitting since logarithms transform multiplication into addition. In a similar vein, if one also takes the logarithms of the independent variables, if they also are proportional, then the resulting fit for multiple linear regression implies a power function product model, not an additive one, i.e., $Y=c X_1^{k1}X_2^{k2}...X_n^{kn}$. That is, one fits $\ln(Y)=\ln(c)+k1 \ln(X_1)+k2 \ln(X_2)...+kn \ln(X_n)$. For proportional variables, this usually gives higher significance than linear fitting, and is more powerful, and has higher $R^2$.
Now if the unaltered regression line (ideally a bivariate regression, e.g., a Deming regression) does not plausibly pass through {0,0}, then it gets a bit more complicated, and one minimizes an offset proportional loss function rather than use ordinary least squares.


FileChooser to select a directory, not a file

Question: My code processes all the files in a folder on a Windows box. I want to offer the user (who happens to also be me) the option to select the folder to be processed, using the standard File Chooser dialog.
I am trying to use the GetOpenFileName function to make this happen. (I am actually calling it from Python via pywin32, but that shouldn't be relevant.)
I can get it to select a particular file, but I can't see any options to let the user select a folder instead.
Is there a flag combination I haven't understood, am I calling the wrong function entirely or is there another idiom for doing this?
Answer: Unfortunately, I think you're calling the wrong function entirely. It's been a while since I've done Win32 gui stuff.. but I seem to recall that there was a different way of bringing up a "select directory" box. It wasn't a straight Win32 function, but was some shell API function that required a whole heap of code to do the simplest thing.
Update: A bit of google reveals the SHBrowseForFolder function.
Update two: And here is an example for Python.
Answer: As Greg mentions, the function you want is a shell function. The specific function you need is SHBrowseForFolder, which is pretty messy to call. There's also PyWin32 documentation for it which mentions the browse_for_folder.py sample.


How to write $x= \sqrt{n^2+2}$ as a continued fraction and prove that x is irrational?

Question: I have to write $x= \sqrt{n^2+2}$ as a continued fraction, where $n \in N^*$.
I tried something like this:
$$n< \sqrt{n^2+2}<n+1 \text{ so } [a_{0}]=n\\ x_1= \frac{1}{x-a_0}=\frac{1}{2}(\sqrt{n^2+2}+n), [a_1]=n $$
but for $x_2$ I obtained $\frac{2}{\sqrt{n^2+2}}$. From here I don't know how to proceed.
Comment: Welcome to Mathematics Stack Exchange.  Do you mean *continued* fraction?
Comment: I don't really know English terms, thanks for the correction
Answer: Consider instead $y=x-n$ then we have
\begin{align}
y
&=\sqrt{n^2+2}-n\\
&=\frac{\left(\sqrt{n^2+2}-n\right)\left(\sqrt{n^2+2}+n\right)}{\sqrt{n^2+2}+n}\\
&=\frac2{\sqrt{n^2+2}+n}\\
&=\frac1{n+\frac{y}2}\\
&=\frac1{n+\frac{1/(n+y/2)}2}\\
&=\frac1{n+\frac1{2n+y}}\\
\end{align}
Applying this final recurrence should give a continued fraction representation of
$$y=[0;\overline{n,2n}]$$
and so we have
$$x=[n;\overline{n,2n}]$$
$x$ is then irrational because any rational number has a finite continued fraction representation.


Big-$O$ of $ \log \binom{n}{n/2} $

Question: I'm asked to evaluate this: $ \mathcal{O} \bigg( \log_2 \binom{n}{n/2} \bigg) $.
I played with this a bit and I keep getting $\mathcal{O} (n\log n)$.
When I substitute $n! = \sqrt{2\pi n} \Big(\dfrac{n}{e}\Big)^n $ I get $\mathcal{O}(n)$, which is the correct answer.
Can you please tell me how to do it without using the above substitution?
Comment: You can also use the majoration of $\binom{n}{n/2}$ by $2^n$ (this is the sum of the $\binom{n}{k} $).
Comment: Is your goal to make the "substitution" rigorous (e.g. using the precise statement of Stirling's approximation), or to do it without using Stirling at all?
Comment: @NateEldredge without using Stirling. Stirling's formula is only an approximation, right? Is there any straightforward way to prove it?
Comment: @AltunHasanli: Well, it is an approximation, but there are theorems about how large the error in the approximation might be.  [Wikipedia](https://en.wikipedia.org/wiki/Stirling%27s_approximation) has lots of results and references.
Answer: I assume that $n=2k$.
Note that $\log_2\binom{n}{n/2}=O\left(\log\binom{n}{n/2}\right)$ by the change-of-base formula for logarithms. Thus, we just need to show that $$\log\binom{n}{n/2}=O(n).$$ Using Riemann-Stieltjes integration, we can show that $$\log(n!)=\sum_{j=1}^n\log(j)=n\log n-n+O(\log n).\tag{1}$$
This is actually stronger than what we need; we only need that $\log(n!)=n\log n+O(n)$. As such, we'll use the weaker statement in what follows.
Using $(1)$, the definition of the binomial, and the property of logarithms that $\log(a/b)=\log(a)-\log(b)$, we can show that for $n=2k$, $$\log\binom{n}{n/2}=\log\left(\frac{(2k)!}{(k!)^2}\right)=2k\log(2k)-2k\log(k)+O(k)=O(n).$$
Comment: Sorry, I'm not familiar with $\Theta(f(x))$ notation. Can you tell me the definition?
Comment: @Altun we aren't ignoring anything. It is precisely that asymptotic that allows you to deduce the desired bound.
Comment: Also, just reading that link, I think it is clear the $O(f(x))$ and $\Theta(f(x))$ are not the same thing

Big-$O$ of $ \log \binom{n}{n/2} $


How to programmatically add a user to a group in Drupal 7

Question: I am trying to programmatically create a group node and add a user to that group in Drupal 7. The group node is being created just fine but the user is not being added to the group and I am not getting any errors. I am guessing I am using the og_group function incorrectly but I am not sure. What am I doing wrong?
function MYMODULE_form_submit($form_id, $form_values) {
    global $user;

    $node = new stdClass();

    $node->type     = "group";
    $node->uid      = $user->uid;
    $node->title        = t("Group Node Title");
    $node->body     = t("Group Node Body");
    $node->status       = 1;
    $node->promote      = 0;
    $node->comment      = 1;

    $node->og_description   = t("OG Description");
    $node->og_register  = 0;
    $node->og_directory = 0;
    $node->og_private   = 1;
    $node->og_selective = 3;

    $node = node_submit($node);
    node_save($node);

    $account = user_load(2);

    og_group($node->nid, array(
                "entity type"       => "user",
                "entity"        => $account,
                "membership type"   => "OG_MEMBERSHIP_TYPE_DEFAULT",
            ));

    drupal_set_message(t("Finished"));
}

Comment: hi max - you raised a good question . thx alot
Answer: I figured it out. It ended up not working because the group ID is NOT the same as the node ID for that organic group. Here is the working version:
function MYMODULE_page_form_submit($form_id, $form_values) {
    global $user;

    $node = new stdClass();

    $node->type     = "group";
    $node->uid      = $user->uid;
    $node->title        = t("Group Node Title");
    $node->body     = t("Group Node Body");
    $node->status       = 1; //(1 or 0): published or not
    $node->promote      = 0; //(1 or 0): promoted to front page
    $node->comment      = 1; //2 = comments on, 1 = comments off

    $node->og_description   = t("OD Description");
    $node->og_register  = 0;
    $node->og_directory = 0;
    $node->og_private   = 1;
    $node->og_selective = 3;

    $node = node_submit($node);
    node_save($node);

    // Get the group ID from the node ID
    $group = og_get_group("node", $node->nid);

    // Load the user we want to add to the group (ID #2 was my test user)
    $account = user_load(2);

    // Add the user to the group
    og_group($group->gid, array(
                "entity type"       => "user",
                "entity"        => $account,
                "membership type"   => OG_MEMBERSHIP_TYPE_DEFAULT,
            ));

    // Changes the users role in the group (1 = non-member, 2 = member, 3 = administrator member)
    og_role_grant($group->gid, $account->uid, 3);

    drupal_set_message(t("Finished"));
}

Answer: Since OG7-2.x the node ID == group ID, there is no need to use og_get_group(). And in og_group() and og_role_grant() your group type is the first argument. So here is the same code for OG 7.x-2.x
function MYMODULE_page_form_submit($form_id, $form_values) {
global $user;

$node = new stdClass();

$node->type     = "group";
$node->uid      = $user->uid;
$node->title        = t("Group Node Title");
$node->body     = t("Group Node Body");
$node->status       = 1; //(1 or 0): published or not
$node->promote      = 0; //(1 or 0): promoted to front page
$node->comment      = 1; //2 = comments on, 1 = comments off

$node->og_description   = t("OD Description");
$node->og_register  = 0;
$node->og_directory = 0;
$node->og_private   = 1;
$node->og_selective = 3;

$node = node_submit($node);
node_save($node);

// Load the user we want to add to the group (ID #2 was my test user)
$account = user_load(2);

// Add the user to the group
og_group('node', $node->nid, array(
            "entity type"       => "user",
            "entity"        => $account,
            "membership type"   => OG_MEMBERSHIP_TYPE_DEFAULT,
        ));

// Changes the users role in the group (1 = non-member, 2 = member, 3 = administrator member)
og_role_grant('node', $node->nid, $account->uid, 3);

drupal_set_message(t("Finished"));

}
Comment: Sorry if I did something wrong. I believe I provide an answer for the people who come here through a search engine and are using 7.x-2.x. You may delete the entire post if it doesn't make sence here.
Comment: This works well with 7.2.x. As mentioned the 7.1.x had this og_get_group function but that has been removed in 7.2.x. So for those looking for the later, please use this.
Comment: This does not provide an answer to the question. To critique or request clarification from an author, leave a comment below their post - you can always comment on your own posts, and once you have sufficient [reputation](http://drupal.stackexchange.com/faq#reputation) you will be able to [comment on any post](http://drupal.stackexchange.com/privileges/comment).
Comment: Your answers is a good start, but pointing out what is wrong in the question isn't enough for this to be considered an answer. Please revise the text to be more helpful by telling people what to do instead of using og_get_group, and the downvotes will likely be converted to up-votes instead. :)
Comment: Ok, I edited my post. I guess this is what you mean?
Comment: I think what Capono is claiming is supported by this issue ticket: https://drupal.org/node/1670642
Comment: Thank you for posting this, was lots faster than redoing it myself :)
Answer: Adding programmatically Group  content:
$node->type     = "group_post";
$node->uid      = $user->uid;
$node->title        = t("Group postNode Title");
$node->body     = t("Group Node Body");
$node->status       = 1; //(1 or 0): published or not
$node->promote      = 0; //(1 or 0): promoted to front page
$node->comment      = 1; //2 = comments on, 1 = comments off

$node->og_group_ref['und'][] = array('target_id' => $gid);

$node = node_submit($node);
node_save($node);


Method of Characterisitcs

Question: How can I use the method of characteristics in order to solve the following:
\begin{equation}
u(x,b,t)+b.\nabla_xu(x,b,t)=0
\end{equation}
with the following initial condition:
\begin{equation}
u(x,b,0)= |x|+|b|^2
\end{equation}
Thanks in advance.
Comment: You have closed your question about discriminant, as I was in the process of writing a solution. Please reopen it and let me know it.
Comment: @JeanMarie Oh my god, im so sorry, Ive reopened it right now, please consider sharing the solution.
Answer: There is just one derivative (with respect to $x$) in this equation, so it's really an ordinary differential equation with $b$ and $t$ as parameters.  In particular, the "initial condition" can't be of the given form: rather, for each $b$ and $t$ it must specify $u(x_0(b,t), b, t)$ for some
$x_0(b,t)$.

Method of Characterisitcs


Trouble centre-aligning items within a QtQuick StackLayout

Question: I'm having trouble centre-aligning items within a QtQuick StackLayout using qml. As far as I can see I'm doing things correctly according to the docs, but I can't get the behaviour I'm after. Any help would be greatly appreciated.
I'd like to use a stack layout such that when the item at the current index is smaller than the minimum size of the layout, it is not stretched but positioned in the centre of the layout. I understand the mechanism for this is the Layout.alignment attached property which I set to Qt.AlignHCenter | Qt.AlignVCenter on the item, however this seems to have no effect. The item remains in the top left corner.
I also need the stack layout to have an implicit size of the Item at the current index, rather than the maximum size of all the items. This I think I have achieved by overriding the implicit size properties.
I've got a minimal reproduction of my issue in the snippet bellow. The red Rectangle should be centred within the StackLayout, however it is positioned in the top left corner. You can paste this into qmlonline.kde.org to get a quick render of the scene.
import QtQuick 2.15
import QtQuick.Layouts 1.15
import QtQuick.Controls 2.15

ColumnLayout {
    StackLayout {
        id: stack

        currentIndex: 0
        implicitWidth: children[currentIndex].implicitWidth
        implicitHeight: children[currentIndex].implicitHeight

        Layout.minimumWidth: 400
        Layout.minimumHeight: 250
        Layout.fillWidth: true
        Layout.fillHeight: true

        Rectangle {
            color: "red"
            implicitWidth: 100
            implicitHeight: 100
            Layout.alignment: Qt.AlignHCenter | Qt.AlignVCenter
            Layout.fillHeight: false
            Layout.fillWidth: false
        }

        Rectangle {
            color: "green"
            implicitWidth: 500
            implicitHeight: 300
            Layout.fillHeight: false
            Layout.fillWidth: false
        }
    }
    RowLayout {
        Button {
            text: "Red"
            onClicked: stack.currentIndex = 0
        }
        Button {
            text: "Green"
            onClicked: stack.currentIndex = 1
        }
    }
}

Comment: If I'm correct, according to the QQuickStackLayout [source code](https://codebrowser.dev/qt5/qtdeclarative/src/imports/layouts/qquickstacklayout.cpp.html#252), the StackLayout doesn't have any alignment options.
Answer:
understand the mechanism for this is the Layout.alignment attached property which I set to Qt.AlignHCenter | Qt.AlignVCenter on the item, however this seems to have no effect. The item remains in the top left corner.

StackLayout does not support Layout.alignment attached property... The list of supported properties is explicitly listed in the documentation.
Simply wrap your rectangle inside an Item, which will occupy all space inside StackLayout by default and center Rectangle in it.
        Item {
            Rectangle {
                anchors.centerIn: parent

                color: "red"
                implicitWidth: 100
                implicitHeight: 100
            }
        }

I also need the stack layout to have an implicit size of the Item at the current index, rather than the maximum size of all the items. This I think I have achieved by overriding the implicit size properties.

Yes, so simply bind wrapping Item implicit sizes to match wrapped Rectangle
        Item {
            implicitWidth: rect.implicitWidth
            implicitHeight: rect.implicitHeight

            Rectangle {
                id: rect

                anchors.centerIn: parent

                color: "red"
                implicitWidth: 100
                implicitHeight: 100
            }
        }

Demo
Comment: Thanks for the response. I understand now - the alignment property is not supported.

Unfortunately, your suggested solution will not work for my use case because the component I'm using (the Rectangle for the sake of the example) needs to sometimes be constrained by the bounding box of the Item. For example, if the Layout descides to squash the item to smaller than its implicitHeight, I need the Rectangle to be similarly squashed. In the suggestion this will not be the case.
Comment: It's a real shame that alignment is not supported. I can't see any neat way around this problem, other than using a `RowLayout` and manually setting the visible properties of the children to fake the behaviour of a stack. This is what I've had to go for in the end, btw.
Comment: @CrouchEndTiger you can bind `width` and `height` of the `Rectangle` to the `width` and `height` of the `Item`, then `Item` will become completely opaque. You didn't ask it in the original question, so I didn't put it into the code, but obviously you can do it.
Comment: But if I do that then I lose the effective center alignment on the Rectangle - it will simply fill the width and height, which I could have done without the item..
Comment: My desired layout is such that the Rectangle remains centred when either it's width or height is less than the layout but is squashed when either dimension exceeds the size of the Layout.
Comment: @CrouchEndTiger thus bind `Rectangle` `width` to something like `Math.min(implicitWidth, parent.width)`
Comment: Sure, but then I'm just reimplementing the missing alignment property. Seems like a hole in the QtQuick.Layouts module which is supposed to handle exactly this stuff without expensive custom width bindings or wrapper Items.
Comment: @CrouchEndTiger I agree that Qt Quick layouts need some love from TQTC in general...
Answer: [REWRITE]
StackLayout is typically useful when your children changes and that you wish your children to implicit inherit the dimensions of your parent, e.g.
Page {
    StackLayout {
        id: stack
        anchors.fill: parent
        Page { Rectangle { anchors.centerIn: parent; width: 100; height: 100; color: "red" } }
        Page { Rectangle { anchors.centerIn: parent; width: 500; height: 300; color: "green" } }
    }
    footer: RowLayout {
        Button { text: "Red"; onClicked: stack.currentIndex = 0; }
        Button { text: "Green"; onClicked: stack.currentIndex = 1; }
    }
}

However, in your case, the size of your children are independent and you want your children to have Layout properties such as Layout.alignment. In this case, I think we can refactor and remove StackLayout and directly control visible on the children:
import QtQuick 2.15
import QtQuick.Layouts 1.15
import QtQuick.Controls 2.15
Page {
    property int currentIndex: 0
    ColumnLayout {
        width: parent.width
        Rectangle {
            color: "red"
            Layout.alignment: Qt.AlignHCenter | Qt.AlignVCenter
            Layout.preferredWidth: 100
            Layout.preferredHeight: 100
            visible: currentIndex === 0
        }
        Rectangle {
            color: "green"
            Layout.alignment: Qt.AlignHCenter | Qt.AlignVCenter
            Layout.preferredWidth: 500
            Layout.preferredHeight: 300
            visible: currentIndex === 1
        }
        RowLayout {
            Button {
                text: "Red"
                onClicked: currentIndex = 0
            }
            Button {
                text: "Green"
                onClicked: currentIndex = 1
            }
        }
    }
}

You can Try it Online!
Comment: Thanks for the answer, but this doesn't really solve my problem. With these Page elements being resized by the StackLayout rather than the actual rectangles I lose much of the flexibility that I would gain from using a layout. For example if I further constrain my stack to have a maximum size then the rectangles will not be constrained within this maximum, they will overlap the parent pages which are constrained.
Comment: @CrouchEndTiger I rewrote my answer guessing your requirements. In your question I am still not entirely sure of the purpose of changing the dimensions of the StackLayout, but, as in the above rewrite, I am not even convinced that the StackLayout is necessary.