Error handling of a Custom Form Handler in ATG

Question: I am new to ATG. And I am trying to use RepositoryFormHandler of my own. But I am not able to do the validations on the form.
Here is my .java file:
public class MyLoginBean extends RepositoryFormHandler {

    private String logname;
    private String logpwd;
    private String message;

    public String getLogname() {
        return logname;
    }

    public void setLogname(String logname) {
        this.logname = logname;
    }

    public String getLogpwd() {
        return logpwd;
    }

    public void setLogpwd(String logpwd) {
        this.logpwd = logpwd;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public boolean handleLogname(DynamoHttpServletRequest pRequest,
            DynamoHttpServletResponse pResponse) throws ServletException,
            IOException {
        boolean tf=true;
        if(logname.isEmpty() || logname==null)
        {
            tf=false;
            setMessage("User name can't empty");
        }

        System.out.println("inside logname");
        return tf;
    }

    public void handleFormException(DropletFormException exception,
            DynamoHttpServletRequest request, DynamoHttpServletResponse response) {
        // TODO Auto-generated method stub
        super.handleFormException(exception, request, response);
    }

}

And here is my .jsp file:
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%@ taglib uri="/dspTaglib" prefix="dsp" %>
<dsp:importbean bean="/atg/dynamo/droplet/ErrorMessageForEach"/>
<dsp:importbean bean="/dynamusic/MyLoginBean"/>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Custom Login</title>

<dsp:form style="color:white">

                    <dsp:droplet name="ErrorMessageForEach">
                        <dsp:param bean="MyLoginBean.formExceptions" name="exceptions"/>
                        <dsp:oparam name="output">

                                <dsp:valueof param="message"/>

                        </dsp:oparam>
                    </dsp:droplet>

                User Name:

                Password:

                <dsp:input type="text" name="logname" bean="MyLoginBean.logname"> </dsp:input>

                <dsp:input type="password" name="logpwd" bean="MyLoginBean.logpwd"> </dsp:input>

                <dsp:input type="submit" bean="MyLoginBean.login"> </dsp:input>

</dsp:form>

This is all I've tried so far and still trying something else.
Please suggest the solution for it and also tell me the mistakes, if any, in the code pasted here.
Comment: Your accessor to `logname` will conflict with your `handleLogname` method as both of these will be referred to by the form as `MyLoginBean.logname`. Looks like you subsequently fixed this by having `MyLoginBean.login` on the JSP but without a related `handle` method in the Java code. Also see Patrick's comments for more guidance.
Answer:
Don't override handleFormException
Instead of using setMessage, use ATG's built-in behavior.  All form handlers inherit a Vector of form exceptions from the GenericFormHandler superclass.  To add an error, use:

addFormException(new DropletException("Your error message"));
Then, at the end of your method, call:
return checkFormRedirect(getSuccessUrl(), getFailUrl(), pRequest, pResponse);
This checks if any form exceptions have been added, and if so, redirects to the failUrl, otherwise redirects to the successUrl.

By convention, you should name your form handler *FormHandler, for example ProfileFormHandler, BillingInfoFormHandler, PaymentInfoFormHandler etc.

Hope this helps.  See http://docs.oracle.com/cd/E22630_01/Platform.1002/apidoc/atg/droplet/GenericFormHandler.html#getFormExceptions()


where should the site root directory be?

Question: Where should I put my site root directory "my_site"?
Any best practice?
/var/www/my_site/
/var/local/sites/my_site/
/usr/share/wwww/my_site/
/usr/local/my_site/
/opt/my_site/
/srv/my_site/

Comment: Whist there should only be one 'best practice' in reality everyone has their own. Use the [FHS](http://www.linuxfoundation.org/collaborate/workgroups/lsb/fhs).
Answer: There is no best place to put it.  It's a matter of preference.
Putting it under /var/www is fairly common.  I use /var/www/sites/<vhost>.
Putting it under the others isn't common.
I personally would never put it under /usr/share.
Just make sure you put it in the same place consistently.  If you end up managing dozens or hundreds of web servers and the DocumentRoot varies from server to server you're going to have a bad time.
Answer: Practice varies, and I don't think that there is any general consensus or that it matters enough for there to really be a "best".
Distributions tend to default to /var/www, which makes sense if you interpret /var as "writable system data". Many people just follow this default and put their own stuff there.
Other people (and, this was often the distro default > 15 years ago) use /home/www or similar, right next to any user home directories. I think generally this is considered not best practice, as policies for users and server application data are generally very different, and there may be a user associated with the service which shouldn't have write access to the files, and overall it just seems like a messy use of the namespace.
/usr/share is also generally not a good idea, because on modern distros /usr (with the exception of /usr/local) is territory which should be under control of the distribution's package manager, and not written to otherwise.
On the positive side: the Filesystem Hierarchy Standard specifies /srv as basically specifically for this purpose:

/srv contains site-specific data which is served by this system.

and

[...] /srv should always exist on FHS compliant systems and should be used as the default location for such data.

So, if you really want a standard to follow, there is one. Personally, I like this, and have found that it makes backup policy much easier. (Most of /var is transient variable data that doesn't need to be retained for long if at all, at least as long as you're following the practice of putting the actual "business" data in /srv.)
Answer: There is no hard coded preference set for putting it under any particular directory.
I prefer /home/acountname/public_html to keep all site related data if I am hosting multiple website on single server since  I put account name as business or user or client for which I am hosting the website .
Most popular document root are /var/www/html/ and /var/www/sites/if you are hosting only one website.
You can put anywhere as per your need. But off course no one will suggest putting it under /usr/share/.
Answer: There isn't a  "correct" place, but is not a bad idea trying to respect the habits of distributions. According to the FHS and other sources, the data owned and managed by programs belongs to 6 different folders:

/usr/share: non-modifiable data thought to be independent of the architecture (of course, for system administrators there no exists non-modifiable data).
/etc: non-modifiable configuration data (again, system administrators have always the last word).
/run: variable data used by processes during their whole lifetime (but non-persistent between reboots).
/tmp: variable data used during short periods of time (non-persistent between reboots).
/var: other auxiliar/optional data (persistent data, data which can be modified by the user, and in general, other data not suitable for other folders). Common subfolders:

www: websites
mail: mail boxes
tmp: same as /tmp, but for temporary data which need survive between reboots.
spool: data waiting for be delivered to or used by other programs/hosts.
lock: locked files.

/srv: Same as /var, but thought for services instead of other programs.

According to these descriptions, websites should go to /srv/www, but debian system don't use it. They used /var instead (/var/www, /var/mail and so on).


http to https redirection - apache2

Question: I have a odoo instance running in an ubuntu16 server. Apache is acting as the front end server and is proxypassing the request to the odoo instance. I have now configured the virtualhost to enable SSL on the frontend URL, which works for the URLs : https://example.com:8069 and https://www.example.com:8069
What I need to achieve is, when someone access the URLs http://example.com:8069 and http://www.example.com:8069 they should be redirected to https://example.com:8069
I cannot use .htaccess methods, since the application doesn't have it. Also, the redirect parameter cannot be passed in the vhost of non-ssl port, because there is no non-ssl port (only this ssl port is enabled for the application, and default ports are already allocated for other websites.)
The virtualhost entries are:
<code><IfModule mod_ssl.c>
<VirtualHost *:8069>

ServerName example.com:8069
ServerAlias www.example.com:8069
RewriteEngine On
RewriteCond %{HTTP_HOST} ^(www\.)(.*) [NC]
RewriteRule (.*) https://%2%{REQUEST_URI} [L,R=301]

SSLEngine on
SSLCertificateKeyFile /etc/apache2/sslsrp.com/example.key
SSLCertificateFile    /etc/apache2/sslsrp.com/example.crt
SSLCertificateChainFile /etc/apache2/sslsrp.com/example.txt

ProxyPreserveHost On
ProxyRequests Off

ProxyPass /longpolling/ http://localhost:8072/
ProxyPassReverse /longpolling/ http://localhost:8072/

ProxyPass / http://localhost:9069/
ProxyPassReverse / http://example.com:8069/

</VirtualHost>
</IfModule>
</code>
Is this possible in apache?
Comment: It is not possible at all. You must use different port numbers.
Answer: This is a similar question as this one or this one or this one. It is still not possible to have http and https running on the same port.
Comment: Thanks bcs78 and @michael-hampton . I knew it's impossible to run both protocols on the same port, but couldn't help but wonder if there was some way to just get the requests to be redirected at least. Anyway, I just changed the current port to a non-ssl port, enabled another custom port for ssl, then redirected the current non-ssl port to the ssl one.

http to https redirection - apache2


Simple jQuery Slider

Question: I have to create simple image slider WITHOUT Views and other modules. I can use only custom post type slides.
How can I do that?
Comment: call the js of the slider in your theme's custom js and apply all the data with attributes like
Comment: In Drupal modules are the way to go to add functionality. If you are doing it any other way, you are asking for troubles alter. Unless you meant "how to create my own module to provide a slider?", maybe?
Answer: You need to follow the following steps

Download the Slider Plugin and paste required files in your active custom module(sites/all/modules/custom/yourmodule/js OR sites/all/modules/custom/yourmodule/css) OR in theme(sites/all/theme/yourtheme/js OR sites/all/theme/yourtheme/css) folder.
Create a new block in youmoudle using hook_block_info and hook_block_view functions.
Inside hook_block_view() call a function
<code>$block['content'] = 'get_slider';</code>
get_slider() will return the html for the slider. Make sure that the html returned follow the proper structure as mentioned in the Slider Plugin you have chosen. You can find the html example for each slider Plugin, follow the same html structure.
Add the corresponding JS files using drupal_add_js and CSS files using drupal_add_css
JS file is used to initialize the Slider to run.
Check your browser console to check errors
Answer: Just download any slider script, and use how it is using its images to make it slider.
Just follow through these steps:-

First paste the html of slider directly on the page
Include the necessary files (js/css)
Now fetch the images only of custom post type from database to make it dynamic

Slider will automatically start working.
There can be issues with drupal js and slider js files, so avoid  including unnecessary files.
Comment: *"paste the html of slider directly on the page where you want to show it"* sounds like a recipe for disaster. Finding where parts of HTML came from year later, or when you are taking over someone's else project is really a challenge (at best) if site is created like that.
Comment: @Molot, You can edit the answer rather than adding the comment. That would be better i think.
Comment: No, I can't. It would be a radical edit changing too much of your original content, and that's forbidden. Radical edits are something only the one who posted is allowed to do.
Comment: Thanks to everyone who tried to help me to understand this question. I am really not expected to get -4 for my question... It is weird... I am not drupal developer. I came from WordPress ...

Simple jQuery Slider


How to get the error vs. epochs (iterations) plot in matlab when using svm classification?

Question: I use svmtrain to train my data set and svmclassify to predict test set. I want to look at the optimization process, the error vs. epochs (iterations) plot. I look into the usage and the code and find out that there are no information regarding such problem. The only thing I can get is control of  the Maximum Iteration.
How to get the error vs. epochs (iterations) plot in matlab when using SVM classification?
Here is the code I modified. But not the one I want, I want the error at each epoch. Anybody did such analysis before? Thank you.
Best regards!

%# load dataset
load fisheriris                                %# load iris dataset
Groups = ismember(species,'setosa');           %# create a two-class problem

MaxIterValue = 210;                            %# maximum iterations
ErrVsIter = zeros(MaxIterValue, 2);            %# store error data

%# Control maximum iterations
for N = 200: MaxIterValue
%   options.MaxIter = N;
    option = statset('MaxIter', N);
    %# 5-fold Cross-validation
    k = 5;
    cvFolds = crossvalind('Kfold', Groups, k);      %# get indices of 5-fold CV
    cp = classperf(Groups);                         %# init performance tracker

    for i = 1:k                                     %# for each fold
      testIdx = (cvFolds == i);                     %# get indices of test instances
      trainIdx = ~testIdx;                          %# get indices training instances

      %# train an SVM model over training instances
      svmModel = svmtrain(meas(trainIdx,:), Groups(trainIdx), ...
                 'options',option, 'Autoscale',true, 'Showplot',false, 'Method','QP', ...
                   'BoxConstraint',2e-1, 'kernel_function','linear');

      %#plotperform(svmModel);

      %# test using test instances
      pred = svmclassify(svmModel, meas(testIdx,:), 'Showplot',false);

      %# evaluate and update performance object
      cp = classperf(cp, pred, testIdx);

    end
    %# get error rate
    ErrVsIter(N, 1) = N;
    ErrVsIter(N, 2) = cp.ErrorRate;

end

plot(ErrVsIter(1:MaxIterValue,1),ErrVsIter(1:MaxIterValue,2));
Comment: Can you provide some level of runnable example?
Comment: Hi Ben, I added an example. Thank you for your help.
Answer: You do it all correct, the problem is SVM is finding solution every time! So each epoch has CorrectRate=1, try and type cp.CorrectRate in your codes to see it.
The problem is in below line:
 Groups = ismember(species,'setosa');

The data is so simple for SVM to solve.
and also plot it like this:
plot(ErrVsIter(200:MaxIterValue,1),ErrVsIter(200:MaxIterValue,2));


Duvida Exercicio Collections - Interface Queue

Question: Pessoal estou com uma dúvida neste exercício sobre Collections em que Devo usar a interface Queue :

Escreva um programa que simule o controle de uma pista de decolagem de aviões em um aeroporto. Neste programa, o usuário deve ser capaz de realizar as seguintes tarefas:
a) Listar o número de aviões aguardando na fila de decolagem;
b) Autorizar a decolagem do primeiro avião da fila;
c) Adicionar um avião à fila de espera;
d) Listar todos os aviões na fila de espera;
e) Listar as características do primeiro avião da fila.

Considere que os aviões possuem um nome e um número inteiro como identificador. Adicione outras características conforme achar necessário.
Comecei meu código assim mas eu parei na questão "B", tenho duvidas se é necessário utilizar um método
import java.util.ArrayList;

public class ControledeTrafego {

    private String nome;
    private int codigo;

    public ControledeTrafego(String nome, int codigo) {
        super();
        this.nome = nome;
        this.codigo = codigo;
    }
    public String getNome() {
        return nome;
    }
    public void setNome(String nome) {
        this.nome = nome;
    }
    public int getCodigo() {
        return codigo;
    }
    public void setCodigo(int codigo) {
        this.codigo = codigo;
    }

    public void autorizacao(ControledeTrafego autorizacao){
        System.out.println("Favor comnfirmar a autorização do voo");
    }
}

Este é o Programa :
package Exercicio3;

import java.util.LinkedList;
import java.util.Queue;

public class Controle {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Queue<ControledeTrafego> aviao =  new LinkedList<>();

        ControledeTrafego aviao1 = new ControledeTrafego(" Tam ", 747);
        ControledeTrafego aviao2 = new ControledeTrafego(" Gol ", 737);
        ControledeTrafego aviao3 = new ControledeTrafego(" Azul", 722);

        aviao.add(aviao1);
        aviao.add(aviao2);
        aviao.add(aviao3);

        System.out.println("Numero de avioes na fila de embarque : " +aviao.size());
    }
}

Comment: Não entendi a diferença da fila de decolagem e fila de espera
Answer: Apesar de não entende o porquê de duas filas, a implementação seria algo da seguinte forma:
Classe Aviao:
public class Aviao {

  private String nome;
  private int codigo;

  public Aviao(String nome, int codigo) {
    super();
    this.nome = nome;
    this.codigo = codigo;
  }

  public String getNome() {
    return nome;
  }

  public void setNome(String nome) {
    this.nome = nome;
  }

  public int getCodigo() {
    return codigo;
  }

  public void setCodigo(int codigo) {
    this.codigo = codigo;
  }

  public void autorizacao(Aviao autorizacao) {
    System.out.println("Favor confirmar a autorização do vôo.");
  }

  @Override
  public String toString() {
    return this.getCodigo() + " - " + this.getNome();
  }
}

Classe Controle:
import java.util.LinkedList;
import java.util.Queue;

public class Controle {

  private final Queue<Aviao> espera = new LinkedList<>();

  public void listar() {
    System.out.println("============ LISTANDO ============");
    this.espera.forEach(a -> System.out.println(a));
  }

  public void listarPrimeiro() {
    System.out.println("============ PRIMEIRO ============");
    System.out.println(this.espera.element());
  }

  public void adicionar(Aviao aviao) {
    System.out.println("=========== ADICIONANDO ===========");
    System.out.println(aviao);
    this.espera.add(aviao);
  }

  public Aviao autorizarDecolagem() {
    Aviao aviao;

    aviao = this.espera.remove();
    System.out.println("====== AUTORIZANDO DECOLAGEM ======");
    System.out.println(aviao);

    return aviao;
  }

  public static void main(String[] args) {
    Controle controle = new Controle();

    controle.adicionar(new Aviao("Tam", 747));
    controle.adicionar(new Aviao("Gol", 737));
    controle.adicionar(new Aviao("Azul", 722));

    controle.listar();
    controle.autorizarDecolagem();
    controle.listar();
  }
}

A saída gerada para esta implementação é a seguinte:

=========== ADICIONANDO ===========
747 - Tam
=========== ADICIONANDO ===========
737 - Gol
=========== ADICIONANDO ===========
722 - Azul
============ LISTANDO ============
747 - Tam
737 - Gol
722 - Azul
====== AUTORIZANDO DECOLAGEM ======
747 - Tam
============ LISTANDO ============
737 - Gol
722 - Azul


Return NSDictionary data from popup tableview

Question: I have a popup tableview (ViewController2) appearing when I click a button on ViewController1.  Then when I select a row in the table, I want those values to be sent back to ViewController1.  I have a NSDictionary set up.  It works fine in a regular navigation controller, but trying to do it with dismissModalViewControllerAnimated, so the tableview drops back down, and the data is appearing in the first view.
This is similar to this question here I think: http://www.iphonedevsdk.com/forum/iphone-sdk-development/39995-return-data-dismissmodalviewcontrolleranimated.html
Here is my code:
ViewController1.h:
<code>@protocol ViewController1Delegate;
@interface ViewController1 : UIViewController <ViewController2Delegate> {
    id <ViewController1Delegate> delegate;
}
@property (nonatomic, assign) id <ViewController1Delegate> delegate;
@end
@protocol ViewController1Delegate
- (void)viewController1DidFinish:(ViewController1 *)controller;
@end
</code>
ViewController1.m:
<code>-(void)buttonGoToViewController2 {
    ViewController2 *controller = [[ViewController2 alloc] initWithNibName:@"ViewController2" bundle:nil];

//  this controller.delegate = self causes it to crash if i have it uncommented for some reason...
//  controller.delegate = self;

    controller.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
    [self presentModalViewController:controller animated:YES];
    [controller release];
}
</code>
ViewController2.m:
<code>- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

    if(searching) {
        // Navigation logic may go here. Create and push another view controller.
        NSDictionary *selectedCountry = [self.copyListOfItems objectAtIndex:indexPath.row];
        ViewController1 *dvController = [[ViewController1 alloc] initWithNibName:@"ViewController1" bundle:nil andDictionary: selectedCountry];
        NSLog(@"selected hit this %@",selectedCountry);
        // Pass the selected object to the new view controller.
        [self.navigationController pushViewController:dvController animated:YES];
        [dvController release];
        [self dismissModalViewControllerAnimated:YES];

    }
    else {
        // Navigation logic may go here. Create and push another view controller.
        NSDictionary *dictionary = [self.listOfItems objectAtIndex:indexPath.row];
        ViewController1 *dvController = [[ViewController1 alloc] initWithNibName:@"ViewController1" bundle:nil andDictionary: dictionary];
        NSLog(@"normal hit this %@",dictionary);
        // Pass the selected object to the new view controller.
        [self.navigationController pushViewController:dvController animated:YES];
        [dvController release];
    }
}
</code>
Answer: In your ViewController2 code you are creating a new ViewController1 object and giving it your NSDictionary.  When you dismiss ViewController2 you go back to the original ViewController1, which never went anywhere and was never sent the NSDictionary. You need to provide ViewController2 with access to the ViewController1 object that presented it (I suggest doing it via a delegate pattern) in order to set the NSDictionary there.
Comment: So in my ViewController2 didSelectRowAtIndexPath, would I have something like this?

 `ViewController1Delegate *appDelegate = (ViewController1Delegate *)[[UIApplication sharedApplication] delegate];
 NSString *nodeText = [[listOfItems objectAtIndex:indexPath.row] objectForKey:@"station"];
 NSString *passThis = [appDelegate nodeText];`

And then in my ViewController1, I have something like this?

 `ViewController1Delegate *appDelegate = (ViewController1Delegate *)[[UIApplication sharedApplication] delegate];
 PassedString = [appDelegate passThis];`
Comment: No, nothing nearly that complicated.  Check out a tutorial on delegates and protocols like this one: http://iphonedevelopertips.com/objective-c/the-basics-of-protocols-and-delegates.html


Serilog Additional Properties with Exception logging

Question: I am using serilog with asp net core 3
It is setup and logging exceptions automatically - so i have no error handling to log the errors.
I was attempting to add extra context properties to logged items, and have added middleware to log these.
LogContext.PushProperty("Email", email);
LogContext.PushProperty("Url", url);

These are added if i manually log myself but any logs added automatically when an error occurs does not have these items added.
Any ideas?
NOTE: i have read this...
https://blog.datalust.co/smart-logging-middleware-for-asp-net-core/
This is the closest i have found to working around the issue, but this catches the exception and manually logs it, which is a shame if this is the only way it can be done.
Comment: seems similar: https://stackoverflow.com/questions/62487408/adding-contextual-properties-to-serilog-logging-of-exceptions
Comment: similar yes but hopefully i have added some more detail.
If i catch the error and log it myself my code works - if i log an information or any other type of log it works.
what doesnt work is it doesnt add the context items for errors its logged itself.
As i have read, its in a different "context" or its "popped off the stack" but this doesnt help, you would think that this was a basic requirement for error logging?
Comment: Definitely not saying this is a dup (for a start the question is asked more directly).
`LogContext.PushProperty` / `Enrich.FromLogContext` definitely work on the assumption of a `using` and/or stackiness; the values are (and can only be) captured when a Logging call is made (which requires that to be still in the same context, not having unrolled everything and completed the teardown). I've not delved into the things one can do with asp.net core to stash context such that it can travel from such an inner context out to an exception handler middleware, but for me thats not Serilog dept.
Comment: Ok so what i have implemented is the only solution i guess.
I have a middleware class that wraps execution, captures the errors and manually logs them, then doesnt re throw, so the automatic error logging is then not called)
To me this is a shame, as things seem really good/useful, but this seems like a hack/workaround to me
Comment: Hm I'm pretty sure the DiagnosticContext or something can flow context from request processing out to global request logging and global exception logging. I remain hopeful you'll get a proper answer. Also not sure if yoiu're aware but the [most recent overview article by Nick covers ASP.NET Core 3](https://nblumhardt.com/2019/10/serilog-in-aspnetcore-3/)
Comment: Does this answer your question? [Serilog Logcontext properties are gone after exception handler](https://stackoverflow.com/questions/55223744/serilog-logcontext-properties-are-gone-after-exception-handler)
Answer: At first, LogContext is a stack; properties that are pushed onto the stack must be popped back off by disposing the object returned from PushProperty():
using (LogContext.PushProperty("Email", email))
using (LogContext.PushProperty("Url", url)){

    // middleware code
   ...
}

Otherwise, the behavior may be non-deterministic.

but any logs added automatically when an error occurs does not have these items added

I assume that error logging occurs outside of the scope, where these properties don't exist. In this case, try ThrowContextEnricher to enrich the exception log with properties from the original context where the exception was thrown.
// call it once on app startup
ThrowContextEnricher.EnsureInitialized();

...

// then each throwing will capture context,
// so you can enrich log in exception handler:
catch (Exception ex)
{
    using (LogContext.Push(new ThrowContextEnricher()))
    {
        Log.Error(ex, "Exception!");
    }
}

Or simply register ThrowContextEnricher globally at LoggerConfiguration (in this case ThrowContextEnricher.EnsureInitialized() is not required). So every exception log will be enriched:
Log.Logger = new LoggerConfiguration()
    .Enrich.With<ThrowContextEnricher>()
    .Enrich.FromLogContext()
    ...
    .CreateLogger();

Disclaimer: I am the author of that library, and I also left an example in this answer.


How to get documents from a collection using the $nin operator in mongodb

Question: I have a user schema like this
const userSchema= new mongoose.Schema({

  Username:{
      type:String,
      trim:true,
      required:true
  },
  email:{
    type:String,
    trim:true,
    required:true
},
hashed_password:{
    type:String,
    trim:true,
    required:true
},
salt:String,
created:{
type:Date,
default:Date.now,
},
updated:Date,
photo:{
data:Buffer,
contentType:String
},

about:{
 type:String
},

following:[{type:ObjectId,ref:"User",}],

followers:[{type:ObjectId,ref:"User"}]
})

when i run the query
User.find({$_id:{$nin:following}} , (err, users) => {
    if (err) {
      return res.status(400).json({
        error: err,
      });
    }
    res.json(users)
  //  let data=users

  //  console.log(following.length,"following")

  //  console.log(newuser)

  }).select("Username")

};
the following variable is an array of objects like this

[{"_id":"5e9c2c7aa9f4bc46e88c7635","Username":"Batman"},{"following":[],"followers":[],"_id":"5ead159d3b41d7061ce639fe","created":"2020-05-13T19:37:17.161Z"}]
after running the query i get an error:
 "errmsg": "unknown top level operator: $_id",
        "code": 2,
        "codeName": "BadValue",

how do i input the fields properly in my query
Answer: Remove $ from _id as with operator mongodb identify it as an operatorlike ($match etc) ,but there is no such operator so it throws error
User.find({_id:{$nin:following}} , (err, users) => {
    if (err) {
      return res.status(400).json({
        error: err,
      });
    }
    res.json(users)
  //  let data=users

  //  console.log(following.length,"following")

  //  console.log(newuser)

  }).select("Username")

};

Answer: You Can Follow This Code
db.inventory.find( { qty: { $nin: [ 5, 15 ] } } )

Comment: There is no qty even in the schema


Find the occurrences of unique element in list in python

Question: For finding occurrences of unique element in a list in python i used
import collections

a='77888'
b=list(collections.Counter(a).items())

but the b is sorted in order of occurences b=[('8',3),('7',2)]. But is want unsorted b. How can i achieve this?
Comment: No, `b` is **not** sorted. The order is arbitrary. Any sorting you think took place is a coincidence here. And the second value is a *number*, not a string; the output is `[('8', 3), ('7', 2)]`.
Comment: Why do you feel you need to list the `Counter()` contents in arbitrary order to find occurrences of unique elements?
Comment: I do not want arbitrary order. I want output as `b=[('7',2),('8',3)]` in the order of appearance
Comment: You are trying to find unique elements; can you give examples of input and what you wanted to find in those? Your sample doesn't have unique elements, to begin with. This sounds like you are chasing Y, but the real problem is X, see [What is the XY problem?](http://meta.stackexchange.com/q/66377)
Answer: To find unique items in the list a:
from collections import Counter

unique_items = [item for item, count in Counter(a).items() if count == 1]

If input is sorted then you could use itertools.groupby():
from itertools import groupby

unique_items = [key for key, group in groupby(a) if len(list(group)) == 1]

If you want to get items and their frequencies in the same order as in the input, you could define OrderedCounter:
from collections import Counter, OrderedDict

class OrderedCounter(Counter, OrderedDict):
    pass

then:
>>> list(OrderedCounter('77888').items())
[('7', 2), ('8', 3)]
>>> list(OrderedCounter('88877').items())
[('8', 3), ('7', 2)]


Finding the number of permutations

Question: Here is the following problem:
Suppose I have coordinates $(x,y,z)$ in which I choose 3 numbers (they are fixed) and permute them,
For example I may choose (1,2,3) then I will want to determine how many ways can I permute these numbers (3,2,1), (2,1,3) etc. However I may also have negatives in the permutations so (-3,2,1) or (-3,-1,-2) are both possible.
How many permutations are there and is there a way to mathematically express this?
What about the case for $x=y$ or $x=y=z$ or $(x,0,0)$?
Comment: Exactly where are you having trouble figuring this out? Some (if not all) of the cases, you should be able to figure out yourself, for instance $x=y=z$ or $x,0,0$.
Comment: Yes, $(x,0,0)$ can have 6 permutations but I would rather find a mathematical way of doing this instead of writing a list.
Answer: For the case of $(x,y,z)$ we have 3 distinct numbers they can be put in 3 places in $3!$ ways. Now in each place there can be either a negative or positive. So there can be $2^3$ ways in which the signs on the coordinates can be arranged so there are in total $3! \times 2^3 = 48$ ways to do this.
If say it of form $(x,x,x)$ or $(x,x,z)$ then in the first case excluding sign there is only one permutation which is obvious, but can be solved as, if we have $n$ objects and k of them are similar then ways of arranging them are $\frac{n!}{k!}$. So for two digits similar the permutations are $\frac{3!}{2!}=3$.    Now they can have positive or negative sign which are 8 possible ways.
So for $(x,x,x)$ it is $1 \times 8 = 8$
And for $(x,x,z)$ it is $3 \times 8 = 24$
All the above cases are assuming that the numbers are nonzero.
There can be forms $(x,0,0), (x, y,0), (0,0,0)$. The last one is trivial and has only one permutation. If there are $0$s then only the nonzero elements can have sign so if one of the numbers are $0$ there can be $4$ ways in which signs can be assigned. If there are two $0$s then there are one ways in which the signs can be assigned. The other rules remain the same.
Using all this we can give following formula.
$$2^{3-(\#of\_0s)}\times\frac{3!}{(\#of\_same\_digits)}$$

Finding the number of permutations


add column based on multiple conditions with mutate() in tidy R grep

Question: I am working to classify a wide data frame in an added column, but based on the threshold (>0) of multiple columns. Previous examples here on SO require complete names of columns and if else() statements with > and ==. But I need to be able to use grep() or contains() to isolate columns based on a common string.
Input dataframe:
library(tidyverse)
df <- data.frame(
    "ID" = c("asdf","vfdkun", "seifu", "seijd", "qweri"),
    "elephant_zoo" = c(1,1,1,2,0), #Should not be useful there
    "rhino_zoo" = c(1,2,3,1,0), #Should not be useful there
    "hippo_zoo" = c(1,1,0,0,0),
    "elephant_wild_A" = c(0,0,1,1,3),
    "rhino_wild_A" = c(0,0,4,3,1),
    "elephant_wild_B" = c(0,0,0,0,0),
    "rhino_wild_C" = c(0,0,1,5,7),
    "hippo_wild_B" = c(0,0,0,0,0)) %>%
  column_to_rownames(var = "ID")
df

In reality, this has many many more columns and rows!

Desired output dataframe has classified rows (ZOO and WILD) and a compilation of these CLASSIFICATION.
df_goal <- data.frame(
    "ID" = c("asdf","vfdkun", "seifu", "seijd", "qweri"),
    "elephant_zoo" = c(1,1,1,2,2), #Should not be useful there
    "rhino_zoo" = c(1,2,3,1,2), #Should not be useful there
    "hippo_zoo" = c(1,1,0,0,2),
    "elephant_wild_A" = c(0,0,1,1,3),
    "rhino_wild_A" = c(1,0,4,3,1),
    "elephant_wild_B" = c(0,0,0,0,0),
    "rhino_wild_C" = c(6,0,1,5,7),
    "hippo_wild_B" = c(0,0,0,0,0)) %>%
  column_to_rownames(var = "ID") %>%
    add_column(ZOO = c("zoo", "zoo", "zoo", "zoo", "")) %>%
    add_column(WILD = c("", "", "wild", "wild", "wild")) %>%
    add_column(CLASSIFICATION = c("zoo only", "zoo only", "both", "both", "wild only"))
df_goal

I am hoping to use a combination of mutate() and case_when(), but I cannot get the select of multiple columns correct.
Examples of attempts:
# using an if else statement
df %>%
   mutate(ZOO = ifelse(select(contains("zoo")) > 0, "zoo", "F"))

# using mutate and case_when
df %>%
   mutate(ZOO = case_when(
       select(contains("zoo")) > 0 ~ "zoo",
       TRUE ~ ""))

My actual data frame has many more categories, so being able to break it down into the ZOO vs WILD and then following up with the compiled column.
Answer: You can try using reduce from purrr package. One may use an intermediate function any_cols to made the code clearer and use it with across:
library(tidyverse)
any_cols <- function(df) reduce(df, `|`)
df %>%
    mutate(ZOO = ifelse(any_cols(across(contains("zoo"), ~`>`(.,0))), "zoo", "F"))
  elephant_zoo rhino_zoo hippo_zoo elephant_wild_A rhino_wild_A elephant_wild_B rhino_wild_C hippo_wild_B ZOO
1            1         1         1               0            0               0            0            0 zoo
2            1         2         1               0            0               0            0            0 zoo
3            1         3         0               1            4               0            1            0 zoo
4            2         1         0               1            3               0            5            0 zoo
5            0         0         0               3            1               0            7            0   F

df %>%
    mutate(ZOO =
             case_when(any_cols(across(contains("zoo"), ~`>`(.,0))) ~ "zoo",
                       TRUE ~ "F"))
  elephant_zoo rhino_zoo hippo_zoo elephant_wild_A rhino_wild_A elephant_wild_B rhino_wild_C hippo_wild_B ZOO
1            1         1         1               0            0               0            0            0 zoo
2            1         2         1               0            0               0            0            0 zoo
3            1         3         0               1            4               0            1            0 zoo
4            2         1         0               1            3               0            5            0 zoo
5            0         0         0               3            1               0            7            0   F


How can I prepopulate a field when creating a new node with the values from a field collection?

Question: I am creating an inventory management system in drupal. I have two different content types: and item and a purchase order.
An item has a name, style code, Colors (this is a field collection with a color name and color code), and a range of sizes (3 to 15 for shoes and XS to 4XL for shirts). Some items don't have colors and some don't have sizes.
In a purchase order, there is a purchase order number and any number of items ordered (a field collection with an entity reference to the item, a field for the number of items ordered, and field for the number of items received). Each item ordered will have one color (one of the colors that the item is available in) and any number of the sizes that was selected in the given item.
My question is how I can populate the color selection (probably a dropdown) with the colors that are in the field collection of the selected item (entity reference). I would also need to populate the sizes list with the sizes that were selected from the item, as well.
I am still pretty new to drupal, and I realize that I may be going about it the wrong way or that I may not have explained everything that someone would need to know to help me. But I am open to new ideas or different solutions. I haven't done much module development, but I would be willing to learn if needed.
Answer: You can try and look at this module. It allows to have corresponding node references and hence if you select something from one node, you can prepopulate the other node as well. http://drupal.org/project/cnr
Answer: You will probably need to write your own module to handle the content creation with the individual collections.  In a bug report on drupal.org, I give a code example that can be used to create a node and field collection (and a field collection within the field collection).
A stripped-down version might look like this:
<?php
$container = entity_create('entity_type', array('type' => 'entity_bundle')); // replace entity_type and entity_bundle with your info

// Set default values for fields in $container, except for the collection,
// which will be done later

// Now save the container
$container->save(); // necessary in order to attach field collections

// Create the collection
$field_collection = entity_create('field_collection_item', array('field_name' => 'field_collection_1')); // replace 'field_collection_1' as appropriate

// Set default values as necessary

// Now save the field_collection
$field_collection->setHostEntity('entity_type', $container); // again, replace entity_type as appropriate
$field_collection->save(TRUE); // calling this with TRUE is important!
}

$container->save(); // must be called again, otherwise the collections will not be added
?>

There's a lot of save() calls in here, but it gets the job done.
Answer: First let's review a bit the business model of your purchase order Content Type. Let's say there is an item node that represents a T-shirt that is available in green, blue and yellow colors and S, M, L sizes. Now, I want to buy two of those T-shirts, one small size in green color, and one large size, in blue color. So, the purchase order instance/node for this usecase, would have two field collection items:

Item id 3 (let's say 3 is the nid of the T-shirt), color green, size
small
Item id 3 (let's say 3 is the nid of the T-shirt), color blue,
size large

So, your field collection definition in the purchase order CT should have the following fields

Item id (single value field)
Color (single value field)
Size (single value field)

and given that model, I would also add a single value checkbox labeled 'Item received'. So it becomes apparent, that you need to change your current implementation to the one above, otherwise with your current implementation, a user cannot order the same T-shirt in different color/size combination (if I understood correctly from the details you provided)
Now, the CNR module suggested above is not a good solution, because a) it has been deprecated in favor of CER b) it is used in cases you want to populate bidirectional references between entities (if node A refers to B, then B is aware that it is referenced by A), which is not the usecase here.
Again, if I understood correctly, when a purchase order is placed (somehow in your context), the node create form for purchase order CT appears to the end user. Then, if the user selects an item, there should be color and size dropdown menus for choosing the desired color and size, depending on the underlying referenced item availabilities. Is that correct? Well, if this is the case, then coreyp_1 solution is not applicable either, as it implies that you save the purchase node programmatically. If you change your model to the one suggested above, then you don't have to do so. You will already have the field infrastructure in the purchase order CT and if you manage to pre-populate colors and sizes appropriately while creating a new instance of it, Drupal will handled the saving for you.
So, back to the original question. The solution depends on the field types for Color and Size. Are they taxonomies? Are they plain list items? In any case, the same fields (both for Color and Size) that are originally used for the Item, should be re-used for the purchase order CT as well. And as far as the pre-population is concerned, it can be implemented as suggested here


Go (language) general numeric type/interface

Question: I'm trying to write a package in Go that computes a equation using a "generic" type. To be specific, I want to implement the runge kutta 5 approximation.
This approximation calculates the value of a (unknown) function y at the point t0 + h using only the value of y at t0, the start time t0, the step width h and a differential equation dgl which is of the form dy/dt = g(t,y) where g is some function.
This approximation behaves exactly the same when working with scalar types as when working with vectors (or even matrices). More generally speaking: It works with everything that can be added/subtracted to a value of the same type and can be scaled by a scalar (for which I use float64)
So I tried to express this as a Go interface:
type Numeric interface {
    Add(rhs Numeric) Numeric
    Sub(rhs Numeric) Numeric
    Mul(rhs float64) Numeric
}

But when I try to "implement" this interface, I ran into troubles because of the parameters type:
type Vec6F struct {
    x, y, z float64
    vx, vy, vz float64
}

func (lhs *Vec6F) Add(rhs *Vec6F) rk5.Numeric {
    result := new(Vec6F)
    result.x = lhs.x + rhs.x
    result.y = lhs.y + rhs.y
    result.z = lhs.z + rhs.z
    result.vx = lhs.vx + rhs.vx
    result.vy = lhs.vy + rhs.vy
    result.vz = lhs.vz + rhs.vz
    return result
}

This gives me the error
cannot use result (type *Vec6F) as type rk5.Numeric in return argument:
        *Vec6F does not implement rk5.Numeric (wrong type for Add method
                have Add(*Vec6F) rk5.Numeric
                want Add(rk5.Numeric) rk5.Numeric

which is, on the one hand absolutely logic to me (because rhs could be another object implementing Numeric)
But on the other hand: How do I express something like that in Go? In C++ I could use operator overloading instead, but thats not possible in go.
Comment: "off-topic": the differential equation solved is the one describing the (simple) mars orbit. For the quick'n'dirty complete code see http://play.golang.org/p/GwehylBbLK
Answer: In order to be generic your Add method must take a Numeric parameter.  The normal way to deal with this is with a type assertion like this (on playground)
func (lhs *Vec6F) Add(_rhs Numeric) Numeric {
    result := new(Vec6F)
    rhs := _rhs.(*Vec6F) // type assertion - will panic if wrong type passes
    result.x = lhs.x + rhs.x
    result.y = lhs.y + rhs.y
    result.z = lhs.z + rhs.z
    result.vx = lhs.vx + rhs.vx
    result.vy = lhs.vy + rhs.vy
    result.vz = lhs.vz + rhs.vz
    return result
}

You could also use a type switch if you had different types you wanted to convert between.
Comment: Thx, this is probably the solution i'm going to end with, although I don't like type assertions. You convert to a pointer type instead of `_rhs.(Vec6F)` to safe a unneccessary copy, right?
Comment: It had to be a pointer type to make the type assertion work. Try changing it on the playground link above to see what I mean - you'll get the error "impossible type assertion: Vec6F does not implement Numeric (Add method requires pointer receiver)"
Answer: Indeed, generics are not supported in go.
If you want a type to implement an interface, the methods' prototypes need to match exactly: you would need func (lhs *Vec6F) Add(rhs Numeric) Numeric.
Here is an attempt to write this method using a type assertion:
func (lhs *Vec6F) Add(rhs Numeric) Numeric {
    vrhs := rhs.(*Vec6F)
    result := new(Vec6F)
    result.x = lhs.x + vrhs.x
    result.y = lhs.y + vrhs.y
    result.z = lhs.z + vrhs.z
    result.vx = lhs.vx + vrhs.vx
    result.vy = lhs.vy + vrhs.vy
    result.vz = lhs.vz + vrhs.vz
    return result
}

It compiles and should work when called with the right types of argument, however, I'd say it's an abuse.
Nothing stops you (except a runtime error) from using this method to add vectors to scalars since they would both implement Numeric. In the end, you would gain nothing from using the interface abstraction.
The go philosophy would dictate the use of type-specific methods/functions in this case.
Comment: What exactly do you mean by "use of type-specific methods/functions"? Can you give a example?
Comment: As in, you would not have a generic Add which works on Vec6F and other numeric like types. You'd have addVec6F, etc.
Answer: There are two problems that you're running into.
1.) The reason it does not compile, and complains about the interfaces not matching is because  Vec6F does not satisfy the function signature for rk5.Numeric.  Both return value, and input parameters must match type.
http://play.golang.org/p/kc9V9EXxJq fixes that problem but creates a new one...
2.) To make the method signatures match so Vec6F satisfies Numeric's signature it broke the ability to perform numeric operations on the property values.  This is because interfaces have only methods, no properties.
In your usecase, would it make sense for the Numeric interface to provide an accessor method which would return a matrix array that the receiver would then perform the Add|Sub|Multi on? This might complicate what needs to be done within each interface implementation's methods but I think would get you what you're looking for.
Comment: Because I needed the results (of the computation) about 2 hours ago, I had changed the code to use slices of float64 instead, which is somehow a radical version of providing such a accessor method. The complete code is at http://play.golang.org/p/GwehylBbLK -- It works, but it is far away from being nice code, in my opinion. The problem with the accessor method is the following: Suppose I had to use complex numbers. Or I would only want Integer values in another use case. Providing an accessor then becomes probably impossible, as I couldnt only operate on vectors/matrices but also on polynoms.


Utilizar ponteiro pode deixar o meu código mais rápido?

Question: Me disseram que se eu trabalhar utilizando ponteiros o programá sera mais rápido. Se em vez de usar índice para percorrer um vetor eu usar o ponteiro, fica melhor?
Comment: Olha, essa sua pergunta não é muito diferente de uma criança de 4 anos perguntando porque o céu é azul. Até é possível dar-se uma resposta que explique refração, difração e interação entre fótons e elétrons de átomos de nitrogênio e oxigênio do ar, mas essa criança não entenderia nada disso. Ponteiros servem para uma infinidade de coisas e podem ou não contribuir com o desempenho, mas para entender uma resposta detalhada dessa pergunta, vai bem longe.
Comment: Alguma das respostas resolveu sua dúvida? Acha que pode aceitar uma delas? Veja o [tour] como fazer isso, se ainda não o fez. Você ajudaria a comunidade identificando qual foi a melhor solução para você. Pode aceitar apenas uma delas. Mas pode votar em qualquer pergunta ou resposta que achar útil no site todo
Answer: Não, isso não faz sentido até porque o índice de um vetor é um ponteiro. Claro que pode ter alguma situação que você faz errado e pode dar diferença, mas é circunstancial. Veja: Arrays são ponteiros?. Em geral fica menos legível usar o ponteiro pode a notação de array pode ser usada.


Java Android Mesclando projetos

Question: As vezes eu preciso utilizar um projeto em outro como por exemplo um framework UI em minha aplicação ou coisa do tipo e a maioria deles estão disponíveis em repositórios como github etc, geralmente faço o download e extraio os arquivos para pasta do meu projeto mas logo o eclipse começa a alertar vários erros geralmente por dois motivos

O importe da classe R referente ao pacote esta errado ou seja ele
geralmente referencia ao pacote original do framework não ao do meu
projeto (Coisa Obvia rsrs)
A classe R não identifica os Resources e eles muitas vezes ficam
inacessíveis

Acredito que provavelmente estou incorporando de forma errada um projeto no outro gostaria de saber como eu posso fazer isso de forma simples, toda vez que decido usar algum Framework UI é uma gerra eu preciso corrigir todos esses erros na mão.
Comment: Poderia responder as seguintes perguntas? Está colocando os fontes da library direto no seu projeto (módulo)? Qual IDE esta usando (Eclipse, Android Studio ou outra)? Qual sistema de build (ant, gradle ou maven)? Poderia também incluir o link de uma dessas libraries?
Comment: Estou usando o Eclipse meu sistema de build é o padrão do eclipse, estou colocando os fontes direto no projeto, as classes e os arquivos xml de layout, um dos projetos que estou incluindo é este https://github.com/JakeWharton/ActionBarSherlock
Comment: Como não uso o Eclipse para desenvolvimento Android, não consigo gerar uma resposta satisfatória. Mas deixo minha contribuição: Sempre que fizer checkout de um repositório de uma library, tente criar um projeto Eclipse (módulo) separado para ele (tendo sua própria pasta `res` e seu próprio `AndroidManifest`), com isso você já evita problemas com referências a classe `R`, pois cada projeto tem uma. De uma olhada em http://www.simpligility.com/2010/07/multi-module-android-project-in-eclipse/. Mais...
Comment: O Eclipse usa o Ant para fazer Build e gerar o APK. Acho que é possível usar o Maven para gerenciar suas dependências, digo isso porque muitas libraries (e.g : https://github.com/ManuelPeinado/GlassActionBar) submetem módulos ao Maven Repository, usando Maven ou Gradle é muito fácil incluir em seu código (https://gist.github.com/wakim/42ee30ceb958a3f80110), assim evitando o problema de uso.
Comment: Quando for iniciar um novo projeto Android, de uma olhada no Android Studio, pode ser opinião pessoal mas nunca mais volto para o Eclipse depois que mudei, não tem comparação.
Comment: @Wakim na verdade eu também prefiro o Android Studio rs eu optei em usar o eclipse porque essas library estavam com o build do eclipse. Obrigado pelas dicas.
Answer: Adicione o projeto como módulo da sua aplicação principal (a que vai fazer o uso dos resources) e marque para ser compilada juntamente com o projeto.
Isso vai permitir você acessar os arquivos de classes do projeto incluído.
Para permitir o acesso aos resources é necessário também, adicionar a pasta do projeto incluído como módulo na solução do projeto principal.
Ficando então 2 pastas na sua IDE:
Minha Aplicacao:
Projeto Principal/
Projeto Incluido/

Certifique-se de que o projeto incluido esteja marcado como Library.
Todas essas opções você encontra na propriedades do seu projeto/solução.

Java Android Mesclando projetos


What is the term in theory/notation when you have notes played over a held note in the same hand?

Question: eg. Liebestraum no. 3, right hand, bars 1 and 2.

also Schubert Impromptu op. 90 no. 3
Lastly, any idea how this is achieved in Sibelius/Musescore?
Thanks
Comment: pedal notes? And why/how can the rests be played while the pedal's held on? Never understood that.
Comment: I wouldn't ca it "pedal" because that "C" belongs to both chords - Ab and C7.
Answer: You'll need different voices to notate these (see this MuseScore handbook page; Lilypond uses the same terminology).
I'm not sure this particular situation has a specific term. It looks like a melody-dominated homophony the right hand is doing a part of the accompanying, usually the job of the left hand.
Another well-known example is the first movement of Beethoven's Moonlight Sonata, which is described as follows:

A melody that Hector Berlioz called a "lamentation", mostly by the right hand, is played against an accompanying ostinato triplet rhythm, simultaneously played by the right hand.
Answer: Actually this is nothing else than an arpeggio.
You can notate it like simple 4 voices piano part. (s.below)
In German we call this Akkord-Zerlegung (that is translated in english chord analysis) but this is nothing else than a guitar accompaniment or by a harp. So I'd call it just an arpeggio with a sustained (bass) note.
You'll  have to notate the voices in different layers, but then you'll have to hide the rests in some voices to get a readable sheet product.
Try to notate it the 4 voices in 4 different channels and systems and then mix them together in one grand staff.
Edit:

any idea how this is achieved in Sibelius/Musescore?

Notate the in Sibelius 4 different voices:

or 2 voices in the treble clef and 2 voices in the bass clef:

and if you have all 4 voices in one staff you can separate them later:


MailChimp Api v1.3 how to set subscriber to pending

Question: anyone out there still knows if its possible to set the new subscriber status to pending with Mailchimp Api v1.3?  the documentation is disabled/deprecated.
the payload for a new subscriber actually is:
<code>$payload = array('email_address' => $this->email,
                'merge_vars' => $this->merge,
                'email_type' => $this->emailType,
                'double_optin' => $this->doubleOptin,
                'update_existing' => $this->updateExisting,
                'replace_interests' => $this->replaceInterests,
                'send_welcome' => $this->sendWelcome,);
</code>
i tried to just add
<code>"status" => "pending"
</code>
like with the Api v3, but this did not work.
i would like to check the docs if the naming was different back then but yeah...
thanks for reading by, help is much appreciated, have a nice one
Comment: Upgrading to API3.0 is not an option?
Comment: at least not right now, it would be the best solution but badly it has to happen later on in a different task
Answer: these is no solution to this. the only way was to actually upgrade to a package supporting MailChimp Api v3 (or doing the implementation yourself)
have a nice one.


Java - Eclipe IDE error - Error occurred during initialization of boot layer

Question: I am using Eclipse for the first time, I just finished installing it, I typed the code below as instructed by my online course:
System.out.println("Hello World");

and I got the error below :
Error occurred during initialization of boot layer
java.lang.module.FindException: Error reading module: C:\Users\seljouki\eclipse-workspace\MyFirstProject\bin
Caused by: java.lang.module.InvalidModuleDescriptorException: MyClass.class found in top-level directory (unnamed package not allowed in module)
Comment: Looks like you have a `module-info.java` making this a 'modular' project which doesn't match what your course wants. Delete the module-info.java to make the project a non-modular Java project.
Answer: Seems a "modul-info.java" related" topic.
Suggestion:

Restart Ecclipse and/or delete projects
Create a new project and when creating a new project do NOT select "module-info.java"
Create a package e.g. hellloworld (package.de.helloworld.chapter01)
In this package right click and create a java class (here HelloWorld)
Run this project as Java application

this should work.
You need also the main statement, you included this? :-)
package de.helloworld.chapter01;

public class HelloWorld {

    public static void main(String[] args) {
            System.out.println("Hello World");

    }

}

Answer: I had the same problem. I had class in default package. I deleted the class and moved it in to a new package. That fixed problem for me.
Answer: The following steps solved it for me;

Right-click on your project and select 'Properties' at the bottom.
Select 'Java Build Path' and navigate to the 'Libraries' tab. Remove
existing libraries.
Add a new library by clicking on 'Add Library' from the menu on the right.
Select 'JRE System Library' and click 'Next'.
Under 'System Library' select 'Execution Environment' and click
'Finish'. Apply all changes & close.
Run your program now.


How to sync configuration between multiple developers' environments

Question: D8 Configuration management is really awesome and easy to use when there's only one developer working on a project. We are running into challenges in keeping configuration synced between environments when more than one developer is introduced to a project at the same time.
Example:

Developer A is working on feature A. Exports configuration to their feature branch and pushes it to a shared develop branch.
At the same time, developer B is working on feature B and does the same thing - pushes feature configuration to the shared develop branch.

How do you import feature A and feature B concurrently?
Answer: Don't push to the develop branch directly. You should have a branch and merge strategy. If using GitHub or GitLab or similar, you would do a pull request of your branch to develop.
A common strategy (or one of) is the Git Flow workflow. Some links to explain Git Flow:

https://nvie.com/posts/a-successful-git-branching-model/
https://www.atlassian.com/git/tutorials/comparing-workflows/gitflow-workflow

There are a handful of strategies, use whatever will fit for your team.
One of the few circumstances I ran into with merge conflicts was if someone was working on something touching the same configuration areas as another person.. we avoided this by just coordinating the work well.
Comment: Ok - good to know. We use bitbucket but are not taking advantage of Git Flow. That looks to be a great strategy. Thanks Kevin
Comment: Oh, i see. So within a pull request, ONLY the configuration files the developer has modified get merged in?
Comment: Yes, at a high level its a merge of the changes. Check the GitHub link I added. I don't know if you are using GitHub or whatever service or just raw Git, either way, don't push directly to a mainline branch in a multi person team. You will have conflicts and issues every step of the way.


Current time of other cities

Question: Is it possible to get current time of other cities from code?(for example current time of Paris)
Answer: Here is how to get it:
<code>[NSTimeZone setDefaultTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"CEST"]];
NSLog(@"Paris time: %@", [[NSDate date] descriptionWithLocale:nil ]);
</code>
Comment: and NSTimeZone supports 48 out of those 250 abbreviations.
Comment: A list of timezone abbreviations is available here: http://www.timeanddate.com/library/abbreviations/timezones/
Answer: Look at NSTimeZone.

Current time of other cities


The greatest lower bound of $\{\{1,3,4\},\{2,3,4\}\}$

Question:
I have definition:

I think the answer is $\{3;4\}$. It's  a correct?
Comment: @coffeemath: Of course it is a poset. _Every_ set of sets ordered by $\subseteq$ makes a poset.
Comment: @HenningMakholm You're right! Deleting comment.
Answer: Yes, your answer is indeed correct.


convergence of Cauchy sequences defined recursively

Question: $X=(x_n)$ defined as $X_1=1,X_2=2$ and $X_n=\dfrac12\left(X_{n-2}+X_{n-1}\right)$.
To finds its limit, first we should prove that it is convergent, but my book has not given its solution. Instead, it just states that it is bounded between $1$ and $2$, i.e., $1< X_n < 2$ and guides to do it myself. It also states that $X_n$ is not monotone.
After some calculations, we find that mod of $X_n - X_{n-1}=\frac{1}{2^{n-1}}$.
Please suggest how to proceed in showing that its Cauchy hence also convergent
thanks in advance!
Comment: Better than the modulus, after some calculation, we find that $X_n-X_{n-1} = (-2)^{-(n-2)}.$ And since we can sum differences up to get an exact value of $X_n,$ there's really no need to prove it's a Cauchy sequence separately.
Answer: $\sum _{n=1}^{\infty} |X_n-X_{n-1}| <\infty$ implies that $\{X_n\}$ is Cauchy. To see this take $k>m$ and note  that  $|X_k-X_{m-1}|=|\sum _{n=m}^{k} (X_n-X_{n-1})| \leq\sum _{n=m}^{k} |X_n-X_{n-1}| $. This last quantity tends to $0$ because teh series $\sum _{n=1}^{\infty} |X_n-X_{n-1}|$ is convergent. [ In fact $\sum _{n=m}^{k} |X_n-X_{n-1}|=S_k-S_{m-1}$ where $S_n$ is the n-th partial sum of the series; if $S_n \to s$ then $S_k-S_{m-1} \to s-s=0$ as $k>m \to \infty$]. We have proved that  $\{X_n\}$ is Cauchy.


Set ENV variable in container is not working, is every under "/usr/local/bin" executed on container run?

Question: I have the following piece of definition in a Dockerfile:
# This aims to be the default value if -e is not present on the run command
ENV HOST_IP=127.0.0.1
...
COPY /container-files/etc/php.d/zz-php.ini /etc/php5/mods-available/zz-php.ini
RUN ln -s /etc/php5/mods-available/zz-php.ini /etc/php5/apache2/conf.d/zz-php.ini
COPY /container-files/init-scripts/setup_xdebug_ip.sh /usr/local/bin/setup_xdebug_ip.sh
RUN chmod +x /usr/local/bin/setup_xdebug_ip.sh
CMD ["/usr/local/bin/setup_xdebug_ip.sh", "/usr/local/bin/setup_php_settings.sh"]

This is the relevant piece of definition at zz-php.ini:
; Xdebug
[Xdebug]
xdebug.remote_enable=true
xdebug.remote_host="192.168.3.1"  => this should be overwrited by HOST_IP
xdebug.remote_port="9001"
xdebug.idekey="XDEBUG_PHPSTORM"

This is the content of the script setup_xdebug_ip.sh:
#!/usr/bin/bash

sed -i -E "s/xdebug.remote_host.*/xdebug.remote_host=$HOST_IP/" /etc/php5/apache2/conf.d/zz-php.ini

Updated the script
I have updated the script to see it that's the reason why the value isn't changed and still not working. See the code below:
#!/usr/bin/bash

sed -ri "s/^xdebug.remote_host\s*=.*$//g" /etc/php5/apache2/conf.d/zz-php.ini
echo "xdebug.remote_host = $HOST_IP" >> /etc/php5/apache2/conf.d/zz-php.ini

In order to build the image and run the container I follow this steps:

Build the image:
docker build -t reynierpm/dev-php55 .

Run the container:
docker run -e HOST_IP=$(hostname -I | cut -d' ' -f1)
           --name dev-php5
           -it /bin/bash reynierpm/dev-php55

After the image gets built and the container is running I open a browser and point to: http://container_address/index.php (which contains phpinfo()) and I can see the value of xdebug.remote_host as 192.168.3.1 ...
why? What is not running when the container start? Why the value doesn't get overwritten using the provided value by -e on the run command?
UPDATE:
I've notice that I am only copying the file and setting up the permissions but I am not running it at all:
# Copy the script for change the xdebug.remote_host value based on HOST_IP
COPY /container-files/init-scripts/setup_xdebug_ip.sh /usr/local/bin/setup_xdebug_ip.sh

# Execute the script
RUN chmod +x /usr/local/bin/setup_xdebug_ip.sh

Could this be the issue? Everything that I put under /usr/local/bin is executed at container start? If not that's definitively the issue or at least I think.
UPDATE #2:
After the suggestions from @charles-dufly I've fixed a few things but still not working.
Now the Dockerfile looks like:
# This aims to be the default value if -e is not present on the run command
ENV HOST_IP=127.0.0.1
...
ADD container-files /
RUN chmod +x /usr/local/bin/setup_xdebug_ip && \
/usr/local/bin/setup_xdebug_ip && \
chmod +x /usr/local/bin/setup_php_settings && \
ln -s /etc/php5/mods-available/zz-php.ini /etc/php5/apache2/conf.d/zz-php.ini && \
ln -s /etc/php5/mods-available/zz-php-directories.ini /etc/php5/apache2/conf.d/zz-php-directories.ini && \
a2enmod rewrite

EXPOSE 80 9001

CMD ["/usr/local/bin/setup_php_settings"]

After build the image I am running the following command:
$ docker run -e HOST_IP=192.168.3.120 -p 80:80 --name php55-img-6 -it reynierpm/php5-dev-4 /bin/bash

I can see the value of xdebug.remote_host being set as 127.0.0.1 but is not taking the value passed as -e on the run command, why?
Comment: Things in `/usr/local/bin` *never were* automatically executed. Not on any Linux distribution ever, since [according to the Filesystem Hierarchy Standard](https://en.wikipedia.org/wiki/Filesystem_Hierarchy_Standard), `/usr/local/bin` is a place for local additions equivalent to `/usr/bin`, and nobody would ever automatically execute everything under `/usr/bin`.
Comment: Well, I'm not a Docker expert, but if you're expecting the `RUN chmod ...` line to execute the script, I'm pretty sure it's not going to do that. That looks like it will only set the permissions. Trying adding another line, `RUN /usr/local/bin/setup_xdebug_ip.sh` at the end.
Comment: @CharlesDuffy that makes sense and it's what I was concerned about, I will try to add a `CMD` or `RUN` command and will come back when I have something to say it works or it doesn't
Answer: You're correct in that items under /usr/local/bin are not automatically executed.
The Filesystem Hierarchy Standard specifies /usr/local as a "tertiary hierarchy" with its own bin, lib, &c. subdirectories, equivalent in their intent and use to the like-named directories under / or /usr but for content installed local to the machine (in practice, this means software installed without the benefit of the local distro's packaging system).
If you want a command to be executed, you need a RUN that directly or indirectly invokes it.

As for the other matters discussed as this question has morphed, consider the following:
FROM alpine
ENV foo=bar
RUN echo $foo >/tmp/foo-value
CMD cat /tmp/foo-value; echo $foo

When invoked with:
docker run -e foo=qux

...this emits as output:
bar
qux

...because bar is the environment variable laid down by the RUN command, whereas qux is the environment variable as it exists at the CMD command's execution.
Thus, to ensure that an environment variable is honored in configuration, it must be read and applied during the CMD's execution, not during a prior RUN stage.
Comment: By the way -- having a bounty gets folks a significant bit of leeway around normal site rules, but under usual circumstances "chameleon questions" (that change from the original question asked into new problems encountered after that first issue is fixed) are rather heavily frowned on.
Comment: Move the update you want to be impacted by the environment variable set at runtime into your `setup_php_settings` script. Your `RUN`s aren't re-executed every invocation, whereas `CMD` contents are.
Comment: Ok, take a look to the update I've made to the OP (the last lines at first code sample where is the `CMD`), it's suppose that the command will run the files, right? well the result is the same as in the OP, the value is not being set properly
Comment: Your current command doesn't make sense. Passing `"/usr/local/bin/setup_php_settings.sh"` as an argument to `"/usr/local/bin/setup_xdebug_ip.sh"` isn't going to execute the former, since the latter doesn't ever look at its argument, much less try to execute that argument as a command.
Comment: Use a `RUN`, not a `CMD` array entry, for additional scripts to run as prerequisites. And consider using `set -x` (as via making your shebang `#!/usr/bin/env bash -x`) to log what your scripts are actually doing.
Comment: Can you add an example of this latest comment on your answer? Sorry I am new to Docker and I am still learning
Comment: Not a Docker suggestion, a bash suggestion. Edit your `setup_php_settings.sh` to change the first line from `#!/usr/bin/bash` to `#!/usr/bin/env bash -x`, and the commands run will be logged to stderr, so you can read those logs and see what's actually being run in practice, and (1) ensure that the script really is run, and (2) compare it to what you expect.
Comment: @ReynierPM, ...and the other part, which *is* a Docker suggestion, is to have a `RUN /usr/local/bin/setup_xdebug_ip.sh` followed by a `CMD /usr/local/bin/setup_php_settings.sh` (assuming that your `setup_php_settings.sh` actually exec's the service process at the end; if it doesn't, you need to fix it to actually do that).
Comment: Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/124229/discussion-between-reynierpm-and-charles-duffy).
Comment: Can you take a look at the **UPDATE #2** on OP? I am still doing something wrong and I can't find what is it
Comment: Still not working, even if I pass the ENV var as `-e HOST_IP=xxx.yyy.zzz.ttt` I am still seing the `xdebug.remote_host` being set as localhost and I already moved the code to the script on the CMD, what  else could be wrong here? Thanks for the advise around the "topic change" won't happen again
Comment: Interesting. I'd want to repro -- if you run `env` in the CMD-launched script to dump environment variables, which value does it show?
Comment: I took the time to reproduce, and the behavior I'm getting is in line with what I stated earlier: Your CMD or ENTRYPOINT gets environment updates passed on the `docker run` command line, whereas prior RUN stages using ENV values set from the Dockerfile are not reexecuted. If the behavior you're seeing is contrary to that, please post a reproducer complete enough that someone else can run it and validate identical behavior.
Comment: Maybe will be better if you take a look to the repo [here](https://github.com/reypm/php55-dev) if you want we can cleanup the post and start from the original issue but take a look to the repo, those are the latest files
Answer: Multiple problems with your repo:
First of all when using CMD in docker file, the command added after the image name in the docker run : /bin/bash  will override the CMD ["/usr/local/bin/setup_php_settings"] from your Dockerfile.
Thus your setup_php_settings is never executed!
You should use ENTRYPOINT i.s.o. CMD in your Dockerfile. I found good explanation  here and here.
In conclusion for the Dockerfile change the CMD [...] line in:
ENTRYPOINT bash -C '/usr/local/bin/setup_php_settings';'bash'

then you can run your container with:
docker run -it -e HOST_IP=<your_ip_address> -e PHP_ERROR_REPORTING='E_ALL & ~E_STRICT' -p 80:80 --name dev-php5 mmi/dev-php55

No need to add /bin/bash at the end. Check-out test-repo for test-setup.
Secondly, in your /usr/local/bin/setup_php_settings, you should add
a2enmod rewrite
service apache2 restart

at the end, just before
source /etc/apache2/envvars && exec /usr/sbin/apache2 -DFOREGROUND`

this in order for your new settings to be applied in your web app.
Comment: This works like a charm, many thanks for taking the time and check those errors and make suggestions
Comment: One question, be inside the container and exit from there cause the container to end, how do I keep it running even if I exit from the bash?
Comment: Then you would have to start it with -d, rest can be same, and connect to container, check out my readme.md on my test-repo
Comment: I've started using `-d` and yes it goes to background and it keeps running, then I can attach to the container but again as soon as I type `exit` inside the container it stops the execution, how do I keep it running even after?
Comment: See http://stackoverflow.com/questions/19688314/how-do-you-attach-and-detach-from-dockers-process
Comment: I have upvoted :) and that works: `docker exec -it  ` does the job, that's what I was looking for
Comment: as this answer is the answer to your question "This works like a charm", why is another answer that did not solve the question is being accepted and rewarded with a bonus?
Comment: you're right, I accepted yours but I can not give you the bounty since it was assigned to the other user, that was my bad, apologies


Como me livro desses warnings

Question: Estou fazendo um programa que caça uma palavra dentre de uma matriz. Para isso fiz 8 funções que varrem em todas as regiões, como preciso devolver na saída as coordenadas da primeira e da última letra.
Por exemplo, preciso encontrar a palavra "casa" na matriz, o programa devolve as coordenadas da letra 'c' e da letra 'a' (última letra), como as entradas eu tenho e preciso de dois valores na saída.
Usei ponteiros como parâmetros, só que está dando muito warning. Ainda falta para terminar o código completo.
#include<stdio.h>
#include<string.h>
#include<stdlib.h>

int Norte (char cacapalavra[][100], char palavra[], int *pc, int *pl) {
    int i, j, n, k;
    j = *pc; k = 0;
    n = strlen(palavra);
    for (i = *pl; i < i+n; i++) {
            if (cacapalavra [i][j] != palavra[k]) return -1;
            else k++;
    }
    *pl = i;
}

int Sul (char cacapalavra[][100], char palavra[], int *pc, int *pl) {
    int i, j, n, k;
    j = *pc; k = 0;
    n = strlen(palavra);

    for (i = *pl; i < i+n; i++) {
            if (cacapalavra [i][j] != palavra[k]) return -1;
            else k++;
    }
    *pl = i;
}

int Leste (char cacapalavra[][100], char palavra[], int *pc, int *pl) {
    int i, j, n, k;
    i = *pl; k = 0;
    n = strlen(palavra);

    for (j = *pc; j < j+n; j++) {
            if (cacapalavra [i][j] != palavra[k]) return -1;
            else k++;
    }
    *pc = j;
}

int Oeste (char cacapalavra[][100], char palavra[], int *pc, int *pl) {
    int i, j, n, k;
    i = *pl; k = 0;
    n = strlen(palavra);

    for (j = *pc; j < j+n; j--) {
            if (cacapalavra [i][j] != palavra[k]) return -1;
            else k++;
    }
    *pc = j;
}

int Nordeste (char cacapalavra[][100], char palavra[], int *pc, int *pl) {
     int i, j, n, k;
     k = 0;
     n = strlen(palavra);

     for (i = *pl, j = *pc; i < i+n; j++, i--) {
            if (cacapalavra [i][j] != palavra[k]) return -1;
            else k++;
     }
     *pl = i; *pc = j;
}

int Noroeste (char cacapalavra[][100], char palavra[], int *pc, int *pl) {
     int i, j, n, k;
     k = 0;
     n = strlen(palavra);

     for (i = *pl, j = *pc; i < i+n; j--, i--) {
            if (cacapalavra [i][j] != palavra[k]) return -1;
            else k++;
     }
     *pl = i; *pc = j;
}

int Sudeste (char cacapalavra[][100], char palavra[], int *pc, int *pl) {
     int i, j, n, k;
     k = 0;
     n = strlen(palavra);

     for (i = *pl, j = *pc; i < i+n; j--, i++) {
             if (cacapalavra [i][j] != palavra[k]) return -1;
             else k++;
     }
     *pl = i; *pc = j;
}

int Sudoeste (char cacapalavra[][100], char palavra[], int *pc, int *pl) {
     int i, j, n, k;
     k = 0;
     n = strlen(palavra);

     for (i = *pl, j = *pc; i < i+n; j++, i++) {
             if (cacapalavra [i][j] != palavra[k]) return -1;
             else k++;
     }
     *pl = i; *pc = j;
}

int main () {

    char cacapalavra [100][100];
    char palavra [100];
    int i, j, k, n, *pc, *pl, aux;
    k = 0;

    scanf ("%d", &n);

    for (i = 0; i < n; i++)
          for (j = 0; j < n; j++)
                scanf ("%c", &cacapalavra[i][j]);

    scanf ("%s", palavra);

    for (i = 0; i < n; i++) {
          for (j = 0; j < n; j++) {
                if (palavra[k] == cacapalavra[i][j]) {
                *pc = j; *pl = i;
                aux = Norte(cacapalavra, palavra, &pc, &pl);
                aux = Sul(cacapalavra, palavra, &pc, &pl);
                aux = Leste(cacapalavra, palavra, &pc, &pl);
                aux = Oeste(cacapalavra, palavra, &pc, &pl);
                aux = Nordeste(cacapalavra, palavra, &pc, &pl);
                aux = Noroeste(cacapalavra, palavra, &pc, &pl);
                aux = Sudeste(cacapalavra, palavra, &pc, &pl);
                aux = Sudoeste(cacapalavra, palavra, &pc, &pl);
                }
          }
    }
}

Warnings:

||=== Build file: "no target" in "no project" (compiler: unknown) ===|
C:\Users\mdesousa\Documents\cacapalavra.c||In function 'main':|
C:\Users\mdesousa\Documents\cacapalavra.c|120|warning: passing argument 3 of 'Norte' from incompatible pointer type|
C:\Users\mdesousa\Documents\cacapalavra.c|5|note: expected 'int *' but argument is of type 'int **'|
C:\Users\mdesousa\Documents\cacapalavra.c|120|warning: passing argument 4 of 'Norte' from incompatible pointer type|
C:\Users\mdesousa\Documents\cacapalavra.c|5|note: expected 'int *' but argument is of type 'int **'|
C:\Users\mdesousa\Documents\cacapalavra.c|121|warning: passing argument 3 of 'Sul' from incompatible pointer type|
C:\Users\mdesousa\Documents\cacapalavra.c|17|note: expected 'int *' but argument is of type 'int **'|
C:\Users\mdesousa\Documents\cacapalavra.c|121|warning: passing argument 4 of 'Sul' from incompatible pointer type|
C:\Users\mdesousa\Documents\cacapalavra.c|17|note: expected 'int *' but argument is of type 'int **'|
C:\Users\mdesousa\Documents\cacapalavra.c|122|warning: passing argument 3 of 'Leste' from incompatible pointer type|
C:\Users\mdesousa\Documents\cacapalavra.c|29|note: expected 'int *' but argument is of type 'int **'|
C:\Users\mdesousa\Documents\cacapalavra.c|122|warning: passing argument 4 of 'Leste' from incompatible pointer type|
C:\Users\mdesousa\Documents\cacapalavra.c|29|note: expected 'int *' but argument is of type 'int **'|
C:\Users\mdesousa\Documents\cacapalavra.c|123|warning: passing argument 3 of 'Oeste' from incompatible pointer type|
C:\Users\mdesousa\Documents\cacapalavra.c|41|note: expected 'int *' but argument is of type 'int **'|
C:\Users\mdesousa\Documents\cacapalavra.c|123|warning: passing argument 4 of 'Oeste' from incompatible pointer type|
C:\Users\mdesousa\Documents\cacapalavra.c|41|note: expected 'int *' but argument is of type 'int **'|
C:\Users\mdesousa\Documents\cacapalavra.c|124|warning: passing argument 3 of 'Nordeste' from incompatible pointer type|
C:\Users\mdesousa\Documents\cacapalavra.c|53|note: expected 'int *' but argument is of type 'int **'|
C:\Users\mdesousa\Documents\cacapalavra.c|124|warning: passing argument 4 of 'Nordeste' from incompatible pointer type|
C:\Users\mdesousa\Documents\cacapalavra.c|53|note: expected 'int *' but argument is of type 'int **'|
C:\Users\mdesousa\Documents\cacapalavra.c|125|warning: passing argument 3 of 'Noroeste' from incompatible pointer type|
C:\Users\mdesousa\Documents\cacapalavra.c|65|note: expected 'int *' but argument is of type 'int **'|
C:\Users\mdesousa\Documents\cacapalavra.c|125|warning: passing argument 4 of 'Noroeste' from incompatible pointer type|
C:\Users\mdesousa\Documents\cacapalavra.c|65|note: expected 'int *' but argument is of type 'int **'|
C:\Users\mdesousa\Documents\cacapalavra.c|126|warning: passing argument 3 of 'Sudeste' from incompatible pointer type|
C:\Users\mdesousa\Documents\cacapalavra.c|77|note: expected 'int *' but argument is of type 'int **'|
C:\Users\mdesousa\Documents\cacapalavra.c|126|warning: passing argument 4 of 'Sudeste' from incompatible pointer type|
C:\Users\mdesousa\Documents\cacapalavra.c|77|note: expected 'int *' but argument is of type 'int **'|
C:\Users\mdesousa\Documents\cacapalavra.c|127|warning: passing argument 3 of 'Sudoeste' from incompatible pointer type|
C:\Users\mdesousa\Documents\cacapalavra.c|89|note: expected 'int *' but argument is of type 'int **'|
C:\Users\mdesousa\Documents\cacapalavra.c|127|warning: passing argument 4 of 'Sudoeste' from incompatible pointer type|
C:\Users\mdesousa\Documents\cacapalavra.c|89|note: expected 'int *' but argument is of type 'int **'|
||=== Build finished: 0 error(s), 16 warning(s) (0 minute(s), 0 second(s)) ===|

Comment: Esse é apenas um problema, esse você resolve passando as variáveis sem `&`. Falo disso em http://pt.stackoverflow.com/q/125793/101 Parte do problema é o código estar desorganizado, algumas coisas não são fáceis de enxergar.
Comment: Quais *warnings*? Onde?
Comment: No final "warning: passing argument 3 of 'Norte' from incompatible pointer type|", sei que é a passagem do ponteiro, mas não sei como tirar. Tô rodando no codeblocks
Comment: A edição tinha escondido eles. Tem muito erro nesse código, vai ser dicífil achar todos. E o pior, que mesmo que compile, eu não vou confiar nele nunca sem fazer uma avaliação profunda. Tem coisa que eu nem sei como consertar, teria que entender o que o código todo faz para resolver. Um exemplo é que as função não retornam nada em determinadas situações. Tem que retornar, mas o que?
Comment: Pelo que entendi o warnings são da passagem do ponteiro para função, todas as função são muito parecidas.
Comment: A resposta resolveu o seu problema? Acha que pode aceitá-la? Se não souber como faz, veja o [tour]. Isso ajudaria muito indicar que a solução foi útil para você e dar uma indicação que houve uma solução satisfatória. Também pode votar em qualquer pergunta ou resposta que achar útil no site todo.
Comment: O erro está na hora de passar os parâmetros, por exemplo para o "Norte". Essa variável já é um ponteiro para "int", logo, você não pode colocar o "&" em pc na frente, senão você estará interpretando o ponteiro como um ponteiro do ponteiro.
Comment: Experimente declarar assim: int **pc, se deseja ponteiro do ponteiro
Answer: Arrumei as variáveis que estavam sendo enviadas com & e já são ponteiros. Coloquei retornos na funções (chutei um valor só para acabar com warning), fiz uso da variável aux e atribuí valores para as variáveis pc e pl. Duvido que faça o que deve, mas resolvi o problema descrito na pergunta, se a pergunta tiver mais detalhes eu melhoro. O código pode ser bastante melhorado.
#include<stdio.h>
#include<string.h>

int Norte(char cacapalavra[][100], char palavra[], int *pc, int *pl) {
    int i, j, n, k;
    j = *pc; k = 0;
    n = strlen(palavra);
    for (i = *pl; i < i + n; i++) {
        if (cacapalavra[i][j] != palavra[k]) return -1;
        else k++;
    }
    *pl = i;
    return 0;
}

int Sul(char cacapalavra[][100], char palavra[], int *pc, int *pl) {
    int i, j, n, k;
    j = *pc; k = 0;
    n = strlen(palavra);
    for (i = *pl; i < i + n; i++) {
        if (cacapalavra[i][j] != palavra[k]) return -1;
        else k++;
    }
    *pl = i;
    return 0;
}

int Leste(char cacapalavra[][100], char palavra[], int *pc, int *pl) {
    int i, j, n, k;
    i = *pl; k = 0;
    n = strlen(palavra);
    for (j = *pc; j < j + n; j++) {
        if (cacapalavra[i][j] != palavra[k]) return -1;
        else k++;
    }
    *pc = j;
    return 0;
}

int Oeste(char cacapalavra[][100], char palavra[], int *pc, int *pl) {
    int i, j, n, k;
    i = *pl; k = 0;
    n = strlen(palavra);
    for (j = *pc; j < j + n; j--) {
        if (cacapalavra[i][j] != palavra[k]) return -1;
        else k++;
    }
    *pc = j;
    return 0;
}

int Nordeste(char cacapalavra[][100], char palavra[], int *pc, int *pl) {
    int i, j, n, k;
    k = 0;
    n = strlen(palavra);
    for (i = *pl, j = *pc; i < i + n; j++, i--) {
        if (cacapalavra[i][j] != palavra[k]) return -1;
        else k++;
     }
     *pl = i; *pc = j;
     return 0;
}

int Noroeste(char cacapalavra[][100], char palavra[], int *pc, int *pl) {
     int i, j, n, k;
     k = 0;
     n = strlen(palavra);
     for (i = *pl, j = *pc; i < i + n; j--, i--) {
        if (cacapalavra[i][j] != palavra[k]) return -1;
        else k++;
     }
     *pl = i; *pc = j;
     return 0;
}

int Sudeste(char cacapalavra[][100], char palavra[], int *pc, int *pl) {
    int i, j, n, k;
    k = 0;
    n = strlen(palavra);
    for (i = *pl, j = *pc; i < i + n; j--, i++) {
        if (cacapalavra[i][j] != palavra[k]) return -1;
        else k++;
    }
    *pl = i; *pc = j;
    return 0;
}

int Sudoeste(char cacapalavra[][100], char palavra[], int *pc, int *pl) {
    int i, j, n, k;
    k = 0;
    n = strlen(palavra);
    for (i = *pl, j = *pc; i < i + n; j++, i++) {
        if (cacapalavra[i][j] != palavra[k]) return -1;
        else k++;
    }
    *pl = i; *pc = j;
    return 0;
}

int main () {
    char cacapalavra [100][100];
    char palavra [100];
    int k = 0, n, *pc = 0, *pl = 0, aux;
    scanf ("%d", &n);
    for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) scanf("%c", &cacapalavra[i][j]);
    scanf ("%s", palavra);
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < n; j++) {
            if (palavra[k] == cacapalavra[i][j]) {
                *pc = j; *pl = i;
                aux = Norte(cacapalavra, palavra, pc, pl);
                aux = Sul(cacapalavra, palavra, pc, pl);
                aux = Leste(cacapalavra, palavra, pc, pl);
                aux = Oeste(cacapalavra, palavra, pc, pl);
                aux = Nordeste(cacapalavra, palavra, pc, pl);
                aux = Noroeste(cacapalavra, palavra, pc, pl);
                aux = Sudeste(cacapalavra, palavra, pc, pl);
                aux = Sudoeste(cacapalavra, palavra, pc, pl);
                printf("%d", aux); //só para eliminar o warning que não foi usada.
            }
        }
    }
}

Veja funcionando no ideone. E no repl.it. Também coloquei no GitHub para referência futura.
Comment: Gostei do "Veja compilando no ideone", haha.
Comment: O problema é a atribuição do ponteiro. No início declara-se que `int *pc = 0`, ou seja, ele é `NULL` e logo em seguida faz `*pc = j`, ou seja, está de-referenciando um ponteiro que é NULL. Deve estar cheio de erro o programa, mas esse é muito óbvio para deixar passar. A solução correta seria eliminar o ponteiro e passar o endereço da variável para a função;
Comment: Como eu disse, resolvi só o problema do *warning* conforme ele pediu, alertei que o código ainda está cheio de erros, não é só esse. A intenção não é fazer tudo para ele, mas resolver o que ele pediu. Tanto que nem coloquei que o código está funcionando, só que está compilando. Se ele quiser outras ajudas ele pode abrir outras perguntas. O foco desta é o *warning*. Eu não introduzi o erro, eu apenas não corrigi.
Comment: O int *pc = 0 entendi. Na segunda parte não entendi, preciso que o endereço na posição da matriz seja atualiza, por isso coloquei *pc = j. O que me tá mais me deixando em duvida são estes warning, quanto aos outros erros não tem problema, acredito que possa arruma-los sem maiores problemas.
Comment: Gostaria de saber o que tem de errado no código para receber negativo. Eu sei que ele não está perfeito, eu disse isso. Mas eu resolvi os problemas colocados na pergunta. Só o negativo não vai ajudar ninguém saber o que tem de errado.

Como me livro desses warnings


Can I put the 'query' part of a =QUERY in a cell?

Question: I am playing with Google Spreadsheet's =QUERY(), and I was wondering if / how I can put the query part in a cell. For, for example, I have
=QUERY(dataset, B1, 1)

in cell A1, and
SELECT *

in cell B1.
When I try it, I get a #REF! error in cell A1. If I change the query string though, I get a #VALUE error, so it does do something, but not what I expect.
Comment: share a copy of your sheet
Answer: perhaps try:
=QUERY(dataset; B1; 1)


Suppose that J and K are subgroups of G and that x; y are in G. Show that if Jx = Ky, then J = K.

Question: Suppose that $J$ and $K$ are subgroups of $G$ and that $x,y \in G$. Show that if $Jx = Ky$, then $J = K$.
I'm struggling with this question for the case that $x \neq y$
Comment: I can see that if Jx=Ky then |J|=|K|.  x is in Jx and y is in Jx, x is in Ky and y is in Ky and Jx=Jy Kx=Ky. Am I going in the right direction?
Answer: $Jx=Ky\implies J=Kyx^{-1}$ let say $r=yx^{-1}$ Thus,$Kr$ is a group which is a right coset of $K$, which is only possible when $Kr=K\implies K=J$
Comment: @GitGud It just depends how you parse it. Which is why we tell first years to use brackets...(Also, there was a sign on the the toilet door beside my office in the department where I did my PhD which read "Toilets for the use of female staff and postgraduate students only". I never quite worked up the courage to either add brackets or use the toilet...)
Comment: I suppose you want to say 'which only possible when $Kr=K$, thus $K=J$'.
Comment: @GitGud :yes exactly.
Comment: But what you're saying is 'which is only possible when $K=J$ is a consequence of $Kr=K$'.
Comment: @GitGud: My english is not perfect,let me clarify What I mean.
After we see that $Kr$ is a group,we must require that $Kr=K$ which means that $K=J$
Comment: @user1729 A similar thing happened at my school. 'Toilet for teaching personnel and non-teaching personnel only'. In any case mathematics should always be read all at once, meaning that it should be bracketed as $[Kr=K\implies K=J]$.