What teams have won the Champions League undefeated?

Question: With the Champions League finals coming this weekend, I was wondering if any team has ever won the Champions League or the European Cup without ever losing a game in both the Qualification rounds and Elimination rounds.
If it is a common occurrence, has any team ever won without conceding a goal, or accomplished that feat twice in a row?
Comment: BTW I thought that the term *clean sheet* is more frequently used to winning a match without conceding a goal. See [Wikipedia](https://en.wikipedia.org/wiki/Shutout#Association_football) and [Wiktionary](https://en.wiktionary.org/wiki/clean_sheet).
Answer: Ten teams have won the European Cup/Champions League unbeaten, of which four have achieved this twice:

Liverpool had 6 wins and 3 draws in 1980–81 and 7 wins and 2 draws in 1983–84.
Milan had 5 wins and 4 draws in 1988–89 and 7 wins and 5 draws in 1993–94.
Ajax had 7 wins and 2 draws in 1971–72 and 7 wins and 4 draws in 1994–95.
Manchester United had 5 wins and 6 draws in 1998–99 and 9 wins and 4 draws in 2007–08.

The other clubs have achieved it on one occasion:

Inter Milan had 7 wins and 2 draws in 1963–64.
Nottingham Forest had 6 wins and 3 draws in 1978–79.
Red Star Belgrade had 5 wins and 4 draws in 1990–91.
Marseille had 7 wins and 4 draws in 1992–93.
Barcelona had 9 wins and 4 draws in 2005–06.
Bayern Munich had 11 wins and 0 draws in 2019–20.


Call function from another controller using Events in AngularJS

Question: I am new bie with AngularJS.
I am trying to call function from another controller.
I found that there are sever ways to do that.
1) Shared Service
2) Using Events
Here is the link that i already checked out.
Can one controller call another
How do I inject a controller into another controller in AngularJS
I think that using events is better approach. Apart from that i think when we use $rootscope it is not destroying event reference right?

var myModule = angular.module('myapp', []);

myModule.controller('otherController', function($scope) {
  $scope.$on('ShowDialog', function(event) {
    alert("hello");
  });
});

myModule.controller('myController', function($scope) {
  $scope.OnClick = function() {
    alert("Done");
    $scope.$emit('ShowDialog');
  }
});

<input type="button" ng-click="OnClick()" value="Say Hello!" />

Please let me know what i am missing? And what is the best way to do it?
Comment: services is the most preferred way... google and you will get lot of links explaining why
Comment: For your reference since the question asked is similar: http://stackoverflow.com/questions/29467339/how-to-call-function-in-another-controller-in-angularjs?rq=1
Answer: There's a couple reasons why your snippet doesn't work.
You don't instantiate otherController so there's no way it will execute any code at all. So you need to add a div with ng-controller="otherController"
Now that you have an instance of the 2 controllers, to communicate with $scope events ($emit, $broadcast, $on) they need to be nested because scope events depend on the hierarchy of elements.
$scope.$emit will register events to parent controllers.
$scope.$broadcast will register events to child controllers.
You can manipulate the snippet below by moving the nested div out and changing events type.

var myModule = angular.module('myapp', []);

myModule.controller('otherController', function($scope) {
  $scope.$on('ShowDialog', function(event) {
    alert("hello");
  });
});

myModule.controller('myController', function($scope) {
  $scope.OnClick = function() {
    alert("Done");
    $scope.$broadcast('ShowDialog');
  }
});

    <input type="button" ng-click="OnClick()" value="Say Hello!" />

If the way your application is built prevents you from nesting controllers, you can use $rootScope events.
They work like this:
$rootScope.$broadcast will broadcast events to the rootScope as well as the scope. This will make your code messy real quick because any scope of any controller can watch for this event.
$rootScope.$emit is to be preferred as it registers the event application wide and makes it available to the rootScope only. ($rootScope.$on)
This said, it is considered bad practice to use $scope or $rootScope events for simple data manipulation that does not make sense application wide.
For example you want to tell your application that user has logged out, then it makes sense to broadcast it to the application as a whole.
But if you just want 1 controller to know some random data has been loaded, then use a service. (ex: the statistics controller doesn't need to know that a user has changed his profile picture)
It's considered bad practice because you will end up with a lot of events registered from different controllers, you will have conflicting event names and eventually it will be very hard to maintain.
If  you still want to stick to events, you should remember to unbind them or you will have memory leaks issues and other nasty bugs:
var unbind = $rootScope.$on('logout', function(event, data) {
    console.log('LOGOUT', data);
});
$scope.$on('$destroy', unbind); //when your controller is unloaded, unbind the events

Answer: the example you've posted, if you're asking why it's not working, it's because each controller has it's own scope. you're emitting 'ShowDialog' from myController and checking it in otherController. but ShowDialog will only be available in myController. that's the exact reason why we use emit on $rootScope, because it's golbal and can be accessed in any controller.
These are the few ways i know of to achieve what you're asking. take a look and let me know if it helps.


Segmentation fault while trying to change game state

Question: I'm making a state machine for switching game states (playing->menu->setup) in my game engine, but I'm getting a segmentation fault. I can change the game state fine from upper level, but how can I change the game state from within a game state?
Here's a minimal code example:
#include <iostream>
#include <vector>

class GameStateManager;

class GameState {
public:
    GameState(GameStateManager* StateManager) {
        StateManager = stateManager;
    };

    virtual ~GameState();

    virtual void update() = 0;

    GameStateManager* stateManager;
};

class GameStateManager {
public:
    GameStateManager();
    ~GameStateManager();

    void changeGameState(GameState* state) {
        if(!running) {
            running = true;
        }

        // Cleanup the current state
        if(!gameStates.empty()) {
            for(unsigned int i = 0; i < gameStates.size(); i++) {
                delete gameStates[i];
            }
            gameStates.clear();

            std::cout << "Cleaning up GameState" << std::endl;
        }

       // Store and initialize the new game state
       gameStates.push_back(state);
    };

    void update() {
        if(!gameStates.empty()) {
            gameStates.back()->update();
        }
    };

    std::vector<GameState*> gameStates;
    bool running;
};

class PlayState : public GameState {
public:
    PlayState(GameStateManager* stateManager) : GameState(stateManager) {};
    ~PlayState();

    void update() override {
        // On some flag, initiate the next level
        nextLevel();
    };

    void nextLevel() {
        stateManager->changeGameState(new PlayState(stateManager));
    };
};

int main() {
    GameStateManager stateManager;

    stateManager.changeGameState(new PlayState(&stateManager));

    while(stateManager.running) {
        for(unsigned int i = 0; i < 10000; i++) {
            std::cout << "Round: " << i << std::endl;

            // Segmentation fault here
            stateManager.update();

            // This works
            //stateManager.changeGameState(new PlayState(&stateManager));
        }
        stateManager.running = false;
    }
    return 0;
}

Comment: We don't know what `gameStates` is. It seems like a queue, but I can't tell how it's implemented.
Comment: gameStates is a standard std::vector of GameState*.
Answer: for some reason the stateManager is not being set in the GameState constructor.
so try this:
class GameState {
public:
    GameState(GameStateManager* StateManager) : stateManager(StateManager)
    {
    };

    virtual ~GameState();

    virtual void update() = 0;

    GameStateManager* stateManager;
};


Somar campos de um Banco Firebase

Question: Preciso somar os campos do meu banco FireBase, que é o campo Receita que esta dentro da coleção Dados segue a foto abaixo:

Estou usando o seguinte código para fazer uma simples leitura, define para ler o campo receita que esta dentro da coleção Dados no documento 3954d8bf-8796-4955-9d7c-0f245dcbbfdf
public class TelaCentral extends AppCompatActivity {

    FirebaseAuth firebaseAuth;
    FirebaseUser firebaseUser;
    FirebaseFirestore db = FirebaseFirestore.getInstance();
    DocumentReference dados =  db.document("Dados/3954d8bf-8796-4955-9d7c-0f245dcbbfdf");

    TextView emailExibe,campoReceita;
    Button buttonSair;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_telacentral);

        firebaseAuth = FirebaseAuth.getInstance();
        firebaseUser = firebaseAuth.getCurrentUser();

        Leitura();
       }

    // LEITURA
    private void Leitura(){
        dados.get().addOnSuccessListener(new OnSuccessListener<DocumentSnapshot>() {
            @Override
            public void onSuccess(DocumentSnapshot documentSnapshot) {
                if (documentSnapshot.exists()){
                    String recei = documentSnapshot.getDouble("Receita").toString();
                    campoReceita.setText(recei);

                }
            }
        });
    }

}

Porém, gostaria de percorrer todos os Documentos que estão na coleção Dados e somar o campo Receita para exibir ao usuário, de que forma poderia fazer isto?
Comment: Esta dando algum erro? O que está acontecendo? Só esta retornando o primeiro?
Comment: pq receita é uma string? deveria ser decimal
Answer: Pra somar tem duas maneiras uma indo em todos os itens e somar
db.collection("Dados")
    .get()
    .addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
        @Override
        public void onComplete(@NonNull Task<QuerySnapshot> task) {
            if (task.isSuccessful()) {
                Double valor = 0.0
                for (QueryDocumentSnapshot document : task.getResult()) {
                   valor += documentSnapshot.getDouble("Receita")
                }
                campoReceita.setText(valor.toString());
            } else {
                Log.d(TAG, "Error getting documents: ", task.getException());
            }
        }
    });

Ou a cada insert vc soma o valor

db.collection("Dados")
    .document("soma")
    .get()
    .addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
        @Override
        public void onComplete(@NonNull Task<QuerySnapshot> task) {
            if (task.isSuccessful()) {
                Double valor = 0.0
               if (documentSnapshot.exists()){
                     valor = documentSnapshot.getDouble("Receita")
                }
                 valor += novoitem.valor
                  db.collection("Dados").document("soma")
                    .set(valor)
                    .addOnSuccessListener(new OnSuccessListener<Void>() {
                        @Override
                        public void onSuccess(Void aVoid) {
                            Log.d(TAG, "DocumentSnapshot successfully written!");
                        }
                    })
                    .addOnFailureListener(new OnFailureListener() {
                        @Override
                        public void onFailure(@NonNull Exception e) {
                            Log.w(TAG, "Error writing document", e);
                        }
                    });

            } else {
                Log.d(TAG, "Error getting documents: ", task.getException());
            }
        }
    });

Somar campos de um Banco Firebase


How does protoc find definitions not on IMPORT_PATH?

Question: In one of my .proto definitions, I import Google's timestamp definition:
import "google/protobuf/timestamp.proto";
From the documentation,

IMPORT_PATH specifies a directory in which to look for .proto files
when resolving import directives.

I am pretty sure timestamp.proto is not on my IMPORT_PATH, which happens to be the current working directory.
Are google protobuf definitions special somehow? Are these google definitions installed locally, when protoc was installed?
Answer: They are indeed special - they are referred to as well-known types.
The compiler looks to resolve these imports relative to where the protoc executable is installed; various locations are checked. If a location is found that contains proto definitions for the well-known types, this is location is looked at as a fall-back - in other words, a path relative to where the protoc executable is run is checked first, before checking the location with the well-known type definitions.
You can see this when executing the compiler with strace or dtruss, e.g. on OSX:
stat64("google/protobuf/timestamp.proto\0", 0x7FFEE4219B98, 0x0)                 = -1 2
open("google/protobuf/timestamp.proto\0", 0x0, 0xFFFFFFFFFFFFFFFF)               = -1 2
stat64("/usr/local/Cellar/protobuf/21.8/include/google/protobuf/timestamp.proto\0", 0x7FFEE4219B98, 0x0)                 = 0 0
open("/usr/local/Cellar/protobuf/21.8/include/google/protobuf/timestamp.proto\0", 0x0, 0x0)              = 3 0

Comment: Thanks for all these details - I don't see anything relevant in the protoc executable's directory, so I think those imports access `Cellar/protobuf/21.9_1/include`. And so they were installed at the same time as `protoc` was installed, as opposed to e.g. Maven/Gradle, which pull dependencies from APIs at build time.


Load a SWF and have the loaded SWF load text dynamically (at runtime)

Question: Not sure if what I am trying to do is possible.
I need to load a swf and have the loaded swf itself load a json file at  runtime.
As an alternative is there some way I might 'inject' the loaded swf with the json AFTER it has loaded??
This is the complete code for the loaded swf and the json file. it simply loads a JSON file and uses that to populate a textField. It works fine standalone ...
<code>package
{
    import flash.display.*;
    import flash.events.*;
    import flash.net.URLLoader;
    import flash.net.URLRequest;
    import com.greensock.*;
    public class DynamicTextSWF extends MovieClip
    {

        public var marquee : MovieClip;
        private var _loader:URLLoader = new URLLoader();
        private var _request:URLRequest = new URLRequest();

        public function DynamicTextSWF()
        {
            this.addEventListener(Event.ADDED_TO_STAGE, onAdded);
        }

        private function onAdded(e:Event):void {

            _request.contentType = "application/json";
            _request.url="config.json";
            _loader.load(_request);

            _loader.addEventListener(Event.COMPLETE,loadConfirm);
            _loader.addEventListener(Event.COMPLETE,decodeJSON);
            TweenLite.to(marquee,12,{x:stage.stageWidth,delay:2 });

        }

        private function loadConfirm(e:Event):void {
            trace("Load Successful" + "\n");
        }

        private function decodeJSON(event:Event):void {
            var loader:URLLoader = URLLoader(event.target);
            trace(loader.data.toString() + "\n");
            var result:Object = JSON.parse(loader.data);

            trace('result..content.description ='+result.content.description);

            marquee.info.text = result.content.description;
        }

    }
}
</code>
This is the json file
<code>{
    "name": "ticker0",
    "content": {
        "type": "text",
        "description": "This is ticker text that is loaded dynamically",
        "required": true
    },
    "tween": {
        "type": "x",
        "duration": 4,
        "delay": 2
    },
    "style": {
        "font": "Futura",
        "color": "blue",
        "size": 12
    }
}
</code>
Comment: Where are all 3 files located? How/Where are you executing these files? Is this a security/sandbox problem? What exactly happens in when loading the json file from within the other container swf? Where do you listen for Error Events?
Comment: Before I go any further is what I am trying to do even possible? Is it simply a security sandbox issue and if so do I need to simply change the logic that loads the json? Or is this entirely controlled by the loading asset?
Comment: I think this should be possible. I guess this could be a sandbox issue, hence my question where things are located. What happens if you try to load the json directly from the "parent" swf? (that which loads the other one)
Comment: of course the parent swf can load the json directly.  I think an alternative to try would be to load the swf with a query string attached ie fo.swf?these%20are%20some%20vars%20to%20load will try and report back
Comment: I suggest you add listeners for errors etc. to the loader to know what's going on.
Answer: You should be able to load any number of SWFs into each other, and then other assets into them, so I think you need to work out at what point your DynamicTextSWF class is failing when loaded into another SWF.
Assuming you have a way to see the trace statements, I would put more trace statements in - one in the DynamicTextSWF constructor, and one in its onAdded method and see how far it gets - is the DynamicTextSWF instance ever added to the stage?. I would also, as been suggested, add a listener for the IOErrorEvent.IO_ERROR with another trace statement.
I use a tool called Vizzy which allows me to view the trace output for Flash debug content when playing in a browser in a Flash Debug Player. This also lets you view the Flash Player policy log, which shows you where there has been a security error.
I also use a tool called Charles which allows you to view network requests (a bit like the network panel in Chrome DevTools, but it does lots more useful things) - this allows you to see if there have been any 404 requests, in the case that your SWF is asking for the JSON data at the wrong URL.


Evaluating whether a function is a probability density or not

Question: I would like to have my solution checked and gather some further information. I have to show which of the following functions define a probability density. We work with $\Omega = \{1, 2, 3\}$ and $f: \Omega \rightarrow \Bbb R$.
Now, for a function being a probability density, we have to check if the values $f(i) = p_i \in$ $[0, 1]$ and if the sum of these values equals $1$.
$f(i)$ = $i \over 5$ is not a probabilty density. Although $p_i \in [0, 1]$, the sum of the $p_i$ doesn't equal $1$, but $6 \over 5$.
$f(i) =$ ${i + 1} \over 9$ is a probality density since $p_i \in [0, 1]$ and since the sum of the $p_i$ does indeed equal $1$.
$f(i) = (-1)^{i+1}$ is not a probality density. For $i = 2$, we receive $f(2) = -1 \notin [0, 1]$.
$f(i) = 2 - i$ is not a probality density either. For $i = 3$, we receive $f(3) = -1 \notin [0, 1]$.
Somehow, this seems way too easy for me. Is it correct so far?
Furthermore, for the second case, I have to evaluate the propability measure, but isn't it given by the function itself?
Answer: All your answers are correct. Presumably, it is easy because it is just your first introduction to the subject (and will get harder). Without context, it is difficult to say what it means to "evaluate" a probability measure; the closest I can think of is that they want you to make a table of function arguments and values, but that is really quite trivial and not insightful.
Comment: Well, that might have been a bad translation of mine. I guess the correct term I have to use here is "specify the propability measure".
Comment: In that case, they probably want you to give the probability $P(A)$ for any subset $A \subseteq \Omega$.
Comment: For example like $P(\{1, 2\})$ $=$ $5 \over 9$? Or is there a way to specify this for an arbitrary subset?
Comment: Yes, like that. The "general way" to specificy it would be something like $P(A) = \sum_{i \in A} \frac{i+1}9$, but that is so much like writing down the definition that I would argue it doesn't qualify as an answer to the question.
Comment: Will ask the tutor on that one, thank you!


How to validate file using hook_file_validate?

Question: I want to validate my file, I'm using

hook_file_validate

function test_file_validate($file) {
  $errors = array();

  if (empty($file->filename)) {
    $errors[] = t("The file's name is empty. Please give a name to the file.");
  }
  if (retstrlen($file->filename) > 255) {
    $errors[] = t("The file's name exceeds the 255 characters limit. Please rename the file and try again.");
  }
  return $errors;
}

But, when I am going to print_r($file) I am not getting any values, please let know how to use this function
Comment: does this hook exist? I've never heard about. And couldn't find any information..
Comment: oops, my bad, it does exist.. Did you flush the cache?
Comment: What it the file peramater? Is it a form tag which is posted by form. Or it is a $file which you have assigned some file path properly?
Comment: hook_file_validate exists, Folks please see the link on D.o https://api.drupal.org/api/drupal/modules!system!system.api.php/function/hook_file_validate/7
Comment: Sidenote: don't use `print_r()`. Instead, install [Devel](http://drupal.org/project/devel) and use `dpm()` function - it will display an element tree of your object/array which is very easy to inspect.
Answer: In Drupal 7 just use drupal_set_message
/**
 * Implementing hook_file_validate
 * @param type $file : Object
 * @return type : array of error messages
 */
function hook_file_validate($file) {
    drupal_set_message("
" . print_r($file, 1) . "
");
    $errors = array();
    if ($file->source == 'field_article_file_und_0') {
        if ($file->filesize > 290081) {
            $errors[] = t("The file's exceeds upload limit. Please try again.");
        }
    }
    return $errors;
}

Answer: hook_file_validate() is called by file_validate().  It lets you supply custom validation to supplement the validators that already exists.  You need to give it valid file object to work with.  Here is an example of how to use. In this example, it always produces an error message (so you don't have to type in absurdly long filenames, etc. to test).
/**
 * Implements hook_file_validate().
 */
function MYMODULE_file_validate($file) {
  debug('hook_file_validate was called');
  // Add your custom validation code here. E.g.:
 $errors = array();
 if (!mb_detect_encoding($file->filename, 'ASCII', true)) {
   $errors[] = t("Please don't use non-ASCII charcters in filenames.");
  }
  $errors[] = t("This error is always added, just to test that it works.");
}

Now, most of the stand upload functions that comes with Drupal already calls file_validate, so you should see any errors generated by it.
However, if you're creating a custom upload method, you need to call file_validate somewhere in your code, for instance in your form validation code:
// Load the file object:
$fid = $form_state['values']['image'];
$file = file_load($fid);
// Use one of the existing validator callbacks to check if it is an image.
$validators = array(
  ' file_validate_is_image' => array(),
);

// When this function is called, hook_file_validate is also called.
$errors = file_validate($file, $validators);
foreach ($errors as $key => $error) {
  drupal_set_message($error);
}

Note that instead of using hook_file_validate(), you can write your own validation callbacks and add those to the $validators array.  I prefer to use this method instead of hook_file_validate.
Answer: Hello Sachin I think the problem is that you are not watching output at right place.
If you are uploading a file at a node's edit then you will see your message there only.
For example I tried it for you by uploading a file with file name larger than 25 characters then at time of uploading I found the this message:

I have also used this print_r($file) in my code and found details about file being uploading in Ajax pop up.
And my code as as follows :
 function common_file_validate($file) {  print_r($file);exit;
  $errors = array();

  if (empty($file->filename)) {
    $errors[] = t("The file's name is empty. Please give a name to the file.");
  }
  if (strlen($file->filename) > 25) {
    $errors[] = t("The file's name exceeds the 25 characters limit. Please rename the file and try again.");
  }

  return $errors;
}


Verilog shift extending result?

Question: We have the following line of code and we know that regF is 16 bits long, regD is 8 bits long and regE is 8 bits long, regC is 3 bits long and assumed unsigned:
regF <= regF + ( ( regD << regC ) & { 16{ regE [ regC ]} }) ;

My question is : will the shift regD << regC assume that the result is 8 bits or will it extended to 16 bits because of the bitwise & with the 16 bit vector?
Answer: The shift sub-expression itself has a width of 8 bits; the bit width of a shift is always the bit width of the left operand (see table 5-22 in the 2005 LRM).
However, things get more complicated after that. The shift sub-expression appears as an operand of the & operator. The bit length of the & expression is the bit-length of the largest of the 2 operands; in this case, 16 bits.
This sub-expression now appears as an operand of the + expression; the result width of this expression is again the maximum width of the two operands of the +, which is again 16.
We now have an assignment. This is not technically an operand, but the same rules are used; in this case, the LHS is also 16 bits, so the size of the RHS is unaffected.
We now know that the overall expression size is 16 bits; this size is propagated back down to the operands, except the 'self-determined' operands. The only self-determined operand here is the RHS of the shift expression (regC), which isn't extended.
The signedness of the expressions is now determined. Propagation happens in the same way. The overall effect here, since we have at least one unsigned operand, is that the expression is unsigned, and all operands are coerced to unsigned. So, all (non-self-determined) operands are coerced to unsigned 16-bit before any operation is actually carried out.
So, in other words, the shift sub-expression actually ends up as a 16-bit shift, even though it appears to be 8-bit at first sight. Note that it's not 16-bit because the RHS of the & is 16-bit, but because the entire sizing process - the width propagation up the expression - came up with an answer of 16. If you'd assigned to an 18-bit reg, instead of the 16-bit regF, then your shift would have been extended to 18 bits.
This is all very complicated and non-intuitive, at least if you have any experience of mainstream languages. It's explained (more or less) in sections 5.4 and 5.5 of the 2005 LRM. If you want any advice, then never write expressions like this. Write defensively - break everything down to individual sub-expressions, and then combine the sub-expressions.

Verilog shift extending result?


How can i increase flutter appbar size in iphone 11,12,13 ? What kind of changes i can do in order to fix this (i have added my appbar code below)

Question: <code>import 'package:flutter/material.dart';
import 'package:flutter_1/widgets/drawer.dart';

class Homepage extends StatelessWidget {

  @override
  Widget build(BuildContext context) {
    return Scaffold(

      drawer: const Mydrawer(),
      appBar: AppBar(
        title: const Text("ASUS",
        style: TextStyle(
          color: Colors.black
        ),),
          backgroundColor: Colors.white,
        iconTheme: const IconThemeData(color:Colors.black),
        elevation: 0.0,

        ),

        floatingActionButton: IconButton(
        onPressed: (){},
    icon: const Icon(Icons.laptop),
        ),

    );
  }
}
</code>
Answer: To increase Flutter AppBar size you can use PreferredSize() Widget To set Appbar custom Size here is the example of preferredsize Appbar
<code>  Widget build(BuildContext context) {
return Scaffold(
  appBar: PreferredSize(
    preferredSize: const Size(340, 150),
    child: Container(
      height: 150,
      color: Colors.blue,
      child: Padding(
        padding: const EdgeInsets.only(top: 58.0),
        child: Row(
          children: [
            BackButton(),
            Text(widget.title),
          ],
        ),
      ),
    ),
  ),
</code>
Here is the Result of code :-


Among $26$ divisors of $120^4$ there is a pair that one of them divides the other

Question:
Given $26$ arbitrary divisors of $120^4$ ,using pigeon hole principle prove that there is a pair that one of them  divides the other.

I considered prime decomposition of $120^4$ as $2^{12}\times 3^4 \times 5^4 $.It's seen that it has a total of  $325$ divisors . So each divisor is of the form: $2^{a}\times 3^b \times 5^c $ such that: $a\leq 12,b\leq 4 , c\leq 4$.But I can't detect holes...
Comment: **Hint:** $26=1+(4+1)(4+1)$.
Comment: Do you really mean "two of them divide each other", or just "one divides another one"? If $a$ and $b$ are positive integers and $a$ and $b$ divide each other then $a=b$.
Comment: I mean one of them divides the other,I'll fix it
Comment: You should fix the title as well.
Answer: Since I have provided a sufficient hint for this problem, I just want to show that it is possible to pick $25$ divisors of $120^4$ in such a way that none of the chosen numbers divides another.  The set $S$ consisting of $25$ numbers of the form
$$2^{12-a-b}\,3^a\,5^b$$
for $a,b\in\{0,1,2,3,4\}$ has the required property.
In general, suppose that an integer $n$ is of the form $p_1^{k_1}\,p_2^{k_2}\,\cdots\,p_r^{k_r}$, where $p_1<p_2<\ldots<p_r$ are prime natural numbers and $k_1,k_2,\ldots,k_r$ are positive integers. Let $D_n$ denote the partially ordered set consisting of (positive) divisors of $n$, equipped with the divisibility ordering (i.e., for $x,y\in D_n$, $x\preceq y$ if $x\mid y$).  Clearly, any antichain of $D_n$ is of size at most $$\nu_n:=\min_{j\in\{1,2,\ldots,r\}}\,\prod_{i\in\{1,2,\ldots,r\}\setminus\{j\}}\,\left(k_i+1\right)\,.$$
If there exists $j\in\{1,2,\ldots,r\}$ such that $k_j \geq \sum\limits_{i\in\{1,2,\ldots,r\}\setminus\{j\}}\,k_i$, then $\nu_n$ is the width of $D_n$.  However, this upper bound is very weak (e.g., $\nu_{p_1p_2\cdots p_r}=2^{r-1}$, but the width of $D_{p_1p_2\cdots p_r}$ is $\displaystyle\binom{r}{\lfloor r/2\rfloor}$).  In fact, $\displaystyle\binom{r}{\lfloor r/2\rfloor}$ is a (quite weak) lower bound for the width of $D_n$ if $n$ has $r$ distinct prime factors (i.e., excluding multiplicities). For an exact algorithm to compute the width of $D_n$, see How do you calculate the width of the Poset Lattice of Divisors?.
Comment: Would you please explain why none of the numbers in S is not divided by the other?
Comment: Let $\omega(n)$ be the number of prime divisors of a positive integer $n$ (including multiplicity).  For example, $\omega(4)=\omega(6)=2$.  Then, for two distinct positive integers $m$ and $n$ with $\omega(m)=\omega(n)$, $m$ and $n$ do not divide one another.


How to change my base URL

Question: I have built a website using drupal. Now, the base URL is http://xxx.xxx.xxx.xxx/drupal.
But I want to change base URL as http://xxx.xxx.xxx.xxx
How do I do?
Thanks.
Comment: Do you have access to add vhost in apache? If yes then one clean way is to add a virtualhost to map the directory where you have installed Drupal (including the drupal folder) to ServerName which is xx.xx.xx.xx and reload apache..
Comment: Hi Dipen,
How to add a virtualhost to map the directory where you have installed Drupal? Thanks.
Answer: go to yousite/sites/default and open the settings.php file and find $base_url and change it to the new value (somewhere around line 270).
NOTE : settings.php is a read-only file, you need to clear the read-only flag first to make the changes. You'll need to restart the server to update the changes.
Comment: I suppose there may be exotic configurations where it may be necessary, but in most cases you shouldn't have to restart the server at all - the change will go into effect immediately.
Comment: when I change the base_url to my domain name. I get much error on page. for example, "failed to load resoutce". because the resource location has been changed to "http://domainname/xxxx/xxx.css" (original is http://ip/xxxx/xxx.css)
why ??
Comment: You need to check where the base installation of your Drupal site is. If it is at the root of the server (e.g. www), then you need to give `$base_url=siteroot`; else if it is in some folder inside the root of the server, then you need to have `site_root/path_to_drupal_install_folder` value for your `$base_url`
Comment: Its not woking for me.
Answer: There is a global variable called $base_url that you can set in sites/default/settings.php. Try changing its value.

How to change my base URL


How to show one selected value in JSF 1.2 selectOneMenu list from database

Question: I am working in JSF 1.2
I have populated a list using selectOneMenu from database. Now my requirement is that, among that list coming from the database, there is one value which have to be shown as selected. But I can not do that.
I am posting my code what I have done so far,
My bean code
 mem = new MemberProxy().getMemberDetails(loggedInUser
                        .getUserAccessList().get(0).getClientCode(), loggedInUser
                        .getUserAccessList().get(0).getCertificateNumber());

             memberDependent.setInsuredMemberName(new SelectItem(mem.getNameFirst()));

My JSP code
 <h:panelGroup styleClass="panelGroup" id="grpMemDep">
                                            <h:selectOneMenu value="#{searchUserProfileBean.insuredMemberName}" id="memDepCode" styleClass="inputfont" onchange="getMemberDepInfo();" >
                                                    <f:selectItems id="selectItems32"
                                                        value="#{searchUserProfileBean.memberDependentList}" />
                                                </h:selectOneMenu>

                                        </h:panelGroup>

This is the way how i am constructing the list
 MemberDependentBO memberDependent = new MemberDependentBO();

            List<DependentDTO> dependentList = new MemberProxy()
            .getDependentListFormMember( loggedInUser
                    .getUserAccessList().get(0).getClientCode(),
                    loggedInUser
                    .getUserAccessList().get(0).getCertificateNumber());
            List<SelectItem> selList=new ArrayList<SelectItem>();

            for(DependentDTO depDTO:dependentList){

                SelectItem sel = new SelectItem();
                sel.setLabel(depDTO.getNameFirst());
                sel.setValue(depDTO.getCertNumber()+"#"+depDTO.getClientCode()+"#"+depDTO.getDependentCode());
                selList.add(sel);
            }
             mem = new MemberProxy().getMemberDetails(loggedInUser
                        .getUserAccessList().get(0).getClientCode(), loggedInUser
                        .getUserAccessList().get(0).getCertificateNumber());

             memberDependent.setInsuredMemberName(new SelectItem(mem.getNameFirst()));
             SelectItem sel = new SelectItem();
             sel.setLabel(mem.getNameFirst());
             sel.setValue(mem.getCertNumber().toString().trim()+"#"+mem.getClientCode().toString().trim());
             selList.add(sel);

            memberDependent.setMemberDependentList(selList);

Here I  have used one selectItem type variable which I am setting to my bean and that I am trying to show in the list but it is not working.
Comment: Here you have a lot of information related to "selectOneMenu" http://stackoverflow.com/tags/selectonemenu/info Including how to set a selected item.
Comment: @RubioRic can you edit my code i am totally clueless
Comment: In the examples that appears in the link, the selected item is a simple String. Have you tried using a String in  searchUserProfileBean.insuredMemberName?
Comment: Is searchUserProfileBean.memberDependentList a list of String or a list of Selecttem?
Comment: @RubioRic searchUserProfileBean.memberDependentList  is a list of selectitem
Comment: @RubioRic yes i  have tried with String but it did not work
Comment: Show how your are constructing that list. Maybe this will give us a hint.
Comment: @RubioRic i have edited my list population please see
Comment: I don't see anything wrong, sorry. Let me insist, in all the examples that I've checked the initial selected value is a String and not a SelectItem.  "memberDependent.setInsuredMemberName(mem.getNameFirst());" should do the work.
Comment: The only strange thing is that you are constructing item values in slightly different way. [ONE] sel.setValue(depDTO.getCertNumber()+"#"+depDTO.getClientCode()+"#"+depDTO.getDependentCode()); [TWO] sel.setValue(mem.getCertNumber().toString().trim()+"#"+mem.getClientCode().toString().trim());
Comment: @RubioRic that's for a reason  i have to send the clientcode and certno for  data polulation
Comment: But why do you construct the items differently in these two cases?
Comment: @RubioRic  i am  new to jsf , can you please edit my code?
Comment: I've tried to explain myself in an answer. Check it, try it and let me know what happens.
Answer: Let me mark three points of your code
 for (DependentDTO depDTO:dependentList){
   SelectItem sel = new SelectItem();
   sel.setLabel(depDTO.getNameFirst());
   sel.setValue(depDTO.getCertNumber()+"#"+depDTO.getClientCode()+"#"+depDTO.getDependentCode());
   selList.add(sel);  // [1]
 }

 mem = new MemberProxy().getMemberDetails(loggedInUser
                    .getUserAccessList().get(0).getClientCode(), loggedInUser
                    .getUserAccessList().get(0).getCertificateNumber());

memberDependent.setInsuredMemberName(new SelectItem(mem.getNameFirst())); // [2]

SelectItem sel = new SelectItem();
sel.setLabel(mem.getNameFirst());
sel.setValue(mem.getCertNumber().toString().trim()+"#"+mem.getClientCode().toString().trim());
         selList.add(sel); // [3]

memberDependent.setMemberDependentList(selList);

[1] Is the value that you want to select already in this list?
[2] You are creating and item with no established value. Item value will be equal to item label: mem.getNameFirst()
[3] At this point you are including an item with the same label but with a different value that the one generated in [2]. Besides the value generated is different from the value generated in [1]
sel.setValue(depDTO.getCertNumber()+"#"+depDTO.getClientCode()+"#"+depDTO.getDependentCode());
sel.setValue(mem.getCertNumber().toString().trim()+"#"+mem.getClientCode().toString().trim());

In the second sentence you are trimming and not including the third element "dependentCode"
Try this
  SelectItem sel = new SelectItem();
  sel.setLabel(mem.getNameFirst());
  // INCLUDE DEPENDENT CODE
  sel.setValue(mem.getCertNumber()+"#"+mem.getClientCode()+"#"+mem.getDependentCode());

  memberDependent.setInsuredMemberName(sel);

  selList.add(sel); // ONLY, ONLY IF ITEM IS NOT INCLUDE IN LOOP [1]

  memberDependent.setMemberDependentList(selList);


Minha função print não funciona no prompt de comando do windows

Question: Eu estou começando a estudar programação. Baixei a versão 3.8.3 do Python e para escrever os programas baixei o Sublime text que permite executar os programas na própria plataforma.
Quando comecei estava funcionando normalmente, conseguia rodar os programas tanto no Sublime text quanto no prompt do Windows (tenho o Windows 10), mas fiquei um tempo sem estudar e quando fui voltar agora a função print não funciona através do prompt, apenas através do Sublime text. Quando tento rodar pelo prompt a janela abre e fecha muito rapidamente, o que não acontecia antes.
O estranho é que minha namorada me enviou um programa por email e o programa que ela fez roda tranquilamente pelo prompt do Windows, mas os que eu faço no meu computador não.
Já tentei ver se era erro de digitação, então escrevi um programa bem simples:

print ("Ola mundo")

E mesmo assim não funcionou.
Já desinstalei e instalei o Python e nada. Tentei escrever o programa usando outra ferramenta de texto e não funcionou também. Vi que podia olhar no help() do Python para ver se estava tudo certo e está.
Será que é algum problema com o Windows?
Comment: Durante a instalação do `Python` (site oficial) o instalador pergunta se desejas `criar` a variável de ambiente do Python. Caso esteja desabilitando esta opção durante a instalação, o Python não será `reconhecido` no `prompt de comandos`. Sugiro reinstalar o Python `habilitando` a definição da `variável de ambiente`.
Comment: Outra coisa, é bom saber que `atualmente` existe em funcionamento duas versões de Python incompatíveis entre si. A versão `2` e a versão `3`. Isto significa dizer que, programas criados em `Python 3` não serão executados por interpretadores de versão `2` ou vise-versa.
Answer: Como exatamente você está executando o programa? (Não posso deixar comentário pois não tenho pontuação o suficiente).
Primeiro você deve se certificar de que a instalação do Python está ok na sua máquina rodando python --version no seu terminal. Se mostrar a versão certinho, é pq está ok. Se não reconhecer o comando você deve refazer a instalação.
Uma vez que a instalação esteja correta, execute o comando python, isso te colocará dentro do interpretador Python. Lá você poderá executar vários comandos individualmente, inclusive o print("Hello, world!").
Para executar um programa que você tem em um arquivo, rode no terminal o comando python nomeDoArQuivo. Certifique-se de que o arquivo tem extensão .py, e que você está rodando o comando no mesmo diretório em que se encontra o arquivo. Espero ter ajudado.
Comment: Só para complementar sua resposta, é bom perceber que, durante a instalação do `Python` (site oficial) o instalador pergunta se desejas `criar` a variável de ambiente do Python. Caso esteja desabilitando esta opção durante a instalação, o Python não será `reconhecido` no `prompt de comandos`. Sugiro reinstalar o Python `habilitando` a definição da `variável de ambiente`.
Answer: Olá, boa noite!
Funcionou rodar o comando python Nome do arquivo.
Muito obrigado pela resposta!


jquery not updating dom inside hide complete function

Question: I have a pair of Jquery / Javascript functions:
var id_testimonials = jQuery.noConflict();

//recusive function to power slider
function ttd_testimonial (elem) {

    elem.each (function () {
        if(id_testimonials(this).is(':visible')) {
            id_testimonials(this).hide(4000, function () {ttd_show (id_testimonials(this)); });

        }
    });
}

//figure out what to show
function ttd_show (elem) {
    container = elem.parent();

    if (elem.next().length !== 0) {
        next_elem = elem.next();
    } else {
        next_elem = container('.testimonial_single').first();
    }

    regen_elems = container('.testimonial_single');
    id_testimonials(next_elem).show(4000, function (){ ttd_testimonial(regen_elems); });
}

The complete function on the .hide() fires correctly as far as I can see. I am also able to select the next_elem variable correctly, so I know the second function is receiving it's args correctly.
However, the .show() never fires (or never seems to). There doesn't seem to be any reason for this.
I have tried next_elem.show(args), next_elem.show() and id_testimonials(next_elem).show()  with no effect.
Also when I try adding .css() in the second function the dom is not updated, but I can alert() object properties correctly. Obviously the two things are linked but I can't work out the cause.
JsFiddle as requested
Comment: @user2641562 Look at your console : Uncaught TypeError: Property 'container' of object [object Object] is not a function. Use `container.find` here.
Comment: @user2641562 again, `container.find()` will work, but it is not very easy to read/follow/understand and does not necessarily reflect the underlying logic. In this case you are using a standard class selector without referencing anything from the particular `container`object. So, `jQ('.testimonial_single')` would have been a much clearer statement.
Comment: Could you put your code in a jsfiddle?
Comment: I don't get the intent in `container('.testimonial_single')`. container isn't a function.
Comment: A big part of jQuery is the ability to write more concise code. `var id_testimonials = jQuery.noConflict();` seems to go against that purpose.
Comment: It is all a bit cryptic, but container is actually a jQuery object, initialized in `container = elem.parent();` with  `elem` being the argument in `ttd_show()`, passed as `$(this)` essentially. For some reason th OP uses `id_testimonials` instead of `$`. ... I quite agree with dystroy: jQuery stands for "write less, do more!"
Comment: I am having conflicts between jquery and other javascript libraries. I don't like having multiple libraries, but I don't have much choice.
Comment: To improve readability, maybe you could do `var jQ = jQuery.noConflict();` instead. That makes it more obvious when you use functions like `jQ(this)`?
Comment: @user2641562 You didn't answer the point about `container('.testimonial_single')`. A jQuery object isn't a function. What did you try to do ? Did you mean `id_testimonials` instead of `container` ?
Comment: @dystroy `container('.testimonial_single')` is for getting child elements of the container object. It's just a standard `$('.class')` selecter
Comment: @dystroy that's fixed it. Care to add an answer for me to tick? I should of seen that error. Also I'll keep the readability advice in mind for the future.
Comment: @cars10 I wrote it like that to keep it portable, but to be honest know that I think about it, that didn't make much sense.
Answer: You can see this error in the console :
Uncaught TypeError: Property 'container' of object [object Object] is not a function

That's because container is a jQuery object, which isn't a function. You must use jQuery traversal functions like find to get your elements starting from some context.
Replace
container('.testimonial_single')

with
container.find('.testimonial_single')


Can a function have a gradient everywhere, but be non-continuous everywhere?

Question: It is well known that a function that has a gradient in $x$ is not necessarily differentiable in $x$ and may in fact be non-continuous in $x$ (unless the gradient is $C^1$.
Answer: I'm assuming that by the term gradient, you mean the partial derivatives with respect to the basis elements.
So let's consider $f(x,y)= \frac{xy}{x^2+y^2}$ if $(x,y)\neq (0,0)$, and $f(0,0)=0$. Note that the partial derivatives $\frac{\partial f}{\partial x}$ and $\frac{\partial f}{\partial y}$ at (0,0) certainly exist, since $f(0,y)=0\ \forall y$ and $f(x,0)=0\ \forall x$. Hence, we have $\nabla f = (0,0)$ at $(0,0)$.
However, $f$ isn't continuous at $(0,0)$. We use the sequential definition of continuity, which says that if there is a sequence $(x_n)$ that converges to $(0,0)$, then the sequence $f(x_n)$ converges to $f(0,0)=0$.To see this, note that if we approach the point $(0,0)$ via the sequence $(\frac{1}{n},\frac{1}{n^2})$, then we get $f(x_n)=0.5\ \forall n$, but $f(0,0)=0 \neq 0.5$. Hence, f is not even continuous at $(0,0)$! This asks us to refine our definition of differentiability, and so we request for the continuity of the partial derivatives!
You want a function, that is nowhere continuous, but whose gradient exists everywhere. I tell you what, this is impossible.
In order to understand this, we must first understand that if the partial derivatives are continuous in even some small interval, then the function is differentiable, so continuous on that interval, so we would also like the partial derivatives to be discontinuous everywhere. This, however, is what is prohibited by what is called the Baire Category Theorem for functions.
If $f'$ existed at a point, then by a well-known theorem, it is a limit of a  pointwise converging sequence of continuous functions, which implies it is of a special class called Baire Class 1. It is known that functions of Baire class 1, are continuous on a dense set of $\mathbb{R}$, which is to say not only is the set of continuous points of $f'$ non-empty, it is in fact dense in $\mathbb{R}$. This proves that $f$ is infact differentiable on a dense set of $\mathbb{R}$, and hence $f$ can't even be nowhere-differentiable!
Comment: Thanks for your answer, I'm looking up the BCT to understand your answer, but I didn't downvote you.
Comment: That's ok. Some other person must have.


Why does C++ allow unnamed function parameters?

Question: The following is a perfectly legal C++ code
void foo (int) {
    cout << "Yo!" << endl;
}

int main (int argc, char const *argv[]) {
    foo(5);
    return 0;
}

I wonder, if there a value to ever leave unnamed parameters in functions, given the fact that they can't be referenced from within the function.
Why is this legal to begin with?
Comment: One standard use case is in [Tag Dispatching](http://www.generic-programming.org/languages/cpp/techniques.php#tag_dispatching)
Comment: The only place I've ever seen it actually used is for prototypes; I've seen some function prototypes and class definitions that omitted the parameter names for brevity or other reasons.  I'm not sure why it's legal.
Comment: I used dummy parameters in one of my designs where I have an object with two sets of identically typed members.  The constructor usually only initializes one set of members.  My factory method knows which set to be initialized. To distinguish the two different sets, I used a dummy bool parameter for the second set.  For illustration: class Twosets { private: int leftA; char leftB; int rightA; char rightB; public: Twosets(int a, char b); Twosets(int a, charb, bool); The later will be used to construct the right members.
Answer: Yes, this is legal. This is useful for implementations of virtuals from the base class in implementations that do not intend on using the corresponding parameter: you must declare the parameter to match the signature of the virtual function in the base class, but you are not planning to use it, so you do not specify the name.
The other common case is when you provide a callback to some library, and you must conform to a signature that the library has established (thanks, Aasmund Eldhuset for bringing this up).
There is also a special case for defining your own post-increment and post-decrement operators: they must have a signature with an int parameter, but that parameter is always unused. This convention is bordering on a hack in the language design, though.
Comment: Worth mentioning that some compilers can warn about unused parameters: Making them unnamed will fix the warning.
Comment: ...or for regular functions that are to be used as a callback (and therefore must conform to a given signature) but don't need to use the parameter.
Comment: @dasblinkenlight: Good point about post-increment, but the type of the unnamed parameter can be used as well. This is actually (ab)used in STL for template parameters in various implementations. This sort of trick is mainly useful for template functions/classes, so you can change which function you're invoking based on traits of the template parameter types.
Comment: Can't unused parameters also be used for function overloading purposes?
Comment: @KevinBallard Arguably, this is how the pre-increment vs. post-increment convention is using it. I think that using otherwise unused parameters for overloads is somewhat of a hack, though: overloads are resolved at compile time, so there is no reason not to use a distinct name rather than adding an unused parameter.
Comment: @AasmundEldhuset, True, I usually name those unused parameters `unused`, though, to make it clearer.
Comment: @KevinBallard You are right, templates are a different story altogether: their programming model borders on Prolog's unification, giving the number and the type of parameters a whole new meaning. You're right about the "abuse", though - there's a lot of "write-only" code in the standard C library.
Comment: @chris That's less clear to me. Giving unused args dummy names is pointless, pollutes the scope with identifiers you don't want to - but now accidentally _can_ - use, generates warnings for any decent set of compiler flags, and I imagine is really tedious especially if you have >1. In contrast, not giving such arguments a name is a standard way to express that you don't care about them, don't want to reserve names for them, and don't require warnings about them. How is `unused` clearer?
Comment: @underscore_d, Honestly, I don't even remember 5 years ago. Nowadays, if you really want to name it, you can attach `[[maybe_unused]]`, and the only advantage I see is being able to name the parameter according to what it is actually for so that you know what you're not using, while having the attribute to be explicit about not using it.
Comment: The rationale about callbacks is also applicable to C, but there omission of parameter name (other than in a prototype) is not allowed.
Comment: I've just read similar examples in Nikolai M. Josuttis'es book "The c++ standard library". He uses std::true_type and std::false_type as a disambiguation between overloads (page 153)
Answer: Of course not naming a parameter is legal when just declaring the function, but it's also legal in the implementation. This last apparently strange version is useful when the function needs to declare the parameter to have a specific fixed signature, but the parameter is not needed.
This may happen for example for a method in a derived class, for a callback function or for a template parameter.
Not giving the parameter a name makes clear that the parameter is not needed and its value will not be used. Some compilers if you instead name a parameter and then simply don't use it will emit a warning that possibly there is a problem with the function body.
Answer: Just wanted to mention a specific (unusual but interesting) usecase - the "passkey idiom".
It uses a "dummy" parameter of a type, constructor of which is accessible only to its friends. Its purpose is only to check, whether the caller has access to this constructor. So it needs no name as it is not used in the function, only the compiler uses it.
It's used like this:
class Friendly; // Just a forward declaration

class Key {
private:
    Key() {}
    friend class Friendly;
};

class Safe() {
public:
    static int locked(Key, int i) {
        // Do something with `i`,
        // but the key is never used.
        return i;
    }
private:
    static void inaccessible() {}
};

class Friendly {
public:
    void foo() {
        int i = Safe::locked(Key(), 1); // OK
        int j = Safe::locked({}, 2);    // OK, sice C++11
    }
    void bar() {
        Safe::inaccessible(); // Not OK, its inaccessible
    }
};

int i = Safe::locked(3);        // Not OK, wrong parameters
int j = Safe::locked(Key(), 4); // Not OK, `Key` constructor is inaccessible
int k = Safe::locked({}, 5);    // Not OK, `{}` means `Key()` implicitly

Answer: I just want to add that there is sometimes a difference whether you name a parameter or not. For example, the compiler treats a named rvalue reference as an lvalue and an unnamed rvalue reference as an rvalue.
// named-reference.cpp
// Compile with: /EHsc
#include <iostream>
using namespace std;

// A class that contains a memory resource.
class MemoryBlock
{
   // TODO: Add resources for the class here.
};

void g(const MemoryBlock&)
{
   cout << "In g(const MemoryBlock&)." << endl;
}

void g(MemoryBlock&&)
{
   cout << "In g(MemoryBlock&&)." << endl;
}

MemoryBlock&& f(MemoryBlock&& block)
{
   g(block);
   return block;
}

int main()
{
   g(f(MemoryBlock()));
}

This example produces the following output:

In g(const MemoryBlock&).
  In g(MemoryBlock&&).

In this example, the main function passes an rvalue to f. The body of f treats its named parameter as an lvalue. The call from f to g binds the parameter to an lvalue reference (the first overloaded version of g).
Comment: This is unrelated. The question is about unnamed arguments, those lacking identifiers on the receiving function's side. You're talking about the value category passed from the caller's side - while incidentally including unnamed arguments, but not in a relevant way. Any difference here is because of the passed value category, not the presence or absence of a name for the argument. Because you don't forward/move the rvalue reference in the first, inner call to `g()`, the `const&` overload must win. The fact you need a name in order to forward it is completely incidental.
Comment: This is logical, setting a name to a variable basically means "I'm gonna use it in the following statements", thus, lvalue. Specifying whether it's lvalue or rvalue doesn't depend on it's origin, but whether the reference in memory will persist after the statement.
Comment: This isn't even valid code (`return block;` should fail to compile). VTD, is irrelevant to the question.


Erro estranho em C

Question: Alguém sabe o porquê do valor do i mudar na condição else if(i==721)? Ele muda estranhamente, como podem ver no vídeo do debuging.
teamfile=fopen("team.txt", "r");
if(fgets(c, 3, teamfile)==NULL){
    printf("Please add one team at least before try to add players or managers.\n");
}
else{
    playerfile=fopen("player.txt", "r");
    for(i=1; i<=722; i++){
        if(fgets(c, 250, playerfile)==NULL && i<720){
            do{                     //NAME
                printf("Name: ");
                getchar();
                gets(c);
                w=0;
                for(j=0; j<49; j++){        //<49 supondo que, para o string máximo, o c[49]=\0
                    if(c[i]>32 && c[i]<65){
                        w=1;
                        printf("Invalid characters. Try again. \n"); break;
                    }
                }
            }while(w==1);
            strcpy(player[i].name, c);

            do{                 //BIRTH DATE
                w=0;
                printf("Player birth date (dd mm yyyy): ");
                scanf("%i %i %i", &d, &m, &y);
                w=dateverific(d, m,y);
            }while(w==1);
            player[i].birth.day=d;
            player[i].birth.month=m;
            player[i].birth.year=y;

            nations(i);     //NATION
            positions(i);       //POSITION
            teamlists(i, a);        //TEAM
            fclose(playerfile);
            playerfile=fopen("player.txt", "a");
            fprintf(playerfile, "%s %d %33s %d %d %d %s %s\n", player[i].position, i, player[i].team, player[i].birth.day, player[i].birth.month, player[i].birth.year, player[i].nation, player[i].name); // explicar troca de id pela position realacianado com o fscafn do string clube name
            fclose(playerfile);
            break;
        }
        else if(i==721){
            printf("Impossible to add more players, all team are full.");
        }
        else{
        }
    }
}

Comment: Como foi declarada sua variável `i`?
Comment: Normalmente, int i=1;
Answer: Como se pode ver no vídeo mesmo, o valor de i é sobreescrito com lixo antes da linha com o  if que você põe na pergunta - e sim na própria linha que contém if(fgets(c, 250, playerfile)==NULL && i<720).
Como a comparação i < 720 não altera o valor de i, o que "sobra" é que o que está colocando lixo em i é a chamada a fgets. essa é uma função segura, mas tem que ser usada da forma correta.  Em particular, o parâmetro de buffer para onde vão ser lidos os seus dados, tem que conter memória livre  - ou seja, seu c tem ou ter sido declarado com char c[250];, ou ter sido declarado como um ponteiro e apontado para uma região de memória alocada - algo como char *c; ...; c = malloc(250); if (c==NULL) {exit(1); /* falha ao alocar memoria */}
O erro provavelmente acontece por que você está supondo que fgets aloca a memoria sozinho - o que não acontece - no meu sistema aqui (que é posix-conformant), a descrição da função é:

fgets(s)  reads  in  at  most one less than size characters from stream
  and stores them into the buffer pointed to by s.

Ou seja - o espaço apontado pelo ponteiro que vai no primeiro parâmetro da chamada já tem que estar reservado.
Bom - essa é a resposta - eu deixo duas dicas adicionais:
(1) ao fazer perguntas sempre inclua uma versão do seu programa completa, que possa replicar o erro. Nesse caso, por exemplo, o problema está na declaração da variável c e em sua não inicialização - mas vendo só o trecho de código que você colocou, não tem como saber disso. Só deu pra entender o que acontece por conta do vídeo do debug, mas isso é que não é pra ser necessário - só ver as demais perguntas do site. Quando eu digo "versão" - quer dizer que você não precisa - e em geral não deve - colocar seu programa original completo, mas sim, pegar o seu programa, e apagar tudo o que não for relacionado com o problema, mas manter um trecho compilável e que apresente o mesmo problema que motivou a pergunta.
(2) òtimo - você aprendeu a programar em C, e manipular arquivos,  e está tentando criar um programa real pra uso "de verdade". Só que C é uma das últimas linguagens que você deveria utilizar pra isso. Por ser uma linguagem de relativamente baixo nível de programação, você tem que se preocupar com detalhes como - alocar memória para cada uso de string que for fazer, usar funções desenhadas na década de 70 para manipular strings, que requerem verifição de código de erro em cada chamada, funções que são perigosas devido a não checagem de comprimento de dados - (legal, você está usando fgets em vez de fget - mas está usando scanf simples, que com uma digitação maliciosa pode dar segfault no seu programa, por exemplo).
Para aplicações desse tipo - que envolvem entrada e saída de texto, manipulação de arquivos de texto, sua aplicação vai ser umas 30 vezes mais simples (sem exagero, e umas 3 vezes menos código, pelo menos), se você a fizer numa linguagem dinâmica de alto nível - linguagens como Python, Javascript, Ruby ou PHP - por exemplo. Em todas essas, a alocação de strings como objetos internos é automática, arquivos de texto são lidos linha a linha, sem preocupação com a memória, e existem funções muito práticas embutidas para manipluar strings e verificar seu conteúdo.
Eu sugiro a linguagem Python, embora isso possa ser um pouco ao gosto do freguês - mas sério: se você acompanhar por 3 horas qualquer tutorial (em formato texto) de Python, deve ser o suficiente para você re-escrever a sua aplicação como ela está nessa linguagem e continuar o desenvolvimento a partir dali. Se conseguir ler em Inglês, recomendo mesmo o tutorial oficial da linguagem. Caso contrário, no google aparecem várias opções em português.
Por favor, entenda que isso não uma "birra" contra C - a linguagem continua sendo, possivelmente, a mais importante de todo o universo de computação - e tem nichos em que é vital, por exemplo, IoT - mas não é a melhor ferramenta para o tipo de programa que você está tentando fazer aí, nem é gentil com programadores mesmo em nível intermediário.
Comment: Muito obrigado, está resolvido!
Comment: Se resolveu seu problema, você pode marcar a resposta como "aceita".

Erro estranho em C


jquery working in all browsers except Opera

Question: I have the following jquery code which seems to be working fine in all browsers except Opera on window.load; but on window.resize, it works okay.
<code>function resizeMargin() {

    var h = $(window).height(),
        w = $(window).width(),
        wrapMargin = (h - 655) / 2,
        bgImage = wrapMargin + 105,
        pageWidth = ((w - 690) / 2) + 340;

    $('#navigation').css({'padding-top' : wrapMargin + 'px', 'display' : 'block'});
    $('#logo').css({'top' : bgImage + 'px', 'display' : 'block'});
    $('.page-content').css({'margin-top' : bgImage + 'px'});

    if (h < 670) {
        $('#navigation').css({'padding-top' : 50 + 'px', 'display' : 'block'});
        $('#logo').css({'top' : 120 + 'px',  'display' : 'block'});
        $('.page-content').css({'margin-top' : 130 + 'px'});
    }

    $('#page-right').css({'width' : pageWidth + 'px', 'display' : 'block'});
    $('#page-left').css({'display' : 'block'});

    var shiftWidth = $(window).width();
    $('#content').animate({left : shiftWidth}, 0).delay(800).css({'display' : 'block'});

}

$(window).load(function () {
    resizeMargin();
});

$(window).resize(function () {
    resizeMargin();
});
</code>
I'd really appreciate it if someone could point out where I'm going wrong. I'm pretty stumped! (and I'm not brilliant at jquery, so that doesn't help!)
Comment: might duplicate of http://stackoverflow.com/questions/2707658/window-loadfunction-problem-in-opera
Comment: so what doesn't work? are you getting an error? maybe post that
Comment: no, no error. just nothing happens unless I resize the window and then the jquery seems to kick in.
Comment: try using the window.onload = function() {resizeMargin();}
Comment: @Ibu, thanks, didn't work. @jimy, $(document).ready worked. Cheers!
Comment: but u have `$(window).resize(...)` doesn't that mean you want it to run when the window resizes?
Comment: yes, and it still works fine on window.resize.
Answer: As per jimy's comment, I used $(document).ready, rather than $(window).load and all is working fine.


How to create an entity-reference field programmatically?

Question: I'd like to know how to create an entity-reference field programmatically, and where should I put this script.
Could I call field_create_instance() in hook_form_alter()?
Answer:
Could I call field_create_instance() in hook_form_alter()?

field_create_instance() is normally called in hook_install(), or hook_enable() from a module, or an installation profile.
You don't call it in hook_form_alter(), especially if the hook is altering the node edit form: Fields are attached to bundles (content types), not to single nodes. When a node is created, its content type is already created, and any field that content type requires is created before its nodes are created.
If there is a setting form that allows users to decide which fields to attach to a content type, then field_create_instance() is called in its submission callback.
A call to field_create_instance() is normally coupled with a call to field_create_field(). To be sure the field doesn't exist, you should first call field_info_field(). It returns NULL when the field doesn't exists.


Is a subgroup of a product of two groups necessarily a product of two subgroups ?

Question: Is a subgroup of a product of two groups necessarily a product of two subgroups  ?
Thanks !
Comment: Do you mind clarifying your question a little? Is your product a *direct product*? If my product of two groups is $G \times H$, then are you asking for two subgroups of $G$ **and/or** $H$? And by saying group $A$ *is* $B$, do you mean they are isomorphic?
Comment: $S_3 \times S_3$ has a subgroup of index $2$ which is not isomorphic to a direct product of two subgroups of $S_3$.
Comment: Possible duplicate of [Is any subgroup of a direct product isomorphic to a direct product of subgroups?](http://math.stackexchange.com/questions/529023/is-any-subgroup-of-a-direct-product-isomorphic-to-a-direct-product-of-subgroups)
Comment: @Myridium-Yeah i mean a direct product and i'm asking for two subgroups of G AND H. I'm so sorry because i only study mathematics in french and i never had the chance to define these English terms.Thanks a lot.
Comment: How's this then? **Is a subgroup $S \leq G \times H$ isomorphic to $A \times B$ for some $A \leq G$ and $B \leq H$?**
Comment: Related if you are talking about isomorphisms : https://math.stackexchange.com/questions/529023
Comment: Have a look at Goursat's theorem that is generalized in (https://arxiv.org/abs/1109.0024)
Comment: @Watson: Not just related but is a duplicate of.
Answer: Not necessarily, Consider the subgroup of $\mathbb Z\times \mathbb Z$ generated by $(1,1)$
Comment: @Myridium what substance are you on?
Comment: This is the product of $\mathbb Z$ with $\{1\}$.
Comment: Am I making a dumb mistake? The way I interpret the OP's question is such that in this case, they are looking for a direct product of subgroups of $\mathbb Z$ isomorphic to the subgroup of $\mathbb Z \times \mathbb Z$ generated by $(1,1)$ (which is $\mathbb Z$).
Comment: Oh ok, I guess that makes sense. I'll try to come up with something under that interpretation.
Comment: What about this subgroup of Z² : {(x, x) / x in Z}  ?
Comment: @ZakariaOussaad - That is $\mathbb Z^2$ which is $\mathbb Z \times \mathbb Z$. The only subgroups of $\mathbb Z^2$ are $\{1\}$, $\mathbb Z$ and $\mathbb Z^2$, so this may not be a good example.


Seeking a free symbolic regression software

Question: Now that Formulize / Eureqa started charging $2500 a year for using it and having crippled the trial version, does anyone know of any replacements that can do similar things like find an equation given data points?
It was free, but is now out of the price range of anyone that's not a company or school.
(it's a symbolic regression software)
Thanks
PS: I used to input an array into Formulize which would create periodic equations with 8000-44100 variables, then I would plug the equations back into octave and create several different periodic signals from the equations.
Comment: R has a symbolic regression package: http://rsymbolic.org/projects/rgp/wiki/Symbolic_Regression
Comment: @ssde The term "symbolic regression" is a misnomer; it has little to do with symbolic computing.  It refers to automatic curve fitting: the user specifies a set of functions and allowable ways of combining them (algebraic operations, usually) and the "symbolic regression" tries to find as close a (penalized) fit as possible among the class of such functions.
Comment: FWIW, Nutonian still offers [free academic licenses of Eureqa](http://www.nutonian.com/products/eureqa/academic-license/).
Comment: For general symbolic computing, check out SymPy for a Python-based alternative to Mathematica, or Theano for another (allegedly very fast) Python solution. No personal experience with either.
Comment: @whuber good to know. I assumed it was symbolic computing as per Aksakal's answer, but apparently that's mistaken too
Answer: I am using Mathematica now, but before that REDUCE was my tool. It's under FreeBSD license. It used to be better than anything in late '90s. I'm sure that commercial packages beat it in terms of bells and whistles, but when it comes to straight symbolic math, it probably holds its own.
I've heard good things about SymPy, but have no personal experience with it.
Comment: You appear to have confounded "symbolic regresion" and "symbolic computation."  They have little in common.
Comment: Yes, jumped the gun on this one.


Edit old revision without changing the current revision

Question: I'm using revisions to keep a public archive of changes in my nodes. Is it possible for me to edit an old revision of a node (both the message and the fields) directly, and not change the current revision? Basically, what I'm trying to do is what the User Revision Edit module does, but for nodes.
So far, in my custom module, I have something like this (notice that I'm also using the Revisioning module):
/**
 * Implements hook_menu().
 */
function node_revision_edit_menu() {
  $items['node/%node/revisions/%vid/modify'] = array(
    'title' => 'Modify this revision',
    'load arguments' => array(3),
    'page callback' => 'drupal_get_form',
    'page arguments' => array('node_revision_edit_form', 1, 3),
    'access callback' => '_node_revision_edit_link_access',
    'access arguments' => array('modify revisions'),
    'file' => 'node_revision_edit.admin.inc',
  );
  return $items;
}

and the essence of the logic that I'm trying to apply:
function node_revision_edit_form($form, &$form_state, $node, $vid) {

  // Prepare loading the node edit form
  form_load_include($form_state, 'inc', 'node', 'node.pages');

  // Populate the form state.
  $form_state += form_state_defaults();

  // Save the form id for the current content type.
  $nfid = $node->type . '_node_form';

  // Rebuild the entire user edit form for our needs
  $form = drupal_retrieve_form($nfid, $form_state);
  drupal_prepare_form($nfid, $form, $form_state);

  // Setup the already existing log in the field
  $form['revision_information']['log']['#default_value'] = node_revision_list($node)[$vid]->log;

  // Set the "Modify current revision, no moderation" as the default revision operation
  $form['revision_information']['revision_operation']['#default_value'] = 0;

  // Unset the options that we do not need
  // unset($form['options']);

  // Create a new submit button since we do not want to invoke the standard callback functions
  unset($form['#submit']);
  $form['#submit'] = array('node_revision_edit_form_submit');

My problem is that I have no idea as to where to go from here. I obviously can't use node_save since it automatically handles revisions. Any ideas on what my next step should be? Is there a function that I'm missing and could be useful for my problem? Or will I have to go for direct database edits?
Any feedback is greatly appreciated.
Answer: I'm afraid that not even _node_save_revision allows that. Revisions were designed to keep old stuff archived and unchanged. Of course sometimes we need to violate that principle for the sake of moderation.
You will have to smartly adapt piece from above function:
$node->uid = $uid; // Make sure revision's author stays unchanged
drupal_write_record('node_revision', $node, $update);

I don't have time to experiment with it, but I'm sure you will find out pretty easily.
Carefully consider if you want to also call
module_invoke_all('node_presave', $node);
module_invoke_all('entity_presave', $node, 'node');

before save, and
module_invoke_all('node_' . $op, $node);
module_invoke_all('entity_' . $op, $node, 'node');

after save. Probably you don't, but it depends - some modules may use revision data for search or other purposes.
Last but not least: I must admit I have no idea how field_attach_update handles field revisions.
Comment: Thanks a lot for taking the time to share your thoughts and knowledge on the question. I have followed a different route to achieve the functionality that I'm after but it's a very "case-specific" approach. I will keep working on this and if I find a more generic solution I'll post it and probably pack it as a module for drupal.org. If not, I will post my current implementation for posterity's sake.
Comment: I know it is not a full answer. I just hope it will help OP with *"what my next step should be?"* and I'm perfectly willing to delete it if it'll get obsolete due to more complete answer posted.
Answer: Both node_save and field_attach_update can be used to update old revisions. The issue is that they also update the current revision. Other revisions are left unchanged. Node_save updates the last edited time/date, which is undesirable when updating an old revision, so field_attach_update could be a better option.
<?php

$nid = 1; //node id
$vid = 5; //revision no

$loaded_node = node_load($nid, $vid);
$original_node = node_load($nid);

//make changes to old node version here
$loaded_node->field_tags[LANGUAGE_NONE][0]['tid'] = '1';

//save the old node revision. unfortunately this updates the current node too.

field_attach_update('node', $loaded_node);
//    node_save($loaded_node); //this is possible here too

//replace the current node with its original content
field_attach_update('node', $original_node);
//    node_save($original_node); // this works but changes the last modified time etc of the current node

?>

You would normally then flush the cache for the given node after performing field_attach_update, however this might not be necessary as wouldn't imagine old revisions are cached and the current node is unchanged.
drupal_write_record would also work to make a modification at the database level, but means you are working with the database rather than a node object.
Answer: After spending some time browsing through the code of node_save() to figure out exactly how it works and testing various methods, I managed to solve my problem by performing the following steps:

Load the node's revision that the user selected to edit
Set the node's properties from the values retrieved from the $form_state
Call node_save for the specific $node object
Since the newer revisions' state changes to "pending approval", I also have to save the latest revision of the node with node_save so that it becomes current again

My submit callback function looks like this:
/**
 * Submit callback for edit revision form.
 */
function node_revision_edit_form_submit($form, &$form_state) {

  // Store the values that we will be needing
  $nid = $form['nid']['#value'];
  $vid = $form['vid']['#value'];

  // STEP 1
  $node = node_load($nid, $vid, FALSE);
  $latestvidobj = array_shift(node_revision_list($node));
  $latestvid = $latestvidobj->vid;

  // STEP 2
  $node->title = $form_state['values']['title'];
  $node->log = $form_state['values']['log'];
  $node->field_tags = $form_state['values']['field_tags'];
  $node->field_law_article_body = $form_state['values']['field_law_article_body'];

  // These are entity reference fields that accept unlimited values
  // I had to unset an 'add_more' variable that is left over in the $form_state
  unset($form_state['values']['field_article_modifies'][LANGUAGE_NONE]['add_more']);
  unset($form_state['values']['field_article_is_modified'][LANGUAGE_NONE]['add_more']);

  // And then remove an empty array left in there
  $tempfam = array_pop($form_state['values']['field_article_modifies'][LANGUAGE_NONE]);
  $tempfaim = array_pop($form_state['values']['field_article_is_modified'][LANGUAGE_NONE]);
  // Then set the $node's properties
  $node->field_article_modifies = $form_state['values']['field_article_modifies'];
  $node->field_article_is_modified = $form_state['values']['field_article_is_modified'];

  $node->field_law_free_tags = $form_state['values']['field_law_free_tags'];
  $node->field_law_article_extra_notes = $form_state['values']['field_law_article_extra_notes'];

  // STEP 3
  node_save($node);
  // STEP 4
  $latestnode = node_load($nid, $latestvid, FALSE);
  node_save($latestnode);

  // Log the revision save
  watchdog('node', "Modified node id: {$nid} and revision id: {$vid}.");

  // Notify the user that the revision was edited succesfully
  drupal_set_message(t('Updated revision %vid of node %nid.', array('%vid' => $vid, '%nid' => $nid,)), 'status');

  drupal_goto('node/' . $nid . '/revisions/' . $vid . '/list');
}

I don't like this code, since it's case-specific and I would like to find a more abstract way of passing the $form_state['values'] to the $node object. Since I have some other requirements from my editors (like the option to rearrange the revisions), I will try to find a cleaner way to do it and post it here (I may package it as a separate module and post it in drupal.org once the project is done).


Função retornando apenas um valor

Question: Estou fazendo um programa em Python e preciso implementar uma função. A função recebe como entrada dois parâmetros: Um dicionário contendo como chave o nome de um funcionário e como valor uma lista contendo email, salário-base e cargo desse funcionário.
O nome de um funcionário.

A função deve retornar como resultado o salário líquido do funcionário. O salário é calculado de acordo com regras para cada cargo.

Desenvolvedor, desconto de 15%, se salário >= 2000, senão desconto de 5%.
Analista, desconto de 20%, se salário >= 3500, senão desconto de 10%.
Gerente, desconto de 25%, se salário >= 4000, senão desconto de 15% .

No entanto quando eu implemento o código eu e rodo o arquivo de teste, ele me retorna um único resultado: Resultado da Função: 2550.0
Como faço para que ele retorne o resultado esperado para cada função e não apenas 2550.0?

Função que implementei
def calcular_salario(dicionario, nome):
    for nome in dicionario:
        if dicionario[nome][2] == 'DESENVOLVEDOR':
            if dicionario[nome][1] >= 2000:
                resultado = dicionario[nome][1] - (dicionario[nome][1] * .15)
            else:
                resultado = dicionario[nome][1] - (dicionario[nome][1] * 0.05)

        if dicionario[nome][2] == 'ANALISTA':
            if dicionario[nome][1] >= 3500:
                resultado = dicionario[nome][1] - (dicionario[nome][1] * .20)
            else:
                resultado = dicionario[nome][1] - (dicionario[nome][1] * .10)

        if dicionario[nome][2] == 'GERENTE':
            if dicionario[nome][1] >= 4000:
                resultado = dicionario[nome][1] - (dicionario[nome][1] * .25)
            else:
                resultado = dicionario[nome][1] - (dicionario[nome][1] * .15)
    return resultado

Arquivo de teste - Não posso modificar
from ac02 import calcular_salario

dicionario = {'marcilio': ['firstname.lastname@example.com', 5000.00, 'DESENVOLVEDOR'],
              'pedro': ['email@example.com', 2000.00, 'DESENVOLVEDOR'],
              'carlos': ['email@example.com', 1000.00, 'DESENVOLVEDOR'],
              'roberto': ['email@example.com', 5000.00, 'ANALISTA'],
              'renata': ['firstname.lastname@example.com', 3500.00, 'ANALISTA'],
              'angelica': ['email@example.com', 1000.00, 'ANALISTA'],
              'amanda': ['firstname.lastname@example.com', 8000.00, 'GERENTE'],
              'ricardo': ['email@example.com', 4000.00, 'GERENTE'],
              'fernanda': ['firstname.lastname@example.com', 3000.00, 'GERENTE'],
              'marcos': ['firstname.lastname@example.com', 800.00, 'ESTAGIARIO']}

try:
    resultado = calcular_salario(dicionario, 'marcilio')
    assert resultado == 4250.0
    print('CORRETO')
except AssertionError:
    print('ERRO:')
    print(' Resultado esperado: 4250.0')
    print(' Resultado da Função:', resultado)

try:
    resultado = calcular_salario(dicionario, 'pedro')
    assert resultado == 1700.0
    print('CORRETO')
except AssertionError:
    print('ERRO:')
    print(' Resultado esperado: 1700.0')
    print(' Resultado da Função:', resultado)

try:
    resultado = calcular_salario(dicionario, 'carlos')
    assert resultado == 950.0
    print('CORRETO')
except AssertionError:
    print('ERRO:')
    print(' Resultado esperado: 950.0')
    print(' Resultado da Função:', resultado)

try:
    resultado = calcular_salario(dicionario, 'roberto')
    assert resultado == 4000.0
    print('CORRETO')
except AssertionError:
    print('ERRO:')
    print(' Resultado esperado: 4000.0')
    print(' Resultado da Função:', resultado)

try:
    resultado = calcular_salario(dicionario, 'renata')
    assert resultado == 2800.0
    print('CORRETO')
except AssertionError:
    print('ERRO:')
    print(' Resultado esperado: 2800.0')
    print(' Resultado da Função:', resultado)

try:
    resultado = calcular_salario(dicionario, 'angelica')
    assert resultado == 900.0
    print('CORRETO')
except AssertionError:
    print('ERRO:')
    print(' Resultado esperado: 900.0')
    print(' Resultado da Função:', resultado)

try:
    resultado = calcular_salario(dicionario, 'amanda')
    assert resultado == 6000.0
    print('CORRETO')
except AssertionError:
    print('ERRO:')
    print(' Resultado esperado: 6000.0')
    print(' Resultado da Função:', resultado)

try:
    resultado = calcular_salario(dicionario, 'ricardo')
    assert resultado == 3000.0
    print('CORRETO')
except AssertionError:
    print('ERRO:')
    print(' Resultado esperado: 3000.0')
    print(' Resultado da Função:', resultado)

try:
    resultado = calcular_salario(dicionario, 'fernanda')
    assert resultado == 2550.0
    print('CORRETO')
except AssertionError:
    print('ERRO:')
    print(' Resultado esperado: 2550.0')
    print(' Resultado da Função:', resultado)

Answer: O problema começa aqui:
def calcular_salario(dicionario, nome):
    for nome in dicionario:

Na primeira linha, você define que a função possui o parâmetro nome, mas na segunda linha, usa essa variável no loop, ou seja o valor que foi recebido é sobrescrito a cada iteração do mesmo.
Mas na verdade você não precisa fazer um loop por todos os registros do dicionário. Perceba a estrutura do mesmo:
dicionario = {'marcilio': ['firstname.lastname@example.com', 5000.00, 'DESENVOLVEDOR'],
              'pedro': ['firstname.lastname@example.com', 2000.00, 'DESENVOLVEDOR'],
              'carlos': ['firstname.lastname@example.com', 1000.00, 'DESENVOLVEDOR'],
              etc...

Ou seja, o nome é a chave, então basta fazer dicionario[nome], que você obtém a lista contendo os demais dados do funcionário. Assim:
def calcular_salario(dicionario, nome):
    email, salario, cargo = dicionario[nome]
    if cargo == 'DESENVOLVEDOR':
        if salario >= 2000:
            return salario * 0.85
        else:
            return salario * 0.95

    if cargo == 'ANALISTA':
        if salario >= 3500:
            return salario * 0.8
        else:
            return salario * 0.9

    if cargo == 'GERENTE':
        if salario >= 4000:
            return salario * 0.75
        else:
            return salario * 0.85

Repare que já posso pegar os elementos da lista e colocá-los em variáveis:
email, salario, cargo = dicionario[nome]

Como todas as listas tem exatamente 3 elementos, não haverá problema em fazer assim.
Depois basta verificar as condições e retornar o valor. Repare que posso usar return em qualquer ponto, pois um return retorna o valor e sai da função (ou seja, ele não executa mais nada depois), e é exatamente o que preciso: se cheguei na condição que preciso, retorno o valor e pronto.
Também mudei o cálculo das porcentagens. Afinal, se há um desconto de 10%, o que sobra é 90% do salário, então basta fazer salario * 0.9 (o mesmo vale para os demais casos).

Obs: como o email não é usado na função, existe a convenção de se usar _ como nome da variável, justamente para indicar que é uma informação que não é usada:
_, salario, cargo = dicionario[nome]

Apesar de não ser usado na função, ainda sim é necessário colocá-lo, para que o Python saiba que o primeiro elemento da lista deve ser colocado ali (assim o segundo e terceiro elementos são colocados corretamente nas variáveis salario e cargo).

Função retornando apenas um valor


Scaling in linear regression

Question: The text is from Intro to Statistical Learning Page no 380.Can anyone explain the both ideas clearly with an example if possible

1) In linear regression scaling has no effect.
2)In linear regression,multiplying a variable by a factor of c will simply lead to multiplication of the corresponding coefficient estimate by a factor of 1/c, and thus will have no substantive effect on the model obtained
Answer: It does not matter for fitted values and residuals if we change the units of measurement of $X$. Consider transforming $X $ by some invertible $k\times k$ matrix $A$, $XA$ (e.g., change months of schooling to years and meters to centimeters when explaining wages).
This is seen as follows,
\begin{eqnarray*}
P_{XA}&:=&XA\bigl((XA)'XA\bigr)^{-1}(XA)'\\
&=&XA\bigl(A'X'XA\bigr)^{-1}A'X'\\
&=&XAA^{-1}(X'X)^{-1}(A')^{-1}A'X'\\
&=&P_{X}
\end{eqnarray*}
What about $\hat{\beta}$? Consider
\begin{eqnarray*}
\hat{\beta}^\circ&=&\bigl(\underbrace{A'X'}_{``X'"}\underbrace{XA}_{``X"}\bigr)^{-1}\underbrace{A'X'}_{``X'"}y\\
&=&A^{-1}(X'X)^{-1}(A')^{-1}A'X'y\\
&=&A^{-1}(X'X)^{-1}X'y\\
&=&A^{-1}\hat{\beta}
\end{eqnarray*}
That is, if
$$
A=\begin{pmatrix}
1/12&0\\
0&100
\end{pmatrix}\qquad\text{so that}\qquad A^{-1}=\begin{pmatrix}
12&0\\
0&1/100
\end{pmatrix}
$$
in the above example, the effect of a change in the regressors is, sensibly, adjusted accordingly.

Scaling in linear regression


Delete the lines containing a specific word (letter and number)

Question: I have a file as the following. I want to delete all lines the consisting H2, H4, H1 and H6 characters. For this aim, I used this command: grep -v "H1" input.gro > output.gro. But this command also deletes the lines including H11 and H10. And after 10000th row, it doesn't deletes the lines. How can I fixed my command? P.S: I should preserve the spacing between the columns in the output file.
XYX    C1    1   3.339   0.189
XYX   H11    2   3.376   0.253
XYX    H2    3   3.276   0.260
XYX   H10    4   3.262   0.127
XYX    C1    5   3.443   0.115
XYX    H4    6   3.491   0.193
XYX    H1    7   3.393   0.048
XYX    B3    8   3.552   0.057
XYX    H6    9   3.512   0.026
...    ..    .   .....   .....
XYX    H1 9998   3.294   4.293
XYX    H2 9999   3.379   4.287
XYX    H310000   3.377   4.151
XYX   H1110001   0.217   3.143
XYX    N110002   0.299   3.109
XYX   H1010003   0.318   3.022
XYX    C410004   0.277   3.096

Answer: The easiest way to hack it is to add a space after the expression. To handle multiple different characters, you can use a character class which represents one of multiple characters in your expression.
grep -v "H[1246] " input.gro > output.gro

The cleaner way to do it is to use word boundaries which are less fragile and allow grep to match the pattern only if it forms a "word" where word is defined as a sequence of alphanumeric characters and underscore.
grep -v "\bH[1246]\b" input.gro > output.gro

Comment: Thanks. How can I delete all lines the consisting H2, H4, H1 and H6 by one command?
Comment: @erhan, There must be something specific about the 1000th row that causes a problem, or the nature of your input changes after that row. You have to identify what that is.
Comment: This is an ouput file of a program. I have not changed it. After 10000th row (not 1000th), the command doesn't delete the lines including H2, H4, H1 and H6. Because those lines are next to the lines of another column. That is a big problem.
Comment: @erhan, It sounds like you need to modify the program that generates this output so that it correctly delimits its fields with a minimum of one space. It would be a tremendously terrible hack for a post-processing program to take the output and separate it based on the character count of the merged column, even though it is technically possible.
Answer: Awk is a very readable approach that requires no hacks.
awk '$2!~/H[1246]$/' input.gro > output.gro

Answer: Grep, at least some of them has -w to match only a whole word.  So you could do
grep -v -w "H1" input.gro > output.gro

or all those matches together
grep -v -w "H[1246]" input.gro > outout.gro

Given your edit about having problems when the chars from the next column run into the H1 column perhaps you can try this:
egrep -v "^.{7}H[1246]"

to anchor it to the start of the line, ignore the first 7 characters then make sure you have one of the H values you want


Find the equivalence class on a equivalence relation

Question: $m R n \iff \exists k \in \Bbb Z\ :\ m^2 - n^2 = 2k$

Determine the equivalence class of $5$
Determine quotient set $\Bbb Z/R$

How do I do this?
Answer: $m$ is in the class of $5$ if and only if
$m^2=25+2k$ for some $k$
For example $7$ is in the class because
$7^2=49=25 +2 \cdot 7$
We can set $m=5+s$ to get that
$m^2=25+s^2+2s=25+2k$
so
$s^2+2s=2k$
if $m$ is odd then $s^2$ is even then you get
$k=\frac{s^2}{2}+s$
so each odd numbers greater of $5$ are in the class of $5$
Answer: $m R n\stackrel{\text{(why?)}}\iff 2\mid m-n\lor 2\mid m+n\stackrel{\text{(why?)}}\iff 2\mid m-n$. So the equivalence class of $5$ is the set of odd numbers. And the other class is the set of even numbers.


How to apply authentication to rest endpoint URL?

Question: I can access the rest endpoint URL for a node in JSON format (e.g. https://192.168.1.235/rest_endpoint/node/1142?_format=json) even if we are not logged-in to the sever.
Is there any way to apply authentication to access this URL?
Comment: You could disable the `View published content` permission for anonymous users, and that should do it.
Comment: @tyler.frankenstein its not a **view** or **content** though ! . its rest enpoint output of a node in json format
Comment: @tyler.frankenstein , It worked by the way ! thanks .but if we need to give permission to view some pages to anonymous users , what should do ?
Answer: Since rest callbacks run through Drupal's normal roles/permissions layer, you can just disable the View published content permission for anonymous users, then they won't be able to fetch the JSON for the View.
If you need finer grained control, you'll have to use hook_node_grants().


GEM Promega 2 not producing sounds

Question: My son is practising piano on a GEM Promega 2 digital piano. Before we went on vacation I completely turned it off. When he wanted to play again today the piano does not produce any sound via the attached (working) speakers, the MIDI signal however is sent out.
Usually the GEM also took a few minutes to load the internal sounds into memory this step nows seems to happen in just a few seconds.
Is there any key combination to run some internal tests or any other thing we can try?
Answer: It's a bit terse, but I found reset & diagnostics info on Sweetwater

Hard reset: Hold Performance Edit while powering up
Diagnostics: Hold down Sounds button while powering up. Use Sounds button to step thru tests.
Comment: I am not sure if the article refers to the actual Promega 2 however it is running again. Keeping certain buttons pressed when powering up seems to be the right way.

GEM Promega 2 not producing sounds


Which team has scored the most goals during the group stage of a single UEFA Champions League?

Question: PSG just finished first of Group B in the UEFA Champions League Group stage.
PSG scored 25 times during the six games, finishing with an average goalscoring rate of 4.1666 per match.
Is this the greatest number of goals scored by a single team during the group stage? If it is not, which team has scored more goals?
Comment: I will add that the following is mentioned in the Wikipedia article [European Cup and UEFA Champions League records and statistics](https://en.wikipedia.org/wiki/European_Cup_and_UEFA_Champions_League_records_and_statistics#Specific_group_stage_records) ([current revision](https://en.wikipedia.org/w/index.php?title=European_Cup_and_UEFA_Champions_League_records_and_statistics&oldid=834461116#Specific_group_stage_records)): Most goals scored in a group stage: 25 - Paris Saint-Germain (2017–18). (No reference is given there.)
Answer: According to UEFA themselves, at December 6, 2017 this is indeed the greatest number of goals scored in a campaign, and is therefore the greatest number of goals scored in the group stage, by a single club.


Prove $ \sum_{1\leq k < n} k^{\underline{m}}=\frac{n^{\underline{m+1}}}{m+1} $ by induction on $m$

Question: I want to prove by induction the following sum:
$$ \sum_{1\leq k < n} k^{\underline{m}}=\frac{n^{\underline{m+1}}}{m+1} $$
but induction should be on $m$. Any hint will be helpful.
EDIT: $ k^{\underline{m}}= k (k-1) \cdots (k-m+1)$
Comment: $k^{\underline m}=k(k-1)\cdots (k-m+1)$? Use finite differences.
Answer: The finite difference operator $\Delta$ on sequences $f: \mathbb{N} \to \mathbb{R}$ is defined by $\Delta(f)(n) = f(n+1) - f(n)$. This operator has inverse given by the "definite-sum" operator $\Sigma$, taking a sequence $g$ to the sequence $\Sigma(g)(n) := \sum_{k = 0}^{n-1} g(k)$. We have that $\Delta \circ \Sigma$ is the identity operator, and the fact that $\Sigma\circ \Delta$ acts as the identity on functions $f$ with $f(0) = 0$ is essentially the method of telescoping sums.
Let $\binom{x}{k} = \frac{x^{\underline k}}{k!}$ be the $k^{th}$ binomial coefficient polynomial. Then the Pascal triangle identity says that as a function of $n$ we have
$$\Delta \binom{n}{k} = \binom{n+1}{k} - \binom{n}{k} = \binom{n}{k-1}$$
or if you like $\Delta \frac{x^{\underline k}}{k!} = \frac{x^{\underline{k-1}}}{(k-1)!}$, or
$$\Delta \frac{x^{\underline{m+1}}}{m+1} = x^{\underline m}$$
after a change of variable. This leads to
$$\frac{n^{\underline{m+1}}}{m+1} = \Sigma (x^{\underline m})|_{x=n} = \sum_{k=0}^{n-1} k^{\underline m}$$
as claimed.
But if you really want to see $\Delta x^{\underline{m+1}} = (m+1)x^{\underline m}$ by an induction on $m$, I would write
$$x^{\underline{m+1}} = x^{\underline m}(x-m)$$
and then apply the product rule $\Delta(f g)(n) = \Delta(f)(n) g(n+1) + f(n)\Delta(g)(n)$, together with induction on $m$.
Answer: Note that there is a very simple algebraic proof. The left is
$$[z^{(n-1)-m}] \frac{1}{1-z}
\left(\frac{d}{dz}\right)^m \frac{1}{1-z}.$$
The right is
$$\frac{1}{m+1} [z^{n-(m+1)}] \left(\frac{d}{dz}\right)^{m+1}  \frac{1}{1-z}.$$
Now observe that
$$ \left(\frac{d}{dz}\right)^m \frac{1}{1-z}
= m! \frac{1}{(1-z)^{m+1}}$$
which you may prove by induction if desired.
This gives for the left side,
$$[z^{(n-1)-m}] \frac{1}{1-z} m! \frac{1}{(1-z)^{m+1}} =
[z^{n-1-m}] m! \frac{1}{(1-z)^{m+2}},$$
and for the right side
$$ \frac{1}{m+1} [z^{n-(m+1)}] (m+1)!  \frac{1}{(1-z)^{m+2}}
= [z^{n-1-m}] m! \frac{1}{(1-z)^{m+2}}.$$
The two are the same, QED.
We have used the fact that the generating function of the sum of the first $n$ terms of a sequence is obtained from the generating function of that sequence through multiplication by $1/(1-z).$