Why does the shopping cart display the login form?

Question: When I'm not logged in and click on the cart logo, the following page appears with the login form:
<code>/cart
</code>
1) I want the contents of the shopping cart to be displayed.
2) When I click on the "Checkout" button I want to display the login form.
How to do this ?
Why does the shopping cart display the login form ?
Answer: There are a a few ways.
1) Set permission to access cart to logged in users only
2) On site information page, set 403 to user/login
There should be a module for this. As soon as I find it, I will update my answer.
Comment: This feature is already installed on my site. Why the anonymous user can not view the contents of the shopping cart?
Comment: You didn't mention that. Did the user added any item to shopping cart? Be specific about your query
Comment: Yes it has an item in the shopping cart, even without item, it should have a message "Your shopping cart is empty". Here is one of my products https://www.s1biose.com/produit/savon-artisanal-bio-la-cannelle
Comment: You need to check permissions. Also, make sure visitors can buy from the site.
Comment: I added the screenshots of my configuration to my question
Comment: Have a look at this: http://bit.ly/DrupalTR
Comment: Make sure, there are no other modules/permissions are overriding the cart access configurations/permissions
Comment: On the link I shared, there is a add to cart button. Give it a try.
Comment: I checked the permissions and it is correctly configured. I use this module https://www.drupal.org/project/commerce_marketplace
Comment: I checked with your website and I guess, it is the cart permissions that you have to check with. Make sure users have 'Access Checkout' permissions:

Check the screen shot I attached in the original answer.
Comment: Yes, there is a screenshot in my question
Comment: Yes, I had a look at it and posted one from mine to confirm the configuration. I guess, there are some other modules/permissions overriding cart permissions.


Validate models with Backbone.js

Question: with help of books and tutorials im trying to do my own Todo list app. My problem is that when you add ah todo my model should validate if the input come with some text before rendering. i created the validate methis but it doesnt work and i dont know how to track the error, i'll appreciate if you guys could help me finding my error
Model:
var Task = Backbone.Model.extend({
    validate: function(attrs){
        if(!attrs.title){
            return "The task has no title";
        }
    }
});

var task = new Task;

Collection:
var Tasks = Backbone.Collection.extend({
    model: Task
});

var tasks = new Tasks([
    {
        title: 'my task'
    },
    {
        title: 'my task 1'
    },
    {
        title: 'my task 2'
    },
    {
        title: 'my task 3'
    }
]);

Views:
var TaskView = Backbone.View.extend({
    tagName: "li",

    template: _.template( $('#task').html() ),

    initialize: function(){
        this.model.on("change", this.render, this);
    },

    render: function(){
        var template = this.template( this.model.toJSON() );

        this.$el.html( template );

        return this;
    },

    events: {
        'click .icon-checkbox': 'toggleState'
    },

    toggleState: function(e){
        var $checkbox = $(e.target);

        $checkbox.toggleClass('icon-checkbox-unchecked');

    }
});

var TasksView = Backbone.View.extend({
    el: '#tasks',

    initialize: function(){
        this.render();
        this.collection.on('add', this.addOne, this);
    },

    render: function(){
        this.collection.each(this.addOne, this);

        return this;

    },

    addOne: function(task){
        var taskView = new TaskView({ model: task });
        this.$el.append( taskView.render().el );
    }
});

var AddTask = Backbone.View.extend({
    el: '#todos',

    events:{
        'click #add': 'addTask'
    },

    addTask: function(){
        var taskTitle = $('#inputTask').val();
        $('#inputTask').val("");
        var task = new Task( {title: taskTitle} ); // create the task model
        this.collection.add(task); //add the model to the collection
    }
});

var tasksView = new TasksView( {collection: tasks} );
var addTask = new AddTask( {collection: tasks} );

Edit:
I just realized that the validate methos its on ly called when you set or save info in the model, but actually what i want to do is check when the user submit a todo that if it comes with text or ini order to create and render the model.
Answer: You never actually call the validate() method.  Have you looked into the Backbone Validation plugin?  Works pretty slick.
https://github.com/thedersen/backbone.validation
Comment: I just realized that the validate methos its on ly called when you set or save info in the model, but actually what i want to do is check when the user submit a todo that if it comes with text or ini order to create and render the model.
Answer: So i came up with this solution, I am not sure if this is a good practice or not or it the view should to this but what i did is: Once you push on the add task button the addTask methos first check if the input has text or not, if it doesnt have text it just only change the placeholder to: "Todo's can not be empty" and doesnt create a model and render its view. But, if the input has text it creates the model append it to the colelction and render the view!.
Here is the new code for the view, i hope someone could tellme if this is good or if the model should validate this or any other object should to this labor.
Code:
var AddTask = Backbone.View.extend({
    el: '#todos',

    events:{
        'click #add': 'addTask'
    },

    addTask: function(){

        var taskTitle = $('#inputTask').val();
        $('#inputTask').val(""); //clear the input

        if($.trim(taskTitle) === ''){
            this.displayMessage("Todo's can not be empty");
        }else{
            var task = new Task( {title: taskTitle} ); // create the task model
            this.collection.add(task); //add the model to the collection
        }
    },

    displayMessage: function(msg){
        $('#inputTask').attr("placeholder", msg);
    }
});

Validate models with Backbone.js


Find maximal element of an array recursively

Question: I have this function:
int max(int arr[], int size)
{
    size--;
    if(size > 0)
    {
        int max = max(arr, size);
        if(arr[max] > arr[size]) return max;
    }
    return size;
}

And of course it works. My question is - how does this work? Could anyone explain me this step by step? It's Saturday so maybe somebody has a bit of time :D I especially mean these two lines in if block.
Comment: Add lots of `printf` calls all over the function, printing all values, then call it for a small array, say size 3 or so. It might help you understand it better.
Comment: You should step through the code in a debugger, or add a bunch of print statements, to allow you to track exactly where the program is going.
Comment: @khernik: You should also print out the values of various variables.  And add some newlines ;)
Answer: Let's take this array for example:
int arr[] = { 42, 54, 23 };
max(arr, 3);

This function work by checking the max of the current element against the max of all previous elements. Here is a representation of the stack calls:
max(arr, 3)
    max(arr, 2)
        max(arr, 1)
            return 0
        arr[0] (arr[max] = 42) <= arr[0] (arr[size] = 42) => return size (0)
    arr[0] (arr[max] = 42) <= arr[1] (arr[size] = 54) => return size (1)
arr[1] (arr[max] = 54) > arr[2] (arr[size] = 23) => return max (1)

NB: It is a bad idea to name both a variable and a function with the same identifier.
Answer: You code is as follows:
1 int max(int arr[], int size){
2     size--;
3     if(size > 0){
4         int max = max(arr, size);
5         if(arr[max] > arr[size]) return max;
6     }
7     return size;
8 }

You call it by passing it array and the size (or length) of that array.
The first important point the code hits is on Line 4, when it calls itself recursively. But notice that on Line 2, the size was decreased by one. Therefore, you can think of size as being an index referring to the element of the array being considered by the current call to the function.
This means that eventually, the size of the array will be down to zero and we will be looking at the first element of the array. At this point Lines 3 through 6 are skipped, and 0 is returned.
When one of the recursive calls returns, we're left back at Line 4.
For the first return, this means that int max = 0;.
Now we are comparing the zeroth element with the first element. We return the index of whichever is greater. The next comparison will be between the second element and whichever of the first two was larger.
This continues until all the recursive calls are returned, at which point the index of the greatest element is returned to the calling function.
Note then, that return size; should be replaced with return 0 to increase clarity.
Answer: Lets step through the problem for arr[] = [1,2] which means call max(arr[], 2)
size--; // 2-1 = 1
if(size > 0) //True
    {
        int max = max(arr, size); //Going into the recursive call

This is the recursive run :
    size--; // Now 1-1 = 0
    if(size > 0) //False
    return size; //0 returned

Now back into the calling function :
        int max = 0 //From return
        if(arr[max] > arr[size]) //arr[0]>arr[1] which is false
    }
    return size; //Now, control reaches here and 1 is passed back to the calling scope
}

Answer:
Sorry for the poor formatting of the diagram


HttpContext is null in derived class

Question: I am getting HttpContext null sometime in the derived class. I am currently inheriting BaseController into ActionLogsController.
Just look at my code:
BaseController:
public abstract class BaseController : Controller
{
    protected virtual new CustomPrincipal User
    {
        get { return HttpContext.User as CustomPrincipal; }
    }
}

ActionLogsController:
public class ActionLogsController : BaseController
{
    public ActionResult AddActionLog(ActionLogModel model)
    {
        var name = user.name;
    }
}

What I am doing wrong? It gives null sometime. Is it just a crash or I need to do any change in my code?
Comment: When asking, please always include the language you are working with - also when it might be obvious by the code provided.
Answer: Controller already has a User property.
Alright, you try create a new one, but there is not need to directly couple to HttpContext there.
Cast the base property to your custom principle.
public abstract class BaseController : Controller {
    protected virtual new CustomPrincipal User {
        get { return base.User as CustomPrincipal; }
    }
}

It gets the user from the same place.
Controller.cs
public IPrincipal User
{
    get { return HttpContext == null ? null : HttpContext.User; }
}

The risk with doing what you are doing is that you need to make sure that principle is of the matching type (in this case your custom principle), otherwise the cast will cause the property to always return null.
And that is because if the current request's user is not authenticated you may get a principle for an anonymous user, which, since it is not your CustomPrincipal will result in null being returned when User is called.

HttpContext is null in derived class


shell wildcards

Question: i tried to google this but can't find a satisfactory answer. it's probably very straightforward so apologies if it's basic stuff
what is the difference bewteen
grep "first" */*html

and
 grep "first" ./*html

i know that dot(.) in the second line stands for 'current directory'
Answer: grep "first" */*html

expands as all html files in all subdirectories (one-level only) from the current dir.
grep "first" ./*html

expands as all html files in the current dir. the './' is what limits it the the current dir.
EDIT
Per @lisko 's comment
Hidden files and directories mean files beginning with the '.' character. If you want to search ALL files, use
grep "first" ./*html ./.*html */*html */.*html

I hope this helps.
Answer: The first line will grep through all files that match filenames ending with "html" one directory below the current directory because the first "*" will match any directory.
The second line will grep though all the files that match filenames ending with "html" in the current directory.
Note that hidden files or hidden directories won't be matched.

shell wildcards


MPMediaItemPropertyArtwork not displaying in UIImageView (iOS 8) with other MPMediaItems not updating

Question: When trying to grab and display song covers/artworks with MPMediaItemPropertyArtwork, they fail to display in my UIImageView. Additionally, with the other MPMediaItems showing the Artist Name and Song Name, they do not update when the song is changed.
This is my .h file:
#import <UIKit/UIKit.h>

@interface ViewController : UIViewController

@property (weak, nonatomic) IBOutlet UILabel *songtitle;
@property (weak, nonatomic) IBOutlet UILabel *songartist;
@property (weak, nonatomic) IBOutlet UILabel *nowplaying;
@property (weak, nonatomic) IBOutlet UIImageView *songalbumart;

@end

This is part of my .m file that has the MPMusicPlayerController content:
MPMusicPlayerController *player = [MPMusicPlayerController systemMusicPlayer];

MPMediaItem *item = [player nowPlayingItem];

NSString *songtitlestring = [item valueForProperty:MPMediaItemPropertyTitle];
NSString *songartiststring = [item valueForProperty:MPMediaItemPropertyArtist];
NSString *nowplayingstring = [NSString stringWithFormat:@"#NowPlaying %@ by %@, via @TweetPlaying", songtitlestring, songartiststring];

self.songalbumart = [item valueForProperty:MPMediaItemPropertyArtwork];

self.songtitle.text = songtitlestring;
self.songartist.text = songartiststring;
self.nowplaying.text = nowplayingstring;

Anyone know how to resolve these issues of:

MPMediaItemPropertyArtwork not displaying (IBOutlet is connected!)
MPMediaItems of the UILabels to display Artist Name and Song Name not updating when song is changed by user

I am developing for iOS 8 and am there using MPMusicPlayerController's systemMusicPlayer as iPodMusicPlayer is depreciated.
Any help would be appreciated!
Edit: So I have to use MPMusicPlayerControllerPlaybackStateDidChangeNotification, can anyone provide an example for my situation?
Comment: `[self.songalbumart setImage:[[item valueForProperty:MPMediaItemPropertyArtwork] imageWithSize:CGSizeMake(songalbumart.frame.size.width, songalbumart.frame.size.height)];` ? You say that info are not updating, but do you listen when the music change?
Comment: @Larme I am using an IBOutlet to link the MKMediaPropertyArtwork to a UIImageView on my Storyboard though, will that code still work? And no, the application isn't listening when the music changes, would you be able to provide a solution for that possibly?
Comment: I think that you still may be able to use `
MPMusicPlayerControllerNowPlayingItemDidChangeNotification` There should be some example on the web.
Comment: @Larme Can you provide something I could like at? Can't find anything quite relevant to my situation.
Comment: Look for example using `iPodMusicPlayer`, and replace it by `systemMusicPlayer`. http://stackoverflow.com/questions/25788671/detect-when-music-player-is-being-paused/25788824#25788824 (and change the notification that you listen but you'll get how it works).
Comment: @Larme Just tried `[self.songalbumart setImage:[[item valueForProperty:MPMediaItemPropertyArtwork] imageWithSize:CGSizeMake(songalbumart.frame.size.width, songalbumart.frame.size.height)];`, doesn't work, any ideas?
Comment: Is `[item valueForProperty:MPMediaItemPropertyArtwork]` nil?
Comment: Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/62348/discussion-between-rastudios-and-larme).
Comment: Possible duplicate of [MPMediaItemArtwork is null while cover is available in iTunes](http://stackoverflow.com/questions/25998621/mpmediaitemartwork-is-null-while-cover-is-available-in-itunes)
Answer: Following code worked for me.
MPMediaItemArtwork *artwork = [mediaItem valueForProperty: MPMediaItemPropertyArtwork];
UIImage *artworkImage = [artwork imageWithSize: albumImageView.bounds.size];

if (artworkImage) {
    albumImageView.image = artworkImage;
} else {
    albumImageView.image = [UIImage imageNamed: @"noArtwork.png"];
}

Got answer from this link


Poisson Process: a problem of customer arrival.

Question: There is a question that I am not sure about the answer.
Customers arrive according to a Poisson process of rate 30 per hour. Each customer is served
and leaves immediately upon arrival. There are two kinds of service, and a customer pays \$5
for Service A or $15 for Service B. Customers independently select Service A with probability
1/
3
and Service B with probability 2/
3

a. During the period 9:30–10:30am, there were 32 customers in total.
What is the probability that none of them arrived during
10:25–10:30am?

Attempt a:
$P(N(60)-N(55)=0|N(60)=30)=\frac{P(N(60)-N(55)=0,N(60)=32)}{P(N(60)=32)}=\frac{P(N(55)=32)P(N(5)=0)}{P(N(60)=32)}$.
At this point, simply plug in the poisson process with $P(N(t)=n)=\frac{(\lambda t)^nexp(-\lambda t)}{n!}$

b. What is the probability that the first two customers after 9:00am
request Service B?

Attempt b: Treat this as two indep poisson process each has rate of $1/3 \lambda$ and $2/3 \lambda$. This is simply $(\frac {1/3 \lambda}{1/3\lambda +2/3 \lambda})^2$

c. Determine the expected amount paid by all customers during a 10 minute period.

Attempt c: $E[N(t)]=E[N_1(t)]+E[N_2(t)]=5*1/3\lambda t+15*2/3\lambda t=35/3 \lambda t$. @10 min, we have $35/3*30/60*10=350/6$
Comment: You should ask those as three separate questions.
Answer: The (a) part could be simply solved by binomial. Although, Poisson is still an option, it just gets a little messy.
Binomial will simply be: Binomial(20,1/12). Try to check by solving. The answer will be (11/12)^32
Answer: a) Conditional on the number of arrivals in a given period, the arrivals are independently uniformly distributed over the period, so the probability that all of them arrived in $\frac{11}{12}$ of the hour is
$$\left(\frac{11}{12}\right)^{32}\approx6.2\%\;.$$
This is also what your more involved approach yields upon simplification.
b) This has nothing to do with the arrival times and thus with the Poisson process; each customer independently decides with probability $\frac23$ to choose service $B$, so the probability that the first two customers choose service $B$ is $\left(\frac23\right)^2=\frac49$. This is also what your more involved approach would have yielded upon simplification, except you seem to have accidentally applied it to service $A$ instead of $B$.
c) Your answer is correct.


Why I am getting different predictions for manual polynomial expansion and using the R `poly` function?

Question: Why I am getting different predictions for manual polynomial expansion and using the R poly function?
set.seed(0)
x <- rnorm(10)
y <- runif(10)
plot(x,y,ylim=c(-0.5,1.5))
grid()

# xp is a grid variable for ploting
xp <- seq(-3,3,by=0.01)
x_exp <- data.frame(f1=x,f2=x^2)
fit <- lm(y~.-1,data=x_exp)
xp_exp <- data.frame(f1=xp,f2=xp^2)
yp <- predict(fit,xp_exp)
lines(xp,yp)

# using poly function
fit2 <- lm(y~ poly(x,degree=2) -1)
yp <- predict(fit2,data.frame(x=xp))
lines(xp,yp,col=2)

My attempt:

It seems to be a problem with intercept, when I fit the model with intercept, i.e., no -1 in model formula, the two lines are the same. But why without the intercept the two lines are different?
Another "fix" is using raw polynomial expansion instead of orthogonal polynomial. If we change the code into fit2 = lm(y~ poly(x,degree=2, raw=T) -1), will make 2 lines the same. But why?
Comment: This is off topic from your question, but you are often very open to commentary.  When reading your code, the first thing I notice is that you use `=` and `<-` for assignment inconsistently.  I really would not do this, it's not exactly confusing, but it adds lots of visual noise to your code for no benefit.  You should settle on one or the other to use in your personal code, and just stick with it.
Comment: Random follow-up tip for making `<-` less of a hassle to type: `alt+-`.
Comment: thanks for helping me on coding! question fixed. @MatthewDrury
Comment: @JarkoDubbeldam thanks for coding tip. I love key board short cuts
Answer: As you correctly note the original difference is because in the first case you use the "raw" polynomials while in the second case you use the orthogonal polynomials. Therefore if the later lm call was altered into: fit3<-lm(y~ poly(x,degree=2, raw = TRUE) -1) we would get the same results between  fit and fit3. The reason why we get the same results in this case is "trivial"; we fit the exact same model as we fitted with fit<-lm(y~.-1,data=x_exp), no surprises there.
One can easily check that the model matrices by the two models are the same all.equal( model.matrix(fit), model.matrix(fit3) , check.attributes= FALSE) #  TRUE).

What is more interesting is why you will get the same plots when using an intercept. The first thing to notice is that, when fitting a model with an intercept

In the case of fit2 we simply move the model predictions vertically; the actual shape of the curve is the same.
On the other hand including an intercept in the case of fit results into not only a different line in terms of vertical placement but with a whole different shape overall.

We can easily see that by simply appending the following fits on the existing plot.
fit_b<-lm(y~. ,data=x_exp)
yp=predict(fit_b,xp_exp)
lines(xp,yp, col='green', lwd = 2)

fit2_b<-lm(y~ poly(x,degree=2, raw = FALSE) )
yp=predict(fit2_b,data.frame(x=xp))
lines(xp,yp,col='blue')

OK... Why were the no-intercept fits different while the intercept-including fits are the same? The catch is once again on the orthogonality condition.
In the case of fit_b the model matrix used contains non-orthogonal elements, the Gram matrix crossprod( model.matrix(fit_b) ) is far from diagonal; in the case of fit2_b the elements are orthogonal (crossprod( model.matrix(fit2_b) ) is effectively diagonal).
As such in the case of fit when we expand it to include an intercept in fit_b we changed the off-diagonal entries of the Gram matrix $X^TX$ and thus the resulting fit is different as a whole (different curvature, intercept, etc.) in comparison with the fit provided by fit. In the case of fit2 though when we expand it to include an intercept as in fit2_b we only append a column that is already orthogonal to the columns we had, the orthogonality is against the constant polynomial of degree 0. This simply results on vertically moving our fitted line by the intercept. This is why the plots are different.
The interesting by-question is why the fit_b and fit2_b are the same; after all the model matrices from fit_b and fit2_b are not the same in face value. Here we just need to remember that ultimately fit_b and fit2_b have the same information. fit2_b is just a linear combination of the fit_b so essentially their resulting fits will be the same. The differences observed in the fitted coefficient reflects the linear recombination of the values of fit_b in order to get them orthogonal. (see G. Grothendieck answer here too for different example.)
Comment: +2.5 thanks for great answer. For the final graph, I learned from @kjetilb halvorsen: One more abstract way of describing this is that the model itself only depends on a certain linear subspace, namely the column space defined by the design matrix. But the parameters, depend not only on this subspace, but on the basis for that subspace, given by the specific variables used, that is, the columns itself. Predictions from the model, for instance, will only depend on the linear subspace, not on the choosen basis.


Edit : How to change this code into LINQ-expression

Question: First of all, sorry if my question will confuse you. Well, I'm still a rocky about this programming in c#.
I am using the code below:
foreach (var schedule in schedules)
{
      if(schedule.SupplierId != Guid.Empty)
      {
          var supplier = db.Suppliers.Find(schedule.SupplierId);
          schedule.CompanyName = supplier.CompanyName;
      }
      if(schedule.CustomerId != Guid.Empty)
      {
          var customer = db.Customers.Find(schedule.CustomerId);
          schedule.CompanyName= customer.CompanyName;
      }
}

It works really well, but what if the company that I will have is about a thousand company, this looping will slow my program, how to change this code into LINQ-expression.
Please for your reply. Thank you.
Comment: @DavidBrabant why did you remove part of the original code?
Comment: You can update as and when a company decides its update, but regardless, each one of those companies will need to run this code so therefore the time taken will probably be the same (if not more time needed due to the individual method calls)
Comment: Two blocks were exact duplicates. Thought that was an error. Was I wrong?
Comment: I've put it back in.. David, it contains info about customers instead and I suspect the OP is looking for a way to rewrite this.
Comment: Yep. I was. Sorry for that.
Comment: what kind of ORM mapper are you using? you can easily do it with a single query, using a join, or multiple selects.
Answer: There isn't a good way to do this in the client. There are some tools out there to do a mass update on EF, but I would suggest to run just a query to do this, if you need to do this at all. It seems you are updating a field which is just related, but in fact belongs to another entity. You shouldn't do that, since it means updating the one will leave the other invalid.
Answer: What Patrick mentioned is absolutely right from an architectural point of view. In my understanding CompanyName belongs somewhere else, unless this entity is a "read-only view"...which obviously is not. Now, if you can't afford to make a major change I would suggest you move this heavy processing off the main thread to a separate thread...if you can.
You can also load all suppliers and companies in memory rather than opening a database connection 1000 times to issue a lookup query. But, again, consider strongly moving this to a separate thread


How can we use AIML for making a chatbot?

Question: Can we give random responses for a single question in AIML. For "Hi", I need random replies like "hey", "hello", "hi", etc.
Comment: Your title and content are quite different. Which one are you after? For the content question the answer is "yes", as a quick internet search will show. It will also show how to do it.
Answer: AIML can be used for making chatbots. But you have to make templates for all possible questions user could possibly ask. Here is an example for AIML random responses
<code> <pattern>HI</pattern>
   <template>
     <random>
        <li> Hello! </li>
        <li> Hi </li>
        <li> Hey </li>
     </random>
</code>


Salvar imagem vindo da API na memória do celular

Question: Estou tentando salvar uma imagem vindo da API na memória do celular.
    public void saveSkin() {
    ivSkinSaver.buildDrawingCache();
    Bitmap bm = ivSkinSaver.getDrawingCache();

    OutputStream Out = null;
    try {
        File mediaFile;
        File mediaStorageDir = new File(Environment.getExternalStorageDirectory()
                + "/Android/data"
                + getApplicationContext().getPackageName()
                + "/Files");
        String timeStamp = new SimpleDateFormat("dd/MM/yyyy_HH:mm_").format(new Date());
        String mImageName = timeStamp + stringSkin;
        mediaFile = new File(mediaStorageDir.getPath() + File.separator + mImageName);
        mediaFile.createNewFile();
        Out = new FileOutputStream(mediaFile);
        Toast.makeText(getBaseContext(),"file saved",Toast.LENGTH_SHORT).show();
    } catch (Exception e) {
        Toast.makeText(this, "Error occured. Please try again later." + e.getStackTrace(),
                Toast.LENGTH_SHORT).show();

        e.printStackTrace();
    }

    try {
        bm.compress(Bitmap.CompressFormat.PNG, 100, Out);
        Out.flush();
        Out.close();
    } catch (Exception e) {
    }
}
}

Eu usei o e.printStackTrace() e o resultado é : "java.io.IOException: open failed: EACCES (Permission denied)"
Comment: Talvez porque você não tem permissão mesmo. Verifique seu Manifest se concedeu permissão de escrita no device: android.permission.WRITE_EXTERNAL_STORAGE
Comment: Além disso, se você tiver usando Android 6.0 tem que conceder permissão em tempo de execução.
Comment: Ja coloquei o WRITE_EXTERNAL_STORAGE e READ_EXTERNAL_STORAGE mas continua com o mesmo problema.
Comment: Em que versão do Android está a executar a aplicação?
Comment: @ramaral está na versão 6.0
Comment: @WellingtonYogui  a resposta abaixo te atendeu ou precisa de mais alguma informação?!
Answer: Isso pode estar ocorrendo porque você de alguma forma não concedeu permissão de escrita no dispositivo. Veja como deve está seu AndroidManifest.xml:
<manifest>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    ...
    <application>
        ...
        <activity>
            ...
        </activity>
    </application>
</manifest>

Além disso, deve observar também se o uso da aplicação é no Android 6.0 + , deve conceder permissão em tempo de execução. Veja como fazer uma solicitação de permissões em tempo de execução na própria documentação.
A partir do Android Marshmallow, API 23, os usuários concedem permissões a aplicativos enquanto eles estão em execução, não quando eles são instalados.

Essa abordagem otimiza o processo de instalação de aplicativos, pois o
  usuário não precisa conceder permissões ao instalar ou atualizar o
  aplicativo.

Além desta questão, também estabelece ao usuário mais controle sobre os recursos do aplicativo. Por exemplo, um usuário poderia optar por permitir que um aplicativo de câmera tenha acesso à câmera, mas não à localização do dispositivo. O usuário pode revogar as permissões a qualquer momento na tela de configurações da aplicação.
Veja um exemplo:
if (ContextCompat.checkSelfPermission(context,WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {

      // Verifica se já mostramos o alerta e o usuário negou na 1ª vez.
      if (ActivityCompat.shouldShowRequestPermissionRationale(context,Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
           // caso o usuário tenha negado a permissão anteriormente, e não tenha marcado o check "nunca mais mostre este alerta"

      } else {
          // solicita permissão
          ActivityCompat.requestPermissions(context,new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},0);
      }
} else {
     // caiu aqui está tudo ok
}

Comment: Ja tenho um método que faz essa validação, mas msm assim cai no catch na hora de salvar.
Comment: Como apareceu "Permission denied", a principal fator a considerar é a questão de permissão de leitura e escrita. Talvez seja seu algoritmo para salvar o arquivo então. Você pegar a imagem de uma URL para salvar no dispositivo certo?
Comment: Sim, eu recebo o link da imagem pela api e passo para uma imagemView e coloquei um botão para salvar a imagem.


aumentar velocidade de resposta do cURL?

Question: Estou usando uma API do google e estou testando ela com o código abaixo, porém há uma diferença enorme no carregamento direto pelo browser e pelo PHP, ela demora muito pelo PHP, existe alguma maneira de "acelerar" isso?
    $this -> curl = curl_init();
    curl_setopt($this -> curl, CURLOPT_URL, ltrim($this -> queryURL() . '&q=' . urlencode($this -> query)));
    curl_setopt($this -> curl, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($this -> curl, CURLOPT_RETURNTRANSFER, 1);
    $this -> response = curl_exec($this -> curl);

    curl_close($this -> curl);

Answer: Mais algumas opções de timeout antes do curl_exec:
curl_setopt($this -> curl, CURLOPT_CONNECTTIMEOUT, 1); // espera 1 segundo para conectar

curl_setopt($this -> curl, CURLOPT_TIMEOUT, 10); // espera ateh 10 segundos no envio de comandos

Baseado em: https://stackoverflow.com/questions/2582057/setting-curls-timeout-in-php
Ah, e existe a opção para passar os parâmetros em ms:
CURLOPT_CONNECTTIMEOUT_MS e CURLOPT_TIMEOUT_MS
Comment: Ambas servem pra otimização?


Abstract algebra. splitting field

Question: Find the degree of the splitting field of the polynomial $x^6-7$ over $F_{3}$ (the field with $3$ elements).
Here, $x^6-7$|${x^6}^2-7^2 = x^{12}-1$  where $7^2 = 1\mod 3$
After this step, I couldn't make anything. How can I continue for solution? or if this step is wrong, what is the way to solve this question?
Thank you
Comment: please show your work! otherwise, someone will down-vote and you're much less likely to get help, as we won't know what's confusing you.
Comment: I have edited @peter a g. Thank you.
Answer: Hint: $x^6-7=(x+1)^3(x+2)^3$ over $\mathbb{F}_3$. So the degree is $1$.
Answer: The splitting field over $\Bbb{F}_3$ is a field $\Bbb{F}_{3^q}$. Let's check; $P(X)=X^6-7$ has $\pm 1$ as roots in $\Bbb{F}_3$ because $(\pm 1)^6=1\equiv 7\pmod{3}$
Now we have in $\Bbb{F}_3$ (remember that $a^3+b^3=(a+b)^3$)
$$(X-1)^3(X+1)^3=(X^2-1)^3=X^6-1=X^6-7$$
And so our polynomial have two distinct roots of multiplicity $3$ in $\Bbb{F}_3$ and the degree is $1$
Comment: Thank you for your interest @marwalik. But how can i show that 1 is root in  $F_3$
Comment: I edited for more details answering your question

Abstract algebra. splitting field


$R^2$ for least absolute deviation regression

Question: I know that $R^2$  is for the least square regression. Is there an analogous measure of fit to $R^2$ in LAD (Least Absolute Deviations) regression?
Here I am concerned with the "fitting quality".
Comment: $R^2$ has many different properties at the same time. You can't keep all of the properties that $R^2$ has, so you have to explain what properties of $R^2$ you want and (at least by omission) convey which ones are not so important to you.
Answer: The definition of "analogue" is not clear.
If you view $R^2$ as a metric to measure the "goodness of the fit" in regression setting. Then, likelihood can be used to evaluate the "goodness of the fit" for LDA (Linear Discriminant Analysis).

EDIT: I think OP was trying to ask LAD (Least absolute deviations regression) but not LDA. Here is my answer to LAD.
I would suggest OP to review the loss function in regression setting. For squared loss regression, the loss function is
$$\sum_i (y_i-\hat y_i)^2$$
where $\hat y_i$ is the predicted value for data $i$, and the sum is over all the data points.
For least absolute deviation loss, the loss function is
$$\sum_i |(y_i-\hat y_i)|$$
Therefore, to evaluate the "goodness of fit", we can exam the loss value. Now, the problem is with the loss value metric, it will depend on number of data points, i.e., the more data points we have, in general, the higher value the will be in aforementioned 2 formulas.
One way of dealing it is divided by number of data points. And if we want to do one step more, we can "normalize" it into 0 to 1 using RSS, which is R square.
But I think dividing the number of data points should be good for your purpose.
Comment: for simplicity can i compare their residuals plot to see the relative performance of "goodness of fit"?
Comment: or how can i calculate the MLE of LAD if i have fitted a LAD using R.Any code i can use?


UML - Diagrama de Classe

Question: Olá,
Comecei a estudar os diagramas UML recentemente e me surgiu um dúvida sobre como saber quem são os objetos.
Minha dúvida é, qual a melhor maneira de identificar um objeto? Pois uma classe pode ser tanto um substantivo (Cliente), quanto uma ação (Cadastrar Cliente).
Desde já, agradeço.
Answer: Você deve analisar não pelas classes que criará no seu programa, más pelo que as classes vão manipular, lembrando que os objetos são diferentes das classes:

Um objeto necessita de uma classe para existir;
Uma Classe não necessita de um objeto para existir;

Uma definição conhecida é: "Um objeto  é um termo que usamos para representar uma entidade do mundo real".
Os objetos é que devem estar no seu diagrama, pois eles terão seus atributos e serão manipulados de acordo com sua necessidade de regras de negócio.
Seguindo a linha de pensamento citado por você na pergunta, um sistema que tenha Cliente e cadastroCliente, Funcionario e cadastroFuncionario, terão como entidades o Cliente e o Funcionario, pois são eles as entidades do "mundo real".
Nesse link você encontrará mais sobre esse assunto: http://www.macoratti.net/net_uml1.htm

UML - Diagrama de Classe


Dbus or Udev command to locate connected hardware

Question: It's a dumb question. Once I knew this command, I used it two or three months ago but now it seems I can't recall it. I tried to look for it using Google but nothing happened :(
It's a dbus command which send a query to udev or something similar, basically I could do
mysterious_command | grep Storage

and I could see all usb storage drives.
(No, using mount it's not the same because it just gives me mounted partition and not if they are usb storage or whatever...or maybe it can and I didn't know about it).
Comment: See: [What's the best way to get info about currently unmounted drives?](http://serverfault.com/questions/190685/whats-the-best-way-to-get-info-about-currently-unmounted-drives) and [How can I find out what hard disks are attached to a Linux box?](http://serverfault.com/questions/5031/how-can-i-find-out-what-hard-disks-are-attached-to-a-linux-box)
Answer: I think you're looking for either lshal or lsusb.
Comment: Fyi hal is being deprecated
Comment: What's the new kid in town then? I need something like hal.
Answer: Will dmesg or dmidecode get what you are looking for?
I don't have any connected USB media to try this against but dmesg | grep Storage returns:
Initializing USB Mass Storage Driver
scsi1 : SCSI emulation for USB Mass Storage devices
scsi2 : SCSI emulation for USB Mass Storage devices
USB Mass Storage support registered
Comment: thanks but it was "lshal". Usually you can do "lshw -C disk -C volume" but it's not useful to my purpouse.


Form API Ajax - how to disable also form elements that will be changed, not only triggering element?

Question: So, element that triggered AJAX gets disabled. But how to make Drupal also disable everything inside ['#ajax']['wrapper']? After all, allowing user to edit something that will get replaced as soon as AJAX response is ready isn't the wisest idea, and I'd like to prevent that. And my AJAX created elements have their own AJAX too, race conditions are pretty bad already.
Is there any ready-made module for that? Or API way I'm missing? If no, where exactly should I put that code to minimize risk of incompatibilities?
Edit: I'm looking for a safe and stable way. It means no hard-coded identifiers in JavaScript files. Solution that breaks when someone edits form definition, or one that works for only one AJAX in form is not enough. After all, I need to avoid race conditions, and I already noted I have multiple AJAX actions, working on different sets of elements, on one page - so no marking elements for disabling at PHP level. I can eventually mark them with classes like disable-on-X and disable-on-Y, but I need to know if it's X or Y AJAX happening. And ideally I'd just disable everything inside ['#ajax']['wrapper'] without any additional marks, as they are not really needed - but again, I would need to know proper ['#ajax']['wrapper'] in javascript.
Answer: You can disable/enable some elements during ajax using this jQuery script:
// Disable filters on ajax call.
  $(document)
    .ajaxStart(function() {
      // Place here all elements that must be disabled during ajax.
      $("#path-to-the-element").attr("disabled", "disabled");
  })
    .ajaxComplete(function() {
      // Place here all elements that must be enablec after ajax.
      $("#path-to-the-element").removeAttr("disabled");
  });

Update. Some helper suggestions:

You can loop all inputs in wrapper element and disable each of them
using jQuery.each
You can see what is the class or id attribute of your generated
element html. Also you can add some special CSS class disable-on-ajax
to all your elements or wrappers that must be disabled on ajax. Then you will be able to handle them with one line of jQuery code.

Update 2
I can suggest one more solution.
E.g. you have added class for your target elements 'disable-on-ajax'.
Then you can write function that will be triggered on blur, select change, click etc.(You'll need to implements all target triggger checks).
In this function you'll check if element has class "disable-on-ajax". And add second class "ajax-disabled". Then on ajaxStart you'll handle only element with class "ajax-disabled"
You can populate form ajax-triggering elements, add property like ajax_wrapper="wrapper", ajax_event="event type" and then in behavior attach events
Comment: let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/9308/discussion-between-milkovsky-and-molot)


How to extract data from 'Column D' to one single column in a different sub sheet?

Question: I've attached the sheet - Click here
I want pull data from these three sheets - A, B, C to this sheet - 'Combined data of Column D' and only the data in Column D would be pulled.
Anyone who can guide a newbie on how to do this? It'd be much appreciated!
Comment: try this `=query({A!D:D;B!D:D;'C'!D:D},"where Col1 is not null")`
Comment: Please include sample data within the question - linking to a file has to be avoided as no one will download it without knowing you. Furthermore you should show us what you already tried or where you have problems. Read [ask] and [repro] - this might help you to improve your question.
Answer: use:
<code>=QUERY({A!D:D; B!D:D; C!D:D}; "where Col1 is not null"; 0)
</code>
Comment: Thanks a ton! What should I do in the case where there are 100s of such sheets with complex names on every sheet. How do I create a similar formula for that?
Comment: @Manas you will need to manually add each sheet into array - thats the only non-scripted way of doing this task


How can I unit test an HTTP service in Ballerina?

Question: Suppose I have an echo HTTP service written in Ballerina as follows:
import ballerina/http;

service / on new http:Listener(9090) {

    resource function post echo(@http:Payload json payload) returns json {
        return payload;
    }
}

How can I write unit test the behavior of the echo resource method?
Comment: This is explained in Ballerina documentation: [Testing services and clients](https://ballerina.io/learn/testing-ballerina-code/testing-services-and-clients/)
Comment: I'm voting to close this question because the answer can be found from the official documentation.
Comment: Thanks for the documentation. It contains what I was looking for. However, should quoting/pointing to the documentation be the answer rather than closing the question?
Comment: @user272735 Can you add your comment as an answer with some quoting so that I can accept it as the answer.
Answer: You can write unit tests for an HTTP service using the Ballerina HTTP client.
Place the tests inside the tests directory inside your Ballerina project.
Following is an example test:
import ballerina/http;
import ballerina/test;

@test:Config {}
function testService() returns error? {
    http:Client httpClient = check new("http://localhost:9090");
    json requestPayload = {message: "hello"};
    http:Request request = new;
    request.setPayload(requestPayload);
    json responsePayload = check httpClient->post("/echo", request);
    test:assertEquals(responsePayload, requestPayload);
}

Here, we send a payload and get it back using an HTTP client, and then check whether the echo service sends back the same payload.
When running the tests, the service will be started automatically. You don't have to run them manually.


How to change euler form of complex to trigonometric form.

Question: In physics, my professor often writes the function $f_{0}\sin(pt)$ as $f_{0}e^{ipt}$.
But I don't understand this, because I know that
$e^{it}$ = $\cos t + i \sin t$
Please explain why my professor can write it like this.
Comment: Please see https://math.meta.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference
Answer: In physics, there's a convention to ease calculation of operations on waves by writing $e^{i pt}$ instead of $\cos(pt)$, then implicitly only pay attention to the real part in the answer. It looks like your professor is doing this with the imaginary part instead (or, more likely, he is assuming a phase constant as part of the $f_0$). You should check his work to see if his usage conforms to this idea.


Identifying order of a group from three pieces of information about its' subgroups

Question:
Suppose $G$ is a cyclic group that has exactly three different subgroups: The trivial one, a subgroup of order $7$ and $G$ itself. What is the order of $G$?

What is the idea here?
Comment: They're all cyclic.
Comment: I don't believe we've learned Lagrange here.
Comment: Lagrange says that the order of a subgroup divides the order of the group. I am sure you had this.
Comment: And if the group is cyclic, then for each prime divisor $d$ of $|G|$ we have a subgroup of order $d$?
Answer: For finite cyclic groups, there is a bijection between subgroups of $G$ and divisors of $|G|$.
Since $G$ is cyclic, the statement is equivalent to saying that $|G|$ has exactly three divisors: $1$, $7$ and $|G|$ itself. So $|G| = 7^2$.
Comment: "For finite cyclic groups, there is a bijection between subgroups of $G$ and divisors of $|G|$." What is this theory? Still new to the course
Comment: @TheNotMe this is the well-known structure theorem for finite cyclic froups https://en.wikipedia.org/wiki/Subgroups_of_cyclic_groups#Finite_cyclic_groups


How to check if vectors can be part of a basis for a subspace

Question: Question
Let V be the subspace of $\mathbb{R}^4$ defined as V={(w, x, y, z) ∈ $\mathbb{R}^4$:w+x+y+z= 0}.
Check that the vectors $\begin{bmatrix} -1 \\ 0 \\ 1 \\ 0 \end{bmatrix}$ and $\begin{bmatrix} 0 \\ -1 \\ 0 \\ 1 \end{bmatrix}$ can be part of a basis for V. Then expand the set consisting of these two vectors to a basis of V.
I'm assuming that the answer is that the two vectors can be part of the basis because they are linearly independent, but I'm not sure if I'm correct. Also, how do we know what dimension of V is? Is it correct that dim(V) = 3, since we need a free variable to solve the problem. e.g. w=-x-y-z
Comment: So the vectors are part of the basis since the vectors span the space (-1+0+1+0=0 and 0-1+0+1=0) and are independent?
Comment: yes,by the definition
Comment: To denote the real numbers, please use the symbol $\mathbb{R}$, the code of which is ```\mathbb{R}```.
Comment: Those vector don't _span_ the space, they are _elements_ of the space.
Answer: For any vector to be an element of a basis for a vector space $V$, first and foremost it must be an element of that space. Based on your comments you appear to be confusing this will spanning the space. It's way too early to speak of anything spanning $V$, and this pair of vectors clearly can't do so, anyway, because per the Rank-Nullity theorem, $V$ is three-dimensional. The two vectors satisfy the defining equation of $V$, so they are indeed elements of $V$.
Second, the vectors must be linearly independent, which should be obvious for these two. Therefore, they can be part of a basis of $V$. As I mentioned above, they cannot span $V$ since you need at least three vectors for that, but we already knew that, anyway, because the next part of the assignment asks to to complete the basis of $V$.
Based on some other comments, it looks like you tried to complete the basis by doing something that you'd no doubt seen for other complete-the-basis: you added the standard basis vectors of $\mathbb R^4$ to the set and then looked for a linearly-independent subset. You've overlooked something very important, though: Remember how at the top I said that the first criterion is that the vector be an element of the space? Well, none of the standard basis vectors are elements of $V$, so they're the wrong thing to use. Instead, you need to supplement the initial set of vectors with other elements of $V$, and then apply the process to that set. An easy-to-find set of vectors in $V$ is $\{(1,-1,0,0)^T, (1,0,-1,0)^T, (1,0,0,-1)^T\}$. The second one of these is obviously a multiple of one of the original two vectors, so we'll discard that and work with the remaining two. Assembling them into a matrix and row-reducing, we get $$\begin{bmatrix}-1&0&1&1\\0&-1&-1&0\\1&0&0&0\\0&1&0&-1\end{bmatrix} \to \begin{bmatrix}1&0&0&0\\0&1&0&-1\\0&0&1&1\\0&0&0&0\end{bmatrix}$$ so we can use either of the extra vectors to complete the basis.
Answer: Part of basis means not only independent but also spans the space. Dimension of $V =3$ is correct
$w=-x-y-z$
written in standard basis as
$x\begin{bmatrix} -1\\0\\0\\0\end{bmatrix}+y\begin{bmatrix}0\\-1\\0\\0\end{bmatrix}+z\begin{bmatrix}0\\0\\-1\\0\end{bmatrix}$
Comment: I expanded the set to $\begin{bmatrix}
-1 & 0 & 1 & 0 & 0 & 0\\
0 & -1 & 0 & 1 & 0 & 0\\
1 & 0 & 0 & 0 & 1 & 0\\
0 & 1 & 0 & 0 & 0 & 1
\end{bmatrix} \sim \begin{bmatrix}
1 & 0 & 0 & 0 & 1 & 0\\
0 & 1 & 0 & 0 & 0 & 1\\
0 & 0 & 1 & 0 & 1 & 0\\
0 & 0 & 0 & 1 & 0 & 1
\end{bmatrix}$
Comment: Since we only select pivot columns and dim(V)=3, then the bases could be $\begin{bmatrix} -1 \\ 0 \\ 1 \\ 0 \end{bmatrix}$,$\begin{bmatrix} 0 \\ -1 \\ 0 \\ 1 \end{bmatrix}$,$\begin{bmatrix} 1 \\ 0 \\ 0 \\ 0 \end{bmatrix}$ or  $\begin{bmatrix} -1 \\ 0 \\ 1 \\ 0 \end{bmatrix}$,$\begin{bmatrix} 0 \\ -1 \\ 0 \\ 1 \end{bmatrix}$,$\begin{bmatrix} 0 \\ 1 \\ 0 \\ 0 \end{bmatrix}$
Comment: Is that correct?
Comment: I understand your answer, but we need to expand the set consisting of the two vectors to a basis of V, so that's why I did the above.
Comment: Can you write $\begin{bmatrix} -1\\0\\1\\0 \end{bmatrix}$ in linear combination of standard basis?
Comment: The way you expand is ok.
Comment: Not sure what you mean about writing $\begin{bmatrix} -1 \\ 0 \\ 1 \\ 0 \end{bmatrix}$ in linear combination of standard basis. Also, since my answer is incorrect, how do we find a basis containing $\begin{bmatrix} -1 \\ 0 \\ 1 \\ 0 \end{bmatrix}$ and $\begin{bmatrix} 0 \\ -1 \\ 0 \\ 1 \end{bmatrix}$
Comment: Can you write$\begin{bmatrix}-1\\0\\1\\0\end{bmatrix}$ in linear combination of $\begin{bmatrix}1\\0\\0\\0\end{bmatrix}$ and $\begin{bmatrix}0\\0\\1\\0\end{bmatrix}$
Comment: Yes. $-1\begin{bmatrix} 1 \\ 0 \\ 0 \\ 0 \end{bmatrix}+1\begin{bmatrix} 0 \\ 0 \\ 1 \\ 0 \end{bmatrix}$
Comment: Then,you are done.
Comment: Wait, but is my answer correct then? I understand that you're implying that there is a linear combination of your answer that will satisfy the question. But I need to include the two vectors specified in the question in the basis.
Comment: You're making the same error in terminology that the OP did in a comment: to be part of a basis, the vectors must be linearly-independent _elements_ of the space. Two vectors can't possibly _span_ the space since it's three dimensional.
Comment: @JevinKosasih Your proposed solutions in the early comments are incorrect. None of the vectors that you've added to the original set are elements of $V$, so they can't possibly be elements of a basis for it.


Xcode 6 Instruments freeze

Question: Profiling my iOS 8 app in Xcode 6 Instruments will run the app for about 5 seconds and then freeze. The profiler will still run after that point but the app is frozen and unusable. Happens on device and simulator and regardless of which profiler I'm using (timer, leaks, etc.)
Running the app from the debugger or an ad hoc build works fine. Profiling with iOS 7 works fine as well.
Any idea why this may be happening? Is Instruments broken?
Comment: If you're having an issue, I'd suggest filing a bug report.
Comment: I am having the same issue, has anybody found any solution ?
Answer: Same issue here:
Application hangs when profiling with instrument in XCode 6.0.1
Looks like if you remove all the NSLog statements it will fix it.
For me this is happening only on iOS 8, i have no problems on iOS 7.
Comment: This seemed to work in a small test case. Unfortunately, seems like the logger in one of the libraries I'm using is still freezing instruments, regardless of whether or not the logger is 'on'. This is still the best answer +1.
Comment: For reference you can use this `#define NSLog(...) do { } while (0)`
Comment: Another solution will be to start the instruments recording after your app is started. I had a bunch of methods in the code that when were running they were freezing the app, I've attached Instruments at the running app and started the recording after those methods finished, in this case you can also have Debug and Instruments at the same time.
Answer: This was also happening to me on an iPod Touch + iOS 8.
Upgrading to 8.0.2 solved this problem for me.
Answer: For me I found out that Instruments was freezing when I started recording due to Xcode already running the application.
It's important for Xcode not to be running any processes when starting Instruments. If you do, Instruments will look like it is hanging.
You can push through the hang by going to Xcode and pressing "Continue Program Execution" on the bottom console toolbar of Xcode.
Answer: I have a very large library that I work on and instruments hangs for me when trying to profile it. I found that I have to have DEBUG_INFORMATION_FORMAT set to DWARF with dSYM File at the app's build settings level.

Xcode 6 Instruments freeze


How to call click event function of menustrip item C#?

Question: I want to call the click function of MenuStrip in C# associated with the item of MenuStrip whose index i can provide
e.g i want to call
menuStrip1.Items[0]

click function.
Answer: Call PerformClick(), i.e. menuStrip1.Items[0].PerformClick();
Comment: Well i have come to know that i have to go through items in menustrip like i have two items 'Main' and 'About Me' and each have 3 sub items.
The actual thing i wanted to do was to perform the click of say 2nd option in Main category. So can you help me on that ...


How to delete an item in sqlite using swift

Question: I am trying to delete a primary key that the user can pass in. When i try to delete an item, nothing happens. Basically from the tableview i would get the indexpath.row to find out which item the user swiped left on and use that value to delete the row.
func DeleteRowDatabase(inputId : Int32) -> Bool
{
        var db: OpaquePointer? = nil
        var returnCode : Bool = true

          if sqlite3_open(self.databasePath, &db) == SQLITE_OK {

        print("Successfully opened connection to database at \(self.databasePath)")

            // step 16d - setup query - entries is the table name you created in step 0
            var deleteStatement: OpaquePointer? = nil
            var deleteStatementString : String = "delete from entries where ID = ?"

            if sqlite3_prepare_v2(db, deleteStatementString, -1, &deleteStatement, nil) == SQLITE_OK {

            sqlite3_bind_int(deleteStatement, inputId, inputId)
             sqlite3_close(db);

            }

        }

        return returnCode

    }

func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {

        if editingStyle == .delete {
            //books.remove(at: indexPath.row)

            print("INDEX PATH")
            print(indexPath.row)

            var x: Int32 = Int32(indexPath.row)

            x = x + 1

            let mainDelegate = UIApplication.shared.delegate as! AppDelegate

            let returnCode : Bool = mainDelegate.DeleteRowDatabase(inputId: x)

        }
    }

Answer: Your main issue is that you never call sqlite3_step to actually execute the query.
But you also have other issues. You need to call sqlite3_close if you attempt to open the database whether the statement is prepared or not. You also need to call sqlite3_finalize on the prepared statement after you are done with it. And you are passing the wrong parameter value for the index in sqlite3_bind_int.
func DeleteRowDatabase(inputId : Int32) -> Bool {
    var db: OpaquePointer? = nil
    var returnCode : Bool = false

    if sqlite3_open(self.databasePath, &db) == SQLITE_OK {
        print("Successfully opened connection to database at \(self.databasePath)")

        // step 16d - setup query - entries is the table name you created in step 0
        var deleteStatement: OpaquePointer? = nil
        var deleteStatementString : String = "delete from entries where ID = ?"

        if sqlite3_prepare_v2(db, deleteStatementString, -1, &deleteStatement, nil) == SQLITE_OK {
            sqlite3_bind_int(deleteStatement, 1, inputId)
            if sqlite3_step() == SQLITE3_DONE {
                returnCode = true
            }

            sqlite3_finalize(deleteStatement)
        }
    }

    sqlite3_close(db)

    return returnCode

}

Comment: @Rob Thanks for the heads up. I've done a lot with SQLite and never saw that little detail you quoted.
Comment: Me, too. I had been using SQLite forever without noticing this. It an edge case (tiny memory leak only when opening of database failed), so we don't see it often in practice.
Answer: Like rmaddy said,

You need to call sqlite3_step to actually perform the prepared statement.

Unrelated, but I'd also suggest:

Call sqlite3_close whether the routine succeeded or not. Even if sqlite3_open didn't succeed, you must call sqlite3_close. As the docs say,

Whether or not an error occurs when it is opened, resources associated with the database connection handle should be released by passing it to sqlite3_close() when it is no longer required.

sqlite3_finalize the prepared statement.

I'd use guard statements to avoid towers of nested if statements.

Check the return code of sqlite3_bind_xxx, too.

I'd call sqlite3_changes to actually confirm whether any rows were deleted or not.

I'd start my method names with lower case letters.

Thus:
func deleteRowDatabase(inputId: Int32) -> Bool {
    var db: OpaquePointer?

    defer { sqlite3_close(db) }
    guard sqlite3_open(databasePath, &db) == SQLITE_OK else {
        return false
    }

    print("Successfully opened connection to database at \(self.databasePath)")

    // step 16d - setup query - entries is the table name you created in step 0
    var statement: OpaquePointer?
    let sql = "DELETE FROM entries WHERE id = ?"

    guard sqlite3_prepare_v2(db, sql, -1, &statement, nil) == SQLITE_OK else {
        return false
    }

    defer { sqlite3_finalize(statement) }

    guard sqlite3_bind_int(statement, 1, inputId) == SQLITE_OK else {
        return false
    }

    guard sqlite3_step(statement) == SQLITE_DONE else {
        return false
    }

    guard sqlite3_changes(db) == 1 else {
        return false
    }

    return true
}

I'd also suggest:

This pattern of opening and closing the database for every SQL statement is a bit inefficient. I'd open the database once and leave it at that.

I worry about assuming that the ID for a row in the table corresponds to indexPath.row. What happens if you have 10 records and delete the first one. You then restart the app and there's now 9 records, but now first row in table corresponds to ID of 2. I'd suggest building an array of ID values when you read in the table, and use those values for subsequent operations, rather than assuming the ID is equal to  indexPath.row + 1.
Comment: FWIW, I'd suggest getting out of the business of writing hairy SQLite code like this. There are tons of SQLite wrappers out there. Or if you want to wrap your own, you could start with something like https://gist.github.com/robertmryan/515bbfc751dd97f5d0745dceee32d3b4.


MySql how to display data from multiple tables only once?

Question: I have two tables in my database - "region" and "attraction". I made a JOIN query that will get data from both of them and I am displaying it afther that. Here is my code:
$regionsId = $_GET['region'];

//$sql    = "SELECT `RegionID`, `RegionName`  FROM `region` WHERE `RegionID`='$regionsId'";
//$sql    = "SELECT `AttractionID`, `Name`, `imglink2`  FROM `attractions` WHERE `RegionID`='$regionsId'";

$sql ="SELECT *
FROM region
INNER JOIN attractions WHERE region.RegionID = '$regionsId' AND attractions.RegionID = '$regionsId'";

$result = mysql_query($sql, $link);

if (!$result) {
    echo "DB Error, could not query the database\n";
    echo 'MySQL Error: ' . mysql_error();
    exit;
}

while ($row = mysql_fetch_assoc($result)) {

    echo $row['RegionName'];

    echo "" .  "
" .
          $row['Name']  .
           "
" .

         "

       ";

}

mysql_free_result($result);

 ?>

My problem is that When I display it the echo $row['RegionName'];  is displayed multiple times, with every attraction I am displaying. How can I make it so that it is displayed only once?
Thank you.
Comment: Go and look again at basic join syntax
Comment: Well you were of SO much help, thanks....
Answer: TRy GROUP  BY
 $sql ="
SELECT *
FROM region
LEFT JOIN attractions ON region.RegionID = attractions.RegionID
WHERE region.RegionID = '$regionsId'
  AND attractions.RegionID = '$regionsId'
GROUP BY region.RegionID" ;

Comment: This only displays one attraction.
Comment: Ok.. `SELECT *
FROM region
LEFT JOIN attractions ON region.RegionID = attractions.RegionID
WHERE region.RegionID = '$regionsId'
  AND attractions.RegionID = '$regionsId'
` Try this
Comment: No, this doesn't work too. If I take out RegionName out of the while loop it doesn't display it at all. I'm at a loss...
Answer: Use this :
$sql = "SELECT DISTINCT *
FROM region
  LEFT JOIN attractions ON region.RegionID = attractions.RegionID
WHERE region.RegionID = '$regionsId'
  AND attractions.RegionID = '$regionsId'
GROUP BY region.RegionID";

Answer: This is a bit long for a comment.  SQL will return values in a table format with all "cells" completely filled in:
region     attraction
   A          1
   A          2
   A          3
   B          1
   B          5

If you want it in this form:
   A           1,2,3
   B           1,5

Then the database is appropriate:
SELECT r.*, group_concat(a.AttractionId)
FROM region r LEFT JOIN
     attractions a
     ON r.RegionID = a.RegionID
WHERE r.RegionID = '$regionsId'
GROUP BY r.RegionID;

If you want it in this form:
region     attraction
   A          1
              2
              3
   B          1
              5

Then you should do the work in the application layer.  It is possible to set this up in the database, but it "violates" the nature of SQL in dealing with tables.  And, it is pretty easy to do by looping through the results as you display them.
Answer: simplest way to go would be to add order by RegionName to your query and then, change your code to watch for region change and display it only when change happens, like this:
$prevRegionName = ''; // fill variable with something that won't be matched in first comparison

while ($row = mysql_fetch_assoc($result)) {

    $currentRegionName = $row['RegionName']; // push current region to variable
    if ($currentRegionName != $prevRegionName) echo $row['RegionName'];  // print region only if it changed

    echo "" .  "
" .
          $row['Name']  .
           "
" .

          "

         ";

    $prevRegionName = $currentRegionName; // save current region to compare it in next interaction
    }

Comment: if you think my answer is the one you were looking for, please mark it as one.


How can I edit or remove the bounding box label text in YOLO (V4)?

Question: I want to edit the bounding box label to show only the probability of detection and not the class label, How shall I do this?
I found a file called image.c in darknet/src which I think is where my edits need to be made.
But there are multiple functions in it that seem relevant for this task and I'm not sure which one to edit, and how to edit to get what I want. The code in image.c in quite long, hence kindly refer to this link (official darknet repo) where the code I'm referring to is available.
I tried editing the function void draw_detections at line 465 by simply changing the code at line 511 to printf("%s: %.0f%%", " ", prob * 100);, ran the !make command but the labels were still present in detection.
Answer: Finally found how to do this:
Locate the file darknet/src/image.c
Delete lines of code at 436
strcat(labelstr, names[selected_detections[i].best_class]);

and from line 441 to 446
for (j = 0; j < classes; ++j) {
    if (selected_detections[i].det.prob[j] > thresh && j != selected_detections[i].best_class) {
        strcat(labelstr, ", ");
        strcat(labelstr, names[j]);
    }
}

Make sure to rebuild the darknet in the project (!make)
Note:These changes will erase out if the darknet repository is cloned again.
Comment: If you want to actually change the labels (to another language for example) you can edit the file `darknet/data/coco.names`
Answer: You are using alexyAB model in your project .go to the image_opencv.cpp file and find draw_detections_cv_v3 function after that find this line:
 strcat(labelstr, names[j]);

change to:
strcat(labelstr, "");

Comment: Made the suggested changes inside the function, ran the !make command, but still showing the class labels. This didn't do anything. (There are two lines of 'strcat(labelstr, names[j]);' in the given function, I changed both)


What is it called to classify easy inputs before hard ones?

Question: For classifying a lot of inputs, it may be useful to handle the more unambiguous cases first and learn from them before tackling the harder ones. This is certainly how I personally grade student work; the idea must be ancient.
What is it called to classify instances from easy to hard? I thought it would be a kind of reinforcement learning, but I'm having trouble framing this basic idea in the language of RL, as a balance between exploitation and exploration.
Answer: The only name I have heard for this principle comes from the legal maxim that "Hard cases make bad law".  This is a very well-known principle of legal analysis that has been popularly expressed in case law for almost two-hundred years.  The reasoning behind this principle is that one is able to induce rules (i.e., classify) more effectively by first looking at simple unambiguous cases, and inducing appropriate rules from these --- the attempt to induce rules from difficult cases is likely to produce "bad" rules.
Although this is a legal maxim, the underlying reasoning for the principle is effectively a principle of inductive reasoning, so it does indeed pertain to statistical inference and classification.  (So you have come to the right place to ask your question --- and as a handy coincidence, your respondent is also a trained lawyer, thus recognising the applicable legal maxim.)  It is probably possible to state the underlying principle you have put forward in the language of statistical inference and inductive reasoning, but I have not heard a specific name for it in this context.
There is no specific name for this principle in a statistical context, since it is just an inherent aspect of the fact that classifications of simple cases are more accurate than classifications of ambiguous/hard cases.  In a statistical context, there is no temporal rule saying that you classify the easy cases before the hard cases, and things tend instead to be done simultaneously, through a model that looks at the totality of all evidence for all casees.  Nevertheless, it is true that more "training" information in a model comes from the simple cases, so then general thrust of what you are talking about is present in a statistical context.
Comment: +1, thanks for the legal context!


install from fork requirements not from source requirements

Question:
the source has a requirement as follows
  "require": {
    "php": ">=5.3.2",
    "symfony/framework-bundle": "~2.1",
    "cboden/Ratchet": "0.2.*"
},

in my fork it is like this
"require": {
        "php": ">=5.3.2",
        "symfony/framework-bundle": "~2.1",
        "cboden/Ratchet": "0.3.*"
    },
When I install from my fork with composer , it always says that it requires cboden/Ratchet": "0.2.* , but I want to work with cboden/Ratchet": "0.3.*
can you help
Answer: Assuming that symfony/framework-bundle effectively requires all Symfony components to be of version 2.1, I have bad news for you: cboden/ratchet version 0.3 requires some Symfony components of version 2.2.
You have to upgrade the Symfony version you are using to make it work.
Comment: I have symfony 2.4 , is that ok ?


Can't find installed gems

Question: I am very new to ruby, and am using Ubuntu , I installed ruby last week and have been using it ever since. But when I decided to start studying rails I realised the rails server will not start, I decided to reinstall ruby, and then rails, which I did successfully.
But now when I install a ruby gem, I do not see it, not even when I type gem list on the terminal, it also throws an error when I try to run it in a program. I am very frustrated and do not know what to do..
Comment: Does `ruby -v` return a version? What kind of error it throws?
Comment: yes ruby -v returns "ruby 2.2.1p85 (2015-02-26 revision 49769) [x86_64-linux]
"
Comment: What is the error you see when running `gem list`?
Comment: no error, only when I try to use the gem that I installed, it tells me that require cannot load such gem
Comment: You do use Gemfile and run your command with `bundle exec`, right? Although this is not strictly necessary it takes care of dependencies.
Comment: naa, I doubt I know how to use Gemfile , I am very new to ruby, so I do not know what that is
Comment: Take a look at the [bundler docs](http://bundler.io/gemfile.html). Otherwise it seems that your ruby process cannot find the gem you want because the path you supply in `require` resolves to something else than the correct one.
Comment: Consider using https://rvm.io right from the start. It basically allows you to install different ruby versions (and gems for that versions) in your home-folder, so you do not need root permissions and can "safely" play around.
Comment: Are you using RVM? RVM takes care of gem installs if you have RVM, and installs gems per user, so using `sudo gem install ` installs the gem for root only, not your user.
Answer: Try installing RVM instead of ruby directly, this will install the required setting and it will be easier to beginners.
https://rvm.io/rvm/install

Can't find installed gems


Show that two metrics are equivalent.

Question: I want to show that the two metrics are equivalent.
Suppose we have a metric space $X \times Y$. Two metrics are defined as:
$d_{X \times Y}((x, y), (x', y')) := \max\{d_X(x, x'), d_Y(y, y')\}$
$d'_{X \times Y}((x, y), (x', y')) := d_X(x, x')+d_Y(y, y')$
Here is my attempt at proof:
Define $\tau$ to be the collection of open sets with respect to $d_{X \times Y}((x, y), (x', y'))$ . Also define $\tau*$ to be the collection of open sets with respect to $d'_{X \times Y}((x, y), (x', y'))$.
First, assume an open set $U \in \tau$. We want to show that $U \in \tau*$.
Since $U \in \tau$, $\forall (x, y) \in U$, $\exists p > 0$ such that $B_{p}^{d} (x, y) \subset U$.
Then $\forall (x, y) \in U$, $B_{p/2}^{d} (x, y) \subset U.$
Since $d_X(x,x') + d_Y(y, y') \leqslant 2 \cdot \max\{d_X(x, x'), d_Y(y, y')\}$,
If we set $r := 2 \cdot \max\{d_X(x, x'), d_Y(y, y')\}$ then
$B_{r}^{d'}(x,y) \subset B_{p/2}^{d} \subset U$.
As you can see, this reasoning is confusing, in fact I got confused writing this. I can kind of see the direction I should head to but this is not it. Can someone enlighten me?
Thanks.
If I get this part correct I think I can handle the converse.
Comment: Btw, remember that to prove two metrics are equivalent you can prove that there exist two constants $C_1,C_2>0$ such that $$C_1 d(x,y) \leq d'(x,y) \leq C_2 d(x,y)$$.
Answer: First prove that $d_{X\times Y}\leq d'_{X\times Y}\leq 2d_{X\times Y}$.
Then you can easily deduce that for any point $p$ in $X\times Y$ and any $r>0$, $B_r^{d}\subseteq (p)B_{2r}^{d'}(p)\subseteq B_{2r}^d(p)$. This proves the equivalence of the two metrics.
Answer: If $x,y$ are non negative, we have
$x+y \le 2 \max(x,y)$ and $\max(x,y) \le x+y$.
Hence
$d'_{X \times Y}((x, y), (x', y')) \le 2 d_{X \times Y}((x, y), (x', y'))$ and
$d_{X \times Y}((x, y), (x', y')) \le d'_{X \times Y}((x, y), (x', y'))$.
Answer: Why make this so complicated when you are almost done:
See that if we allow $(a,b)\in \operatorname{B_d^p(x,y)}$(I have kept your notations intact);
Then $d((a,b),(x,y))<p\implies d_X(a,x)<p;d_Y(b,y)<p\implies d^{'}((a,b),(x,y))<2p$
Then choose $q=p$ then we have $(a,b)\in \operatorname{B_{d^{'}}^q(x,y)}\subseteq \operatorname{B_d^p(x,y)}$
Similarly the converse.

Show that two metrics are equivalent.


Estimation of a probability of marginal values of a random variable

Question: My question is related with this question on combinatorics of 0-1-matrices from MO. Trying to obtain a (asymptotic) lower bound for $\alpha(n)$ by probabilistic approach (see, for instance, "The probabilistic method" by N. Alon and J. Spencer), I encountered the following problem.
Given a natural number $n>1$, find a bound $\alpha (n)>0$ (the bigger, the better) satisfying the following condition.
If for each positive integer $k$ and each sequence $m_1, \dots m_k$, where each $m_j$ is an integer from $0$ to $n$, we define mutually independent random variables $x_1,\dots, x_k$ such that for each $j$ a variable $x_j$ equals $1$ with probability $m_j/n$ and equals $0$ with probability $1-m_j/n$ then
$$P(x_1+\dots+x_k<\lfloor \alpha(n)(m_1+\dots+m_k)/n \rfloor)<1/n.$$
I hope that we can make $\alpha(n)\ge c/\log n$ for some $c>0$ and all sufficiently large $n$.
Thanks.
Answer: It seems the following
My probabilistic approach failed. To see this put $$x=x_1+\dots +x_k$$ and $$\mu=E(x)=\frac{m_1+\dots+m_k}n.$$ By Multiplicative Chernoff Bound, for any $0<\alpha<1$ we have
$$P(x\le \alpha\mu)\le e^\frac{-(1-\alpha)^2\mu}2.$$
which suggests $$ e^\frac{-(1-\alpha)^2\mu}2<\frac 1n,$$
which implies $$\alpha<1-\sqrt{\frac{2\ln n}{\mu}},$$
which is useless for $\mu\le 2\ln n$.
This has a simple explanation for the initial question from MO: if in our matrices are small number of $1$'s and a large number of $0$'s then a random choice is a bad choice for a big sum.


javascript load events not working with multiple IDs

Question: how to load comments using  load event function for multiple ids
html code
          <div id="user2<?php echo $d['qid'];>">
          comments code

JS CODE
  setInterval(function(){

            $("#user2").load('test2.php #user2'+qid).fadeIn(1000);

      },1000);

please help me  I  have tried many times not working
Comment: What are you asking? What does your HTML look like? Are you getting errors? This question doesn't have enough information for users to help you.
Comment: @luxdvie  Whats you problem  Id="qid"  and  Conment code
Comment: Update your answer to include the HTML. Based on your question it's not clear what you're trying to accomplish. Be a little more descriptive and someone can probably lead you in the right direction.
Comment: @luxdvie see my updated code
Answer: If your HTML looks like this:

You could load like this:
for (i = 1; i < 4 i++) {
  $("#user2"+i).load("test2.php").fadeIn(1000);
}


How can I remove variables and any usage of them from my project? Intellij

Question: The alt + delete way remove only definition of variable but I must remove all  occur of my variable and I couldn't find how to do that.
Comment: That wouldn't really make sense... how would you want IDE to know that you use a variable outside the local scope when it was defined?
Answer: There is no way to do this automatically. For example, if the variable is passed as a parameter to a method, there is no way for an IDE to automatically remove that usage while maintaining correctness of the code.


How to use string.format with string array in powershell

Question: I want to output a formated string to console. I have one string variable and one string array variable.
When I do this:
$arr = "aaa","bbb"
"test {0} + {1}" -f "first",$arr

The output is this:
test first + System.Object[]

But I need output to be:
test first + aaa,bbb

Or something similar...
Answer: Several options:

Join the array first, so you don't rely on the default ToString() implementation (which just prints the class name):
PS> 'test {0} + {1}' -f 'first',($arr -join ',')
test first + aaa,bbb

Use string interpolation:
PS> $first = 'first'
PS> "test $first + $arr"
test first + aaa bbb

You can change the delimiter used by setting $OFS, which by default is a space:
PS> $OFS = ','
PS> "test $first + $arr"
test first + aaa,bbb

You can get the same result (including the note about $OFS) with
PS> 'test {0} + {1}' -f 'first',(''+$arr)
test first + aaa bbb

This forces the array to be converted into a single string first, too.
Comment: `-f` is just a straightforward convenience for `String.Format()`, it uses the same semantics as .NET in that regard. String interpolation is a tricky subject, as it converts objects to string using the invariant culture (apparently); it will also join arrays using `$OFS`. Generally I don't feel confident right now to accurately summarise the exact differences. Something fun: `$a = (date),(date),(date); Write-Host $a; Write-Host "$a"`
Comment: Very nice! I would normally use string interpolation right away, but I just discovered -f operator for string.format and liked it so much I used it everywhere and got confused :)   This raises another question what is the difference in background processing of -f operator and string interpolation? Maybe some articles? Thanks


Polynomial interpolation but with a perfect fit on certain data points

Question: When given $n$ data points $(x_1,y_1),\ldots, (x_n,y_n)$ (where $x_i\neq x_j$ for $i\neq j$) we can use the least squares method to obtain a polynomial $f$ of degree $m$ (with $m<n$) such that the sum of squared errors is minimized. It is known that in general we only have $f(x_i)\approx y_i$ instead of equality. Is there some way to modify the least squares method (or any other approximation technique) to fit certain data points, say for example the first and final data point, perfectly, that is $f(x_1)=y_1$ and $f(x_n)=y_n$, while still minimizing the squared sum of the remaining errors?
Comment: First off, welcome to MSE. Secondly, you might be able to increase the degree by 2 in order to have 2 more degrees of freedom, I suspect that you may be able to then use these two extra degrees of freedom to do that, though to be honest I haven't tried.
Answer: Given a $N$ degree fitting polynomial $P_N(x)=\sum_k a_k x^k$ and a data set $D=\{x_j,y_j\},\ \ \ j=1,\cdots,M$ we can solve
$$
\min_{a_k}\sum_{j=2}^{M-1}\left(\sum_{k=0}^N a_k x_j^k-y_j\right)^2\ \ \ \text{s. t.}\ \ \sum_{k=0}^N a_k x_{\nu}^k-y_{\nu} = 0,\ \ \nu = \{1,M\}
$$
This is can be solved by using the Lagrange multipliers technique.


Multiple Vlookups on main dataframe from multiple sources?

Question: I have a master data that I wish to do vlookups for additional columnns.
Here's what I am aiming to achieve:
Master Data:
Ctry    Product
CN         BTL
VN         HP

Ref table 1:
Ctry    Country
AU      Australia
CN      China
VN      Vietnam

Ref table 2:
ProductID  Product
BTL        Bottles
HP         Handphone
PRN        Printer

How do I achieve it to combine all into the Master Data as below?
Expected Output:
Ctry    Product  Country    Product
CN         BTL    China     Bottles
VN         HP     Vietnam   Handphone

My below codes only references 1 table and I'm stuck, how do I go about adding the additional columns to the existing Master Data Sheet?:
import pandas as pd

# IMPORT DATA

df1 = pd.read_excel("Masterdata.xlsx")
df2 = pd.read_excel("Ref_table_1.xlsx")

Left_join = pd.merge(df1,df2, on = 'Ctry', how ='left')

Left_join.to_excel("Output.xlsx", index = False)

Comment: do another pd.merge for ref table 2? `pd.merge(Left_join, df3, left_on="Product", right_on="Product_id")`
Answer: You can use this and eliminate columns not required:
import pandas as pd

df1 = pd.DataFrame({'Ctry': ['CN', 'VN'], 'Product': ['BTL', 'HP']})
df2 = pd.DataFrame({'Ctry': ['CN', 'VN', 'AU'], 'Country': ['Australia', 'China', 'Vietnam']})
df3 = pd.DataFrame({'ProductID': ['BTL', 'HP', 'PRN'], 'Product': ['Bottle', 'HandPhone', 'Printer']})

m1 = df1.merge(df2, how='left')
m2 = m1.merge(df3, how='left', left_on='Product', right_on='ProductID')
print(m2)


Calculate the area bounded by two curves via double integration

Question: I need to find the area of the middle part bounded (or between) 2 curves:
$ x²+y²=1$ and $ 4x²-y²=1$.
I have the graphic of the middle part (the part, which I need to calculate the area for it), but I can't understand, do I need to solve this in polar system or Cartesian?
I think, that I can move to Cartesian, but I don't know which function to integrate.
In Cartesian system I'm solving this integral:
$$\int_{-\frac{\sqrt{1+y^2}}{2}}^{\frac{\sqrt{1+y^2}}{2}}\int_{-\sqrt{1-x^2}}^{\sqrt{1-x^2}}1\ dx\ dy$$
But I'm getting a function of x or y, not a number.
And in polar system I can't understand which function to use, I know that $\ r$ will vary from $\ 0$ to $\ 1$ and $\theta$ will vary from from $0$ to $\ 2\ π$.
Comment: **Comments have been [moved to chat](https://chat.stackexchange.com/rooms/150400/discussion-on-question-by-mohaboko-calculate-the-area-bounded-by-two-curves-via); please do not continue the discussion here.** Before posting a comment below this one, please review the [purposes of comments](/help/privileges/comment). Comments that do not request clarification or suggest improvements usually belong as an [answer](/help/how-to-answer), on [meta], or in [chat]. Comments continuing discussion may be removed.
Answer: I can't see how to do this without breaking this integral in two.

In Cartesian, you can either integrate with respect to y first and integrate the caps separate from the area bounded by the parabola.
Or, with respect to y first and do the middle bounded by the circle separate from what is bounded at one end by the parabola and at the other by the circle.
In either case, you need to find the points where the curves intersect.
Or you can do this in polar

It will still be two integrals.
Where do the curves intersect?
$x^2 + y^2 = 1\\
4x^2 - y^2 = 1\\
5x^2 = 2\\
x = \sqrt {0.4}\\
y = \sqrt {0.6}$
$4\int_{0}^{\sqrt{0.6}}\int_0^{\frac {\sqrt {1+y^2}}{2}} \ dx \ dy + 4\int_{\sqrt{0.6}}^{1}\int_0^{\sqrt {1-y^2}} \ dx \ dy$
or
$4\int_0^\frac 12 \int_0^{\sqrt{1-x^2}}\ dy\ dx + 4\int_{\frac 12}^{\sqrt{0.4}} \int_{\frac {\sqrt {1+y^2}}2}^{\sqrt{1-y^2}} \ dx\ dy$
or, in polar.
$4\int_0^{\arctan \sqrt {\frac 32}}\int_0^{\frac {1}{4\cos^2\theta + \sin^2\theta}} r\ dr\ d\theta + 4\int_{\arctan \sqrt {\frac 32}}^{\frac {\pi}{2}}\int_0^1 r\ dr\ d\theta$
Comment: Thank you, but I couldn't find the functions of these 2 integrals
Comment: Can you help me please?
Comment: How these 2 integrals will be?
Comment: Thank you. But can you tell from where we got 0 and 1/2 ?
Answer: Hint: The area of one of the unshaded parts is given by
$$\int_{-\sqrt{\tfrac35}}^{\sqrt{\tfrac35}} \int_{\tfrac{\sqrt{1+y^2}}2}^{\sqrt{1-y^2}} dx \, dy$$
which can be used to determine the desired area.
Comment: Thanks. But please can you explain from where sqrt(3/5) and -sqrt(3/5)?
Comment: They are the $y$-coordinates of the intersections of the circle and hyperbola in the first/fourth quadrants of the plane. Solve for $y$ such that $x=\sqrt{1-y^2}$ and $2x=\sqrt{1+y^2}$.
Comment: So, Pi - this area, right?
Comment: Not quite, this double integral only gives you the area of one of the unshaded regions.
Comment: Then, Pi - 2 * this area
Comment: Yes, that's correct
Comment: Well. Thank you


How can I find Python Built-in functions?

Question: I went through python 2x and 3x docs. It only mentions the following -

The Python interpreter has a number of functions and types built into it that are always available.

How and where are these built-in methods free floating?
Comment: Python supports the OO paradigm but does not impose it. You can write in a plain procedure style or even functional, etc.
Comment: in the Lib folder .... (for most of them) ... the ones that are built into python itself can be browsed by checking out the source on github
Comment: "since python is OO based" Nope.
Comment: Python is **not** OO-based. It *supports* OO, but that does not make it OO-based.
Comment: "everything should be defined inside objects" nope.
Answer: Python is not object oriented based,it can also be functional.However if you want to look for the functions and their methods you can type in the interpreter
<code>>>>dir(__builtins__)
</code>
This gets a list of built-in functions and variables in the directory,also you can use work around by typing
<code>>>>help('module')
</code>
or
<code>>>help(function-name)
</code>


PHP retorno função

Question: Apesar da variável url estar retornando conteúdo, conforme VAR_DUMP, o código abaixo sai pela mensagem "URL inexistente". Por que isso? Onde estou pecando no código?
public function getUrlcliente($cliente_id) {

        $parametro = "cliente_id=" . (int)$cliente_id;
        $url_externa = $this->db->query("SELECT DISTINCT query as indice, keyword as url FROM url_alias WHERE query = '" . $parametro . "'");

        if (empty($url_externa)) {
            $url = "Erro - URL amigável não cadastrada";
        }
        else {
            foreach ($url_externa as $row) {
                var_dump($row);
                if (isset($row->url)) {
                    $pos = strpos($row->url, "www");
                    if ($pos == false) {
                    }
                    else {
                        $url = $row->url;
                        break;
                    }
                }
                else {
                    $url = "Url inexistente";  ---> ele está saindo aqui
                }
            }
        }

        if ($url_externa->num_rows) {
                    return $url;
                }
        else
                {
                    return "Erro-Url inexistente";
                }
}

o VAR_DUMP está retornando isso ---->

int(1) array(2) { ["indice"]=> string(13) "cliente_id=42" ["url"]=> string(21) "http://www.uol.com.br" } array(1) { [0]=> array(2) { ["indice"]=> string(13) "cliente_id=42" ["url"]=> string(21) "http://www.uol.com.br" } }

Percebam que o objetivo da função é retornar apenas uma string, a URL, não quero que retorne um array.
Comment: Já tentou tentou pegar o valor assim `$row["url"]` ?
Comment: @Augusto era isso. Obrigado.
Answer: Segue a solução abaixo pegando o resultado da array $row
public function getUrlcliente($cliente_id) {
    $parametro = "cliente_id=" . (int)$cliente_id;
    $url_externa = $this->db->query("SELECT DISTINCT query as indice, keyword as url FROM url_alias WHERE query = '" . $parametro . "'");

    if (empty($url_externa)) {
        $url = "Erro - URL amigável não cadastrada";
    } else {
        foreach ($url_externa as $row) {
            if (isset($row['url'])) {
                $pos = strpos($row['url'], "www");
                if ($pos !== false) {
                    $url = $row['url'];
                    break;
                }
            } else {
                $url = "Url inexistente";  ---> ele está saindo aqui
            }
        }
    }

    if ($url_externa->num_rows) {
        return $url;
    } else {
        return "Erro-Url inexistente";
    }
}

Comment: MSergio se a solução do Augusto resolver seu problema, pode marcar a resposta como aceita depois, de forma a aparecer como resolvida na listagem do site. Quando for coisa que admite várias respostas, é sempre bom esperar um tempo maior, para escolher a mais adequada, mas nesse caso aqui acho que não tem muito o que mudar.

PHP retorno função


Application Of Derivatives - tangent questions

Question: A curve in the co-ordinate plane is given by the parametric equation $x = t^2 + t + 2$ and $y = t^2− t + 2$ where $t \geq 0$. The number of straight lines passing through the point $(2, 2)$ which are tangent to the curve is/are?
I found the slope of tangent $\frac{dy}{dx}= 2t-\frac{1}{2t}+1$
and equation of the tangent as $y-(t^2-t+2)=(2t-\frac{1}{2t}+1)(x-(t^2+t+2))$
Comment: What have you tried?
Comment: @BornilBuragohain: Please edit your question to include that work.
Comment: found the slope of the tangent . found the equation. now i am unable to proceed further.
Comment: I'm sorry , what do i need to include?
Comment: You need to include the slope, equation you found. You can do so by clicking on the 'edit' button that's in the bottom left corner of the post just above your profile picture.
Comment: i included that . please help me now.
Comment: A curve given parametrially is a function mapping a single variable $t$ to a point in the $x,y$ plane. Your curve is $w(t)=(t^2+t+2,t^2-t+2).$ To get the derivative one just takes the derivative of the components (separately) of the curve. You did not do that.
Answer: Since you are not able to catch the hint, here is the complete  solution
The slope of the tangent at the point $'t'$ would be given by
$\frac{dy}{dx}=\frac{\frac{dy}{dt}}{\frac{dx}{dt}}=\frac{2t-1}{2t+1}$
The point $(2,2)$ lies on the curve which corresponds to $t=0$.
Therefore $\frac{dy}{dx}$ at $(2,2)$ is $-1$ ( By putting $t=0$). Now you can find equation of tangent at point $(2,2)$ which is  $y-2=(-1)(x-2)$.
There would be only one tangent passing through the point $(2,2)$ because it lies on the given curve and derivative at this point exists.


How to use PHPSpreadsheet in CodeIgniter 3 to read data from Excel (.xlsx and .xls) file?

Question: Recently in one of my CodeIgniter based project, I need to read data from Excel file ( .xlsx and .xls ) and insert those data into MySQL. Unfortunately, I did not use PHPSpreadsheet before (as I did not require to work with Excel :( ).
So far what I did was, download the PHPSpreadsheet from Github and extract it to the root directory of my CodeIgniter Project.

PHPSpreadsheet in CodeIgniter root directory.

File Structure of PHPSpreadsheet.
So far I've tried to import the official docs example into my CI apps:
<code><?php
    defined('BASEPATH') OR exit('No direct script access allowed');
    use PhpOffice\PhpSpreadsheet\IOFactory;
    class Welcome extends CI_Controller {
       function __construct() {
           parent::__construct();
       }

       public function index()
       {
           $inputFileType = 'Xlsx';
           $inputFileName = 'test.xlsx';
           $reader = \PhpOffice\PhpSpreadsheet\IOFactory::createReader($inputFileType);
    /**  Load $inputFileName to a Spreadsheet Object  **/
          $spreadsheet = $reader->load($inputFileName);
          print_r( $spreadsheet );
    }
}
</code>
But it shows the following error!!

Can anyone tell me how can I use PHPSpreadsheet in CodeIgniter to read data from Excel file and store them into MySQL database?

Thanks
Comment: You need to autoload the library using a psr4 autoloader like the one from fig if you google. You cannot load namespaces libraries as you would a ci library.
Comment: Did you use Composer to install? It is easiest if you do.
Comment: Thanks, @DFriend
Answer: The easiest way to include PhpSpreadsheet is to use Composer - the documentation at https://phpspreadsheet.readthedocs.io/en/latest/ explains how to do this.
Otherwise you will need a PSR4 autoloader to load the class specified by your use statement or to include the files yourself. If you include files yourself, to read an Excel file you will need to include PhpSpreadsheet/src/PhpSpreadsheet/IOFactory.php
Comment: I am sorry but the link you provided appears to be dead.
Comment: Since the link is dead just Google 'phpspreadsheet'.


Hilbert class field of a quadratic field whose class number is 3

Question: Is the following proposition true?
If yes, how would you prove this?
Proposition
Let $f(X) = X^3 + aX + b$ be an irreducible polynomial in $\mathbb{Z}[X]$.
Let $d = -(4a^3 + 27b^2)$ be the discriminant of $f(X)$.
Let $K = \mathbb{Q}(\sqrt{d})$.
Let $L$ be the splitting field of $f(X)$ over $\mathbb{Q}$.
Suppose the following conditions hold.
(1) $|d| = |4a^3 + 27b^2|$ is a prime number.
(2) The class number of $K$ is 3.
(3) $f(X) \equiv (X - s)^2(X - t)$ (mod $d$), where $s$ and $t$ are distinct rational integers mod $d$.
Then $L$ is the Hilbert class field of $K$.
Examples
Each of the following polynomials of negative discriminants satisfies the above conditions.
(1) $f(X) = X^3 - X + 1 \equiv (X - 13)^2(X - 20)$ (mod 23)
(2) $f(X) = X^3 + X + 1 \equiv (X-3)(X-14)^2$ (mod 31)
(3) $f(X) = X^3 + 2X + 1 \equiv (X - 14)^2(X - 31)$ (mod 59)
I could not find a polynomial of positive discriminant satisying the above conditions.
Comment: What you want is Acta Arithmetica, volume 57 (1991), pages 131-153, Kenneth S. Williams and Richard R. Hudson, Representation of primes by the principal form of discriminant $-D$ when the classnumber $h(-D)$ is $3.$ I have a pdf.
Comment: Do you know the standard argument that the splitting field of example 1 is the Hilbert class field of $\mathbb{Q}(\sqrt{-23})$? You should try to mimic it in this generality and see if something goes wrong. Maybe negative discriminant comes up so that the real place of the conductor ramifies. I don't remember, but that seems to me the only thing that could go wrong. My guess is it is true.
Comment: @WillJagy, I would appreciate it very much if you send me the pdf. Regards,
Comment: Done. ${}{}{} $
Comment: @WillJagy Thank you so much.
Comment: @Matt I don't know the standard proof of the case $Q(\sqrt{-23})$. Regards,
Answer: You can be even more lenient on the assumptions.
Proposition.
If $K$ is a cubic number field for which $\Delta_K=\Delta(\mathcal{O}_K)$ is squarefree then $3|h(\mathbb{Q}(\sqrt{\Delta_K)})$.
Remark: note that when $K=\mathbb{Q}(\alpha)$ with $\alpha$ a root of an irreducible monic cubic polynomial $f\in\mathbb{Z}[X]$ with $\Delta(f)$ squarefree, then the above hypotheses are satisfied: we have
$$
\Delta(f)=\Delta(\mathbb{Z}[\alpha])=[\mathcal{O}_K:\mathbb{Z}[\alpha]]^2\cdot\Delta_K,
$$
from which we see that $\mathcal{O}_K=\mathbb{Z}[\alpha]$ and $\Delta_K=\Delta(f)$.
Proof. As $\Delta_K$ is not a square in $\mathbb{Q}$ it follows that the normal closure $N$ of $K/\mathbb{Q}$ has degree $6$ over $\mathbb{Q}$ and that $[\mathbb{Q}(\sqrt{\Delta_K}):\mathbb{Q}]=2$. Then $N/\mathbb{Q}(\sqrt{\Delta_K})$ is an Abelian extension of degree $3$. I claim that it is also unramified, so that it is contained in the Hilbert class field of $\mathbb{Q}(\sqrt{\Delta_K})$, proving the proposition.
To see this, let $(r,s)$ be the signature of $K$. Since $r+2s=3$ we have either $(r,s)=(1,1)$ or $(r,s)=(3,0)$. When $(r,s)=(1,1)$ we have that $\mathbb{Q}(\sqrt{\Delta_K})$ is complex as $\mathrm{sign}(\Delta_K)=(-1)^s$ so it is unramified at the infinite primes. When $(r,s)=(3,0)$ we see that $K$ and $\mathbb{Q}(\sqrt{\Delta_K})$ are both totally real, hence their compositum $N$ is also totally real. Thus $\mathbb{Q}(\sqrt{\Delta_K})$ is unramified at the infinite primes in that case as well.
Now suppose that a finite prime $\mathfrak{p}$ of $\mathbb{Q}(\sqrt{\Delta_K})$ ramifies in $N$. As $N/\mathbb{Q}(\sqrt{\Delta_K})$ is Galois of prime degree, we must have that $\mathfrak{p}$ is in fact totally ramified in $N$. The ram-rel identity $efg=6$ for the extension $N/\mathbb{Q}$ yields that $3|e$ and by multiplicativity of the ramification index it follows that the rational prime $p$ lying under $\mathfrak{p}$ ramifies totally in $K$, say $p\mathcal{O}_K=\mathfrak{q}^3$. But this implies that $\mathfrak{q}^2|\mathfrak{D}_K$, and hence upon taking norms that $p^2|\Delta_K$, which is a contradiction and hence $N/\mathbb{Q}(\sqrt{\Delta_K})$ is unramified at the finite primes.
Answer: The above proposition is a special case of the following proposition.
Proposition
Let $f(X)$ be a monic irreducible polynomial of degree 3 in $\mathbb{Z}[X]$.
Let $d$ be the discriminant of $f(X)$.
Let $K = \mathbb{Q}(\sqrt{d})$.
Let $L$ be the splitting field of $f(X)$ over $\mathbb{Q}$.
Suppose the following conditions hold.
(1) $|d|$ is a prime number.
(2) The class number of $K$ is 3.
(3) $f(X) \equiv (X - s)^2(X - t)$ (mod $d$), where $s$ and $t$ are rational integers and $s$ and $t$ are distinct mod $d$.
Then $L$ is the Hilbert class field of $K$.
Proof:
Since the degree of $f(X)$ is 3, $[L : \mathbb{Q}] \leq 6$.
Since $f(X)$ is irreducible, $3|[L : \mathbb{Q}]$.
By (1), $[K : \mathbb{Q}] = 2$.
Hence $2|[L : \mathbb{Q}]$.
Hence $[L : \mathbb{Q}] = 6$.
Hence $[L : K] = 3$.
Therefore, by (2), it suffices to prove that every prime ideal of $K$ is unramified in $L$.
Let $Q$ be a prime ideal of $K$ lying over a prime number $q \neq p$, where $p = |d|$.
By the application of the proposition of this question, $q$ is unramified in $L$.
Hence $Q$ is unramified in $L$.
Let $P$ be a prime ideal of $K$ lying over $p$.
It remains to prove that $P$ is unramified in $L$.
Let $\theta$ be a root of $f(X)$ in $L$.
Let $M = \mathbb{Q}(\theta)$.
Since $f(X)$ is irreducible, $[M : \mathbb{Q}] = 3$.
Hence $[L : M] = 2$.
We denote by $\mathcal{O}_K, \mathcal{O}_M, \mathcal{O}_L$ the rings of integers in $K$, $M$, $L$ respectively.
Let $D_M$ be the discriminant of $M$.
It is well known that $d = k^2 D_M$ for some rational integer $k$.
Since $k^2 = 1$ by (1), $d = D_M$.
Hence $\mathcal{O}_M = \mathbb{Z}[\theta]$.
It is is well known(e.g. Milne's online course note) that $p\mathcal{O}_M = \mathfrak{p}^2\mathfrak{q}$ by (3), where $\mathfrak{p}$ and $\mathfrak{q}$ are distinct prime ideals of $\mathcal{O}_M$.
Since $[L : M] = 2$, We have the following patterns of the prime decompositions in $L$.
(1) $\mathfrak{p}\mathcal{O}_L = \mathfrak{P}$.
(2) $\mathfrak{p}\mathcal{O}_L = \mathfrak{P_1}\mathfrak{P_2}$, where $\mathfrak{P_1} \neq \mathfrak{P_2}$.
(3) $\mathfrak{p}\mathcal{O}_L = \mathfrak{P}^2$.
(1)' $\mathfrak{q}\mathcal{O}_L = \mathfrak{Q}$.
(2)' $\mathfrak{q}\mathcal{O}_L = \mathfrak{Q_1}\mathfrak{Q_2}$, where $\mathfrak{Q_1} \neq \mathfrak{Q_2}$.
(3)' $\mathfrak{q}\mathcal{O}_L = \mathfrak{Q}^2$.
Since $L/\mathbb{Q}$ is Galois, each ramification index of prime ideals of $L$ lying over $p$ is the same. Hence only the combination of (2) and (3)' is possible.
Hence $p\mathfrak{O}_L = \mathfrak{P_1}^2\mathfrak{P_2}^2\mathfrak{Q}^2$.
Since $p$ ramifies in $K$, $p\mathfrak{O}_K = P^2$.
Hence by the above result, $P$ is unramified in $L$.
QED
Comment: As a reminder, you should specify that $p=|d|$, in order not to confuse the reader. Regards.
Comment: @awllower I edited the answer. Thanks.
Comment: Good to see that. :D