text:
Q: MongoDB - eval Vs. db.eval I have a simple stored script in system.js collection called getAllNotes.
script code: function (x) {  return db.notes.find(); }
notes is a collection holding the data I wish to extract.
eval('getAllNotes()')  - works well and returns the data.
db.eval('getAllNotes()') - returns a JSON string with various configuration that has nothing to do
with my collection See below. Any idea? anyone understands the difference between executing eval and db.eval?
 "_mongo" : {
               "slaveOk" : false,
               "host" : "EMBEDDED"
       },
       "_db" : {
               "_mongo" : {
                       "slaveOk" : false,
                       "host" : "EMBEDDED"
               },
               "_name" : "test"
       },
       "_collection" : {
               "_mongo" : {
                       "slaveOk" : false,
                       "host" : "EMBEDDED"
               },
               "_db" : {
                       "_mongo" : {
                               "slaveOk" : false,
                               "host" : "EMBEDDED"
                       },
                       "_name" : "test"
               },
               "_shortName" : "notes",
               "_fullName" : "test.notes"
       },
       "_ns" : "test.notes",
       "_query" : {

       },
       "_fields" : null,
       "_limit" : 0,
       "_skip" : 0,
       "_batchSize" : 0,
       "_options" : 0,
       "_cursor" : null,
       "_numReturned" : 0,
       "_special" : false

A: eval takes a string of code that it executes.
db.eval, according to the docs, takes a function to call and a list of parameters to pass to that function. In other words, leave off the single quotes ' here:
db.eval(getAllNotes())

As for the difference between the two, the docs also state it:

The helper db.eval() in the mongo shell wraps the eval command. Therefore, the helper method shares the characteristics and behavior of the underlying command with one exception: db.eval() method does not support the nolock option.

Docs. Important stuff to learn things from before asking other people to do it for you.


text:
Q: Remove string from input on click? jQuery I'm trying to write my own function to wrap each string separated by a comma in a tag, I have this working, but on the 'close' click id like to remove the corresponding string from the input, is this possible at all?
jQuery
$('body').on('click', '.tag span', function(){
    $(this).parent().hide();
});
$('input').keyup(function(e) {
        $('.result').html('');
        var valueArr = $(this).val().split(',');
        for(var i=0; i<valueArr.length; i++){$('.result').append('
'+valueArr[i]+' X
')};
});

http://jsfiddle.net/Liamatvenn/7huQ4/1/

A: Try this:
$('body').on('click', '.tag span', function(){
    $(this).parent().hide();
    $(this).closest('.result').prev('input').val(""); //get the input respective to the clicked close button.
});

.closest() will get you to the parent .result and target only its previous input which generated the tag using .prev().
Demo
Much simpler, use index of the clicked tag item and remove that respective item from the array based on the same index as they are inserted in that order itself.
$('body').on('click', '.tag span', function () {
    var $parent = $(this).closest('.tag');
    var index = $parent.index(); //Get the index of the `tag`

    $(this).closest('.result').prev('input').val(function (_, value) { //use val function argument
        var values = value.split(','); //split the value
        values.splice(index, 1); //remove the item from array
        return values.join(','); //join them back
    });

    $parent.remove(); //then remove your tag
});

Demo

A: You could always modify your click handler to do something like:
$('body').on('click', '.tag span', function(){
    var $this, $input, val, arr;
    $this = $(this);
    $input = $('input');
    arr = $input.val().split(',');
    val = $this.parent().text().replace(' X','');
    arr.splice(arr.indexOf(val), 1);
    $input.val(arr.join(','));
    $this.parent().hide();
});

You can see it working at http://jsfiddle.net/eF5ev/

A: You can just store your elements in an array and remove the ones that get clicked by their index:
var $tag = $('
×
');
var tags = [];

$('.result').on('click', '.tag .close', function() {
    var $parent = $(this).parent();

    tags.splice($parent.index(), 1);
    $parent.remove();

    $('input').val(tags.join(', '));
});

$('input').keyup(function() {
    tags = []
    $('.result').empty();

    $(this.value.split(/\s*,\s*/)).each(function(index, value) {
        var tag = $tag.clone();

        tag.find('.text').text(value);
        tag.appendTo('.result');

        tags.push(value);
    });
});

Demo: http://jsfiddle.net/7huQ4/9/

A: You can input data on close button click. jquery text() method to get text inside  tag.
remove that text from input data. then remove leading and trailing commas with regular expression.
Try this one.
    $('input').keyup(function(e) {
                var input = $(this); /* Store input object for replaced value insertion */
                $('.result').html('');
                var valueArr = $(this).val().split(',');

                for (var i = 0; i < valueArr.length; i++) {
                    $('.result').append('
' + valueArr[i] + ' X
');
                }
                $('span').click(function() {
                    /* Removal of unwanted string like ' X' (close button) */
                    var data = $(this).parent().text();
                    data = data.replace($(this).text(), ""); /* Basic javascript replace() function*/
                    /* Delete unwanted commas, Store modified string to input field */
                    input.val(input.val().replace(data, '')
                                         .replace(/^[,\s]+|[,\s]+$/g, '')
                                         .replace(/,[,\s]*,/g, ','));
                });
            });

demo : http://jsfiddle.net/7uqEg/

redpajama_set_name: RedPajamaStackExchange


text:
Q: What's the highest character level in Torchlight? I was googling quite a lot for this question, but I couldn't find an answer. But what is the highest reachable character level in Torchlight?

A: The highest level attainable without the use of mods, is: 100.
With the use of mods, you can reach level 999 (Link to the mod:LVL&SkillMod)


text:
Q: Not able to install the latest django in virtualenv Hello I am trying to install latest version of django in my virtualenv through the following command.
pip install Django==3.0.5

for which I got an output as below
ERROR: Could not find a version that satisfies the requirement Django==3.0.5 (from versions: 1.1.3, 1.1.4,
1.2, 1.2.1,1.2.2, 1.2.3, 1.2.4, 1.2.5, 1.2.6, 1.2.7, 1.3, 1.3.1, 1.3.2, 1.3.3,1.3.4, 1.3.5,
1.3.6,1.3.7, 1.4, 1.4.1, 1.4.2, 1.4.3, 1.4.4, 1.4.5, 1.4.6, 1.4.7, 1.4.8, 1.4.9, 1.4.10,
1.4.11, 1.4.12, 1.4.13, 1.4.14, 1.4.15, 1.4.16, 1.4.17, 1.4.18, 1.4.19, 1.4.20, 1.4.21,
1.4.22, 1.5, 1.5.1, 1.5.2, 1.5.3, 1.5.4, 1.5.5, 1.5.6, 1.5.7, 1.5.8, 1.5.9, 1.5.10, 1.5.11,
1.5.12, 1.6, 1.6.1, 1.6.2, 1.6.3, 1.6.4, 1.6.5, 1.6.6, 1.6.7, 1.6.8, 1.6.9, 1.6.10, 1.6.11,
1.7, 1.7.1, 1.7.2, 1.7.3, 1.7.4, 1.7.5, 1.7.6, 1.7.7, 1.7.8, 1.7.9, 1.7.10, 1.7.11, 1.8a1,
1.8b1, 1.8b2, 1.8rc1, 1.8, 1.8.1, 1.8.2, 1.8.3, 1.8.4, 1.8.5, 1.8.6, 1.8.7, 1.8.8, 1.8.9,
1.8.10, 1.8.11, 1.8.12, 1.8.13, 1.8.14, 1.8.15, 1.8.16, 1.8.17, 1.8.18, 1.8.19, 1.9a1,
1.9b1, 1.9rc1, 1.9rc2, 1.9, 1.9.1, 1.9.2, 1.9.3, 1.9.4, 1.9.5, 1.9.6, 1.9.7, 1.9.8, 1.9.9,
1.9.10, 1.9.11, 1.9.12, 1.9.13, 1.10a1, 1.10b1, 1.10rc1, 1.10, 1.10.1, 1.10.2, 1.10.3,
1.10.4, 1.10.5, 1.10.6, 1.10.7, 1.10.8, 1.11a1, 1.11b1, 1.11rc1, 1.11, 1.11.1, 1.11.2,
1.11.3, 1.11.4, 1.11.5, 1.11.6, 1.11.7, 1.11.8, 1.11.9, 1.11.10, 1.11.11, 1.11.12, 1.11.13,
1.11.14, 1.11.15, 1.11.16, 1.11.17, 1.11.18, 1.11.20, 1.11.21, 1.11.22, 1.11.23, 1.11.24,
1.11.25, 1.11.26, 1.11.27, 1.11.28, 1.11.29, 2.0a1, 2.0b1, 2.0rc1, 2.0, 2.0.1, 2.0.2, 2.0.3,
2.0.4, 2.0.5, 2.0.6, 2.0.7, 2.0.8, 2.0.9, 2.0.10, 2.0.12, 2.0.13, 2.1a1, 2.1b1, 2.1rc1, 2.1,
2.1.1, 2.1.2, 2.1.3, 2.1.4, 2.1.5, 2.1.7, 2.1.8, 2.1.9, 2.1.10, 2.1.11, 2.1.12, 2.1.13,
2.1.14, 2.1.15, 2.2a1, 2.2b1, 2.2rc1, 2.2, 2.2.1, 2.2.2, 2.2.3, 2.2.4, 2.2.5, 2.2.6, 2.2.7,
2.2.8, 2.2.9, 2.2.10, 2.2.11, 2.2.12)
ERROR: No matching distribution found for Django==3.0.5

It's like it is only aware of Django==2.2.12. Then I tried running
pip install --upgrade django

for which it install the cached django
Using cached Django-2.2.12-py3-none-any.whl (7.5 MB)
Requirement already satisfied, skipping upgrade: pytz in ./SHIVAM/myapp/lib/python3.5/site-
packages (from django) (2019.3)
Requirement already satisfied, skipping upgrade: sqlparse in
./SHIVAM/myapp/lib/python3.5/site-packages (from django) (0.3.1)
Installing collected packages: django
Successfully installed django-2.2.12

my pip version is 20.0.2. Kindly help.

A: Django 2.2 is the last version where Python 3.5 is supported. Django 3.0 requires Python 3.6+. To install the latest Django upgrade your Python to at least Python 3.6, better to 3.7.


text:
Q: Update a Directus collection with fetch()-api in Vue.js I am trying to update a row from a Directus collection. I read the documentation on the topic, but I'm still not sure how to do it with the fetch() function in the <script> section of my Vue. js code. I want to update the name of the customer and this is my current code. I also tried with method: 'POST', but it doesn't work either.
await fetch('http://localhost:8055/items/customers/' + this.$route.params.id, {
      method: 'PATCH',
      body: JSON.stringify({
          "name": this.name
      })
});

A: I think even the function that I showed in the question works, but my Directus had to be manually refreshed to show the changes. I had to adjust my Directus to auto refresh every 10 seconds. I also changed my function a bit.
await fetch('http://localhost:8055/items/customers/' + this.$route.params.id, {
    method: 'PATCH',
    body: JSON.stringify({
          name: this.name
    }),
    headers: {
          'Content-type': 'application/json; charset=UTF-8',
    },
})
    .then((response) => response.json())
    .then((json) => console.log(json));


text:
Q: Html.Display, Raw not showing DateTime Converted to Local I have a List index view where one model value is an UTC timestamp. I've written code that checks to see if it's null, and if it's not outputs to the view the timestamp converted to a specified timezone. However, despite stepping through the debugger and the debugger hitting the Html.Raw.Display line and the variable showing a value of {9/29/2015 2:23:10 PM}, the td is empty
                <td>
                    @{
                        DateTime tmp;

                        //Check if not null, if not null convert to specified time zone
                        if (DateTime.TryParse(item.timestamp.ToString(), out tmp))
                        {
                            tmp = item.timestamp;
                            TimeZoneInfo cstZone = TimeZoneInfo.FindSystemTimeZoneById("Central Standard Time");
                            DateTime cstTime = TimeZoneInfo.ConvertTimeFromUtc(tmp, cstZone);

                            Html.Raw(cstTime.ToString() + " " + cstZone.StandardName); //Using Html.Display also fails
                        }
                        else
                        {
                            Html.DisplayFor(modelItem => item.timestamp);
                        }
                    }
                </td>

What am I doing wrong here with my code?

A: HtmlHelper.Raw does not output content to the page it just returns a IHtmlString with Raw content.
What is causing confusion to you is that most of the time it's used with the Razor expression:
@Html.Raw(var)

This expressions is what makes the return of the function be output to the page, but in your example your are using it directly within a code block (@{...}).
Just add @ before the call and it will work:
@Html.Raw(cstTime.ToString() + " " + cstZone.StandardName);


text:
Q: Non-Blocking Server Apache Thrift Python In one Python Module A I am doing some stuff. In the middle of doing that stuff I am creating a Thrift connection. The problem is after that connection starts, the program gets stuck in the network logic. (i.e blocking).
In module A I have:
stuff = "do some stuff"
network.ConnectionManager(host, port, ...)
stuff = "do more stuff" # not getting to this point

In network...
ConnectionManager.start_service_handler()
def start_service_handler(self):
        handler = ServiceHandler(self)
        processor = Service.Processor(handler)
        transport = TSocket.TServerSocket(port=self.port)
        tfactory = TTransport.TBufferedTransportFactory()
        pfactory = TBinaryProtocol.TBinaryProtocolFactory()
        # server = TServer.TThreadedServer(processor, transport, tfactory, pfactory)
        server = TNonblockingServer(processor, transport, tfactory, pfactory)
        logger().info('starting server...')
        server.serve()

I try this, but yet the code in module A does not continue as soon as the connection code starts.
I thought TNonblockingServer would do the trick, but unfortunately did not.

A: The code blocks at server.serve() which is by design, across all target languages supported by Thrift. The usual use case is to run a server like this (pseudo code):
init server
setup thrift protocol/tramsport stack
server.serve()
shutdown code

The "nonblocking" does not refer to the server.serve() call, rather to the code taking the actual client call. With a TSimpleServer, the server can only handle one call at a time. In contrast, the TNonblockingServer is designed to accept a number of connections in parallel.
Conclusion: If you want to run a Thrift server and also have some other work to do in parallel, or need to start and stop the server on the fly during program run, you will need another thread to achieve that.


text:
Q: Difference between brute force and Euclidean algorithms for finding GCD Why is consecutive integer checking algorithm for finding GCD considered brute force, but Euclidean algorithm is not? I am just confused about it. Is it because we are checking one by one?

A: Brute-force algorithms try every candidate solution that could be tried, see which one fits, and return its findings as the answer. For example, a brute-force GCD algorithm would start with the smaller of the two numbers, and continue down to 1, examining every single possibility, one by one, on its way down.
In contrast, Euclidean algorithm does not go one by one: it makes jumps, sometimes pretty significant ones. Moreover, it does not check each possible number to be a solution to the GCD problem at each step: its ending condition is rather different from a typical brute-force solution, which is to check if the current candidate is a solution to the problem, and stop when the answer is "yes". Euclidean algorithm checks a different condition, namely, b != 0, to decide on whether to continue or not.
These two distinctions (large steps and a different stopping condition) make the Euclidean algorithm different from brute-force algorithms.

A: A brute-force search involves trying every (reasonable) possibility.  Euclid's algorithm only checks a very small subset of those possibilities.


text:
Q: Angular ui-form-validation not working trying to create an angular ui form validation based on this tutorial https://www.youtube.com/watch?v=R-5loy9X6KE&feature=youtu.be and this github page https://github.com/nelsonomuto/angular-ui-form-validation but it doesnt seem to work.
my index page

    <link href="style.css" rel="stylesheet" />

   <form name="loginData" novalidate ng-controller="MainCtrl">

          <input type="text" name="orgCode" class="form-control" ng-model="user.orgCode" placeholder="Organization Code" validation-no-space="true" validation-field-required="true" validation-no-special-chars="true" validation-dynamically-defined="locallyDefinedValidations">

          <input type="email" name="email" class="form-control" ng-model="user.email" placeholder="Email Address" ng-required="true">

          <input type="Password" name="password" class="form-control" ng-model="user.password" placeholder="Your Password" validation-min-length="8" validation-field-required="true" validation-no-space="true" >

          <button class="button button-block button-positive" type="submit">Log in</button>

    </form>

my scripts,js file
angular.module('angularUiFormValidationApp', [
 'angularUiFormValidationApp', 'directives.customvalidation.customValidationTypes'
])

.controller('MainCtrl', function ($scope) {

  angular.extend($scope, {
      user: {
        orgCode: null,
        password: null,
        confirmPassword: null,
        email: null,
        firstName: null,
        lastName: null
      },
      locallyDefinedValidations: [
          {
              errorMessage: 'Cannot contain the number one',
              validator: function (errorMessageElement, val){
                  return /1/.test(val) !== true;
              }
          },
          {
              errorMessage: 'Cannot contain the number two',
              validator: function (errorMessageElement, val){
                  return /2/.test(val) !== true;
              }
          }
      ]
  });
});

Attached is my plunkr file
http://plnkr.co/edit/44i7Dp?p=info


text:
Q: Zooming stops working using highstock chart after updating jQuery, I am using highstock chart version v1.2.5 and highchart v2.3.5 with jQuery 1.5.1. I have to work with next version of jQuery 1.7.2. Mostly everything work correct instead of zooming. It is stopped to work.
It is zoomed by X axis.
zoomType: 'x',

Stack trace is next:

*

*Anonymous function [highstock.js] Line 572   Script

*Anonymous function [highcharts.js] Line 58   Script

*zoom [highstock.js] Line 572 Script

*Anonymous function [highstock.js] Line 480   Script

*fireEvent [highcharts.js] Line 62    Script

*a [highstock.js] Line 480    Script

*dispatch [jquery-1.7.2.min.js] Line 3    Script

*i [jquery-1.7.2.min.js] Line 3   Script

It is crashed in the next code: if (b.tracker[e.isXAxis ? "zoomX" : "zoomY"]) tracker is undefined.
Does anybody meet this issue and know any solution for this?

A: There were a number reasons for such kind of behavior:

*

*Highcharts are included in Highstock. So I only need to load the highstock.js file.

*I have implemented complex behavuior where zooming of one graph recreates other graphs. Looks like that there drag&drop calls some code that related to all graphs on page, and in some moment it calls not initialized graph. I have add some extra check for avoiding calls no initialized graphs.

This two steps solved my issue.


text:
Q: Recursive 2-sum problem involving an array and number (n), determines if n can be produced with values from the array The goal of the problem is to reach a True or False conclusion. If n can be made from a combination of numbers in an array then True, if not then False.
Example: n = 8 , arr = [2, 4], expected result is True because 4+4 = 8 or 2+2+2+2 = 8 or 2+2+4 = 8 and so on. The result would be false if n = 5 and arr= [2, 4]. No combination of those numbers will give 5 therefore the result would be false. I have started out but am running into difficulty, the code I have is below
def sum_exists(n, i, p_list=[]):

#n = the number chosen
#i = the sum of the array
#p_list = the array of numbers to be chosen from

#below are my base cases upon which the recursion depends

  #if the sum is 0 return true as there is nothing that needs to be added
  if (i == 0):
    return True

  # if the number chosen is 0 and the sum is not equal to 0 then return false as the statement
    cannot be true
  # and both individual statements need to be true for the entire statement to be true
  if (n == 0 and i != 0):
    return False

  #if the last number is the array is greater than the sum
  #we cannot add it to the sum as if would be greater than n. Therefore we ignore
  if (p_list[n-1] > i):
    return sum_exists(n-1, i, p_list)

  #checking to see if i can be obtained by removing the last number of p_list or including it
  else:
    return sum_exists(n-1, i, p_list) or sum_exists(n-1, i-p_list[n-1], p_list)

#driving function
p_list = [2, 3, 5]
i = 17
n = len(p_list)
if (sum_exists(n, i, p_list) == True):
  print('True')
else:
  print('False')

The issues I'm having

*

*I cannot perform repetitions of the array Ex n = 8, p_list = [2+4] gives False, whereas it should give true as multiple combinations can be done

*How do I get away from having to implement a driver code using print?

*How can I list multiple arrays for multiple n's in the same code?

Not expecting a solution, just some guidance

A: One way to accomplish this:
def sum_exists(n, p_list=[], current_sum=0, sum_track = []):
    if current_sum>n:
        return False

    elif current_sum == n:
        print(sum_track)
        return True

    else:
        new_sums = [current_sum + x for x in p_list]

        truth_list = [sum_exists(n, p_list, s, sum_track+[s]) for s in new_sums]
        #Printing the line below may help you understand what's going on.
        #print("Truth list: ", truth_list, "New sums:",new_sums)

        return any(truth_list)

print(sum_exists(17, [2,3,5]))

Explanation: I got rid of the i parameter you have because I approached the problem in a different way. I just have:

*

*n, the target number

*p_list, the list of possibilities we can choose from to add (with replacement)

*current_sum, which determines when to end the recursion

*sum_track, an array which shows us how we got to the final number we want (this is not necessary, but just to show you how we got to the true or false conclusion).

The logic of the code is simple. The new_sums list indicates the set of new possibilities to be considered as we keep adding. If the current_sum (which is one of the elements in new_sum) is greater than the desired number, we return False, if not, we return True.
The truth list is where the recursion occurs. Finally, the any() statement allows us to see if at least one of the returned values in the truth list is true, if it is, then we know that we can sum up to the target number with the elements in the list.
I am not sure if this is the most efficient way to do things, but I think it is illustrative.
Output:
[2, 4, 6, 8, 10, 12, 14, 17]
[2, 4, 6, 8, 10, 12, 15, 17]
[2, 4, 6, 8, 10, 12, 17]
[2, 4, 6, 8, 10, 13, 15, 17]
[2, 4, 6, 8, 10, 15, 17]
[2, 4, 6, 8, 11, 13, 15, 17]
...
[5, 10, 12, 14, 17]
[5, 10, 12, 15, 17]
[5, 10, 12, 17]
[5, 10, 13, 15, 17]
[5, 10, 15, 17]
True

(You can tell which number is being added by subtracting two consecutive numbers).

A: You can write a recursive function for one n/arr. Simply call it multiple times if you have many test cases to check (or write a separate function to go through the test cases, which doesn't require recursion):
def canSum(n,arr):
    if not n or not arr:   # zero always works, an empty arr, never does
        return n == 0
    m    = max(arr)        # start with larger numbers to maximize speed
    rest = arr.copy()      # recursion will use rest of numbers
    rest.remove(m)
    for use in reversed(range(0,n+1,m)): # multiples from large to small
        if canSum(n-use,rest):           # recurse with rest
            return True
    return False

output:
print(canSum(8,[2,4]))      # True
print(canSum(15,[2,4]))     # False
print(canSum(18,[3,4]))     # True
print(canSum(12,[3,8,5]))   # True

You can also make a non-recursive solution using a set of reachable values that you progress applying all numbers to all previous results:
def canSum(n,arr):
    reachable = set(arr)
    while reachable and n not in reachable:
        reachable = {r+a for r in reachable for a in arr if (r+a)<=n}
    return n in reachable

Note that these solutions only work if all numbers in arr are positive


text:
Q: Singleton as performance upgrade in access to database I'm writting a .NET application that implements different design patterns.
I have an idea to write singleton + flyweight pattern example.
Let's imagine I have remote database with Pizzas & ingredients. My idea is to:
on app start I would download all Pizzas and Ingredients and keep them in flyweight pattern class. Thanks to this I hope to achieve some memory save.
Moreover:I'd like to implement Singleton pattern, so the download objects are accessible without asking database. Won't this save me time, while accessing database?
Now I would only have to insert orders into database without asking for data.
Please tell me if this explanation for singleton & flyweight is reasonable.

A: Flyweight is when you have many different kinds of a single thing.
Singleton is when you have a single thing.
For example, you might use the Flyweight Pattern to describe countries. One object for Canada, one for Russia, etc. They are both countries, and share similar properties but are not necessary identical.
In contrast, you might use a singleton to represent the Earth, there can only be one Object of the Earth Class.
As for loading the whole database on start, that seems unnecessary and bad practice, a database is for holding information which you can retrieve. If you will be using the same call many times you should cache results, and if you have a huge database which requires lots of text base search you should use a lucene based search server, etc. etc.
However for simple unique SQL or LINQ calls (with EF) to a database you should call when you need to utilize the results of said call.


text:
Q: Addition of two numbers I need help to solve a really simple problem. I wrote code that adds two numbers, but only in type float. So when I write 2+2, it gives me 4.0. What do I need to do in order to get only 4? But in the same time if I write 5.2+5.3 to get 10.5?
It's homework, and should not include an if statement.
I tried all variable types, but it just gives me unrealistic numbers. I would really appreciate if someone helped.
Code
#include <stdio.h>

/*Addition of two numbers*/

 int main()
{
    float a;
    float b;
    float x;

   printf("Enter the first number:\n");
   scanf("%f", &a);

   printf("Enter the second number:\n");
   scanf("%f", &b);

   x = a + b;

   /*Printing decimal number*/

   printf("Result: %.1f + %.1f = %.1f", a, b, x);

   return 0;

}

A: I think what you want to do is to use the g format specifier for the printf instruction. This is used for printing the shortest representation. You can read more about format specifiers here: http://www.cplusplus.com/reference/cstdio/printf/
This code prints how you described: 5 + 5 = 10 and 5.1 + 5.2 = 10.3
#include <stdio.h>

int  main()
{
  float a;
  float b;
  float x;

  printf("Enter the first number:\n");
  scanf("%f", &a);

  printf("Enter the second number:\n");
  scanf("%f", &b);

  x = a + b;

  /*Printing decimal number*/

  printf("Result: %.1f + %.1f = %g\n", a, b, x);

  return 0;

}

A: If you want to be 'smart' (and I use that term loosely, rather than advisedly - and neither am I trying to detract anything from the great answer posted by @Sebi), and format your output according to the (maximum) precision of the input(s), then this will work for 'fractional' parts that aren't zero:
#include <stdio.h>

int main()
{
    float a, b, x, test;
    int aPrec = 0, bPrec = 0, xPrec = 0, iTest;

    printf("Enter the first number:\n");
    scanf("%f", &a);
    test = (float)fabs(a); // Just in case it's -ve!
    iTest = (int)(test + 0.5);
    while (test != (float)(iTest)) {
        ++aPrec;
        test *= 10.0;
        iTest = (int)(test + 0.5);
    }

    printf("Enter the second number:\n");
    scanf("%f", &b);
    test = (float)fabs(b); // Just in case it's -ve!
    iTest = (int)(test + 0.5);
    while (test != (float)(iTest)) {
        ++bPrec;
        test *= 10.0;
        iTest = (int)(test + 0.5);
    }

    x = a + b;
    xPrec = aPrec > bPrec ? aPrec : bPrec; // Or, you could use max()!!
    // The "*" precision specifiers get their values from arguments immediately …
    /// … preceding the relevant 'float' value!
    printf("Result: %.*f + %.*f = %.*f", aPrec, a, bPrec, b, xPrec, x);
    return 0;
}

What the code is doing, is to keep multiplying each input by 10 until it sees that this 'test' value is then equal to its integral (truncated) value; this is the "precision" value for each input, a and b. Now, being smart (again, I use the term loosely), it thinks that the output precision should be the greater of the two inputs.
If you don't know how the "%.*f format specifier works, I can add more details, of course.


text:
Q: Event Storming | Command | Validation | Rules | Make it visible I'm practicing event-storming, with sticky notes and stuffs.
But one thing is missing: command validation (rules to be satisfied for a command to be accepted / succeed).
How to make it visible in the whiteboard? (not just as comments sprinkled here and there). Event-storming only mentions "events" (yellow), "command" (blue), "aggregate" (pale yellow), etc. I don't see "command validation" as first-class citizen.
Any thoughts?

A: I would consider command validation as policies in event storming. Those are business rules that must be satisfied for a command to be accepted.
They will go on pink "policy" sticky note - https://eventnotes.io/pdf/cheatsheet-big-picture-exploration.pdf
I consider policies as:

*

*Control how the action plays out

*Business rules

*Decisions

*When an event occurs, you apply policy and decide what the next action is

*Reactive logic

*External decision

*Time based

*Trigger based

*Reacts on events

*Triggers commands

*Often at domain boundary

A: I had this same trouble and worked through it like this....
First understand there are different types of validation. What is the type of validation you want to do?
Do you want to validate a model to ensure the order address is correctly formatted? This would only extend to "schematic" validation and could be done synchronously as part of your command, and would be what I would call Command Validation. I would make a note somewhere with the language as this will be taken through to build the contract.
Do you want to validate that "if there isn't enough stock to complete the order the order should fail"? It is not the commands responsibility to validate business logic, it is the aggregate; and I would call this Domain Validation. I use negative events to indicate some form of validation has taken place in the aggregate.
I hope this helps


text:
Q: How to sort filenames numerically in c#? I have several files in a folder.
By default, they are displayed like this.
1.jpg
11.jpg
2.jpg
21.jpg
...

What I need is that the files are ordered numerically, taking as number
to file name
1.jpg
2.jpg
11.jpg
21.jpg

My code
string path = Server.MapPath("./");
string[] files = Directory.GetFiles(path);

A: You could try:
string[] files = Directory.GetFiles(YourDirectory).OrderBy(f =>int.Parse(Path.GetFileNameWithoutExtension(f))).ToArray();

What this does is create an array, and for every file in a directory (YourDirectory in this example), it gets the file without the extension, and adds it to the list and orders it numerically. Check the source for more similar examples.
Source

A: you can use custom Comparer - sample:
using System.Text;

var directoryInfo = new DirectoryInfo(@"D:\test");
var fileInfoCollection = directoryInfo
    .GetFiles("*.txt")
    .OrderBy(x => x.Name, new AlphanumComparator());

PrintFiles(fileInfoCollection);

void PrintFiles(IEnumerable<FileInfo> files)
{
    foreach (var file in files)
    {
        Console.WriteLine(file.Name);
    }
}

and the core AlphanumComparator class for your problem - borrowed from stack (https://stackoverflow.com/a/5402865/1187755):
/*
 * The Alphanum Algorithm is an improved sorting algorithm for strings
 * containing numbers.  Instead of sorting numbers in ASCII order like
 * a standard sort, this algorithm sorts numbers in numeric order.
 *
 * The Alphanum Algorithm is discussed at http://www.DaveKoelle.com
 *
 * Based on the Java implementation of Dave Koelle's Alphanum algorithm.
 * Contributed by Jonathan Ruckwood <jonathan.ruckwood@gmail.com>
 *
 * Adapted by Dominik Hurnaus <dominik.hurnaus@gmail.com> to
 *   - correctly sort words where one word starts with another word
 *   - have slightly better performance
 *
 * Released under the MIT License - https://opensource.org/licenses/MIT
 *
 * Permission is hereby granted, free of charge, to any person obtaining
 * a copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included
 * in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
 * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
 * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
 * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
 * USE OR OTHER DEALINGS IN THE SOFTWARE.
 *
 */
public class AlphanumComparator : IComparer<string>
{
    private enum ChunkType { Alphanumeric, Numeric };
    private bool InChunk(char ch, char otherCh)
    {
        ChunkType type = ChunkType.Alphanumeric;

        if (char.IsDigit(otherCh))
        {
            type = ChunkType.Numeric;
        }

        if ((type == ChunkType.Alphanumeric && char.IsDigit(ch))
            || (type == ChunkType.Numeric && !char.IsDigit(ch)))
        {
            return false;
        }

        return true;
    }

    public int Compare(string x, string y)
    {
        string s1 = x;
        string s2 = y ;

        if (s1 == null || s2 == null)
        {
            return 0;
        }

        int thisMarker = 0, thisNumericChunk = 0;
        int thatMarker = 0, thatNumericChunk = 0;

        while ((thisMarker < s1.Length) || (thatMarker < s2.Length))
        {
            if (thisMarker >= s1.Length)
            {
                return -1;
            }
            else if (thatMarker >= s2.Length)
            {
                return 1;
            }
            char thisCh = s1[thisMarker];
            char thatCh = s2[thatMarker];

            var thisChunk = new StringBuilder();
            var thatChunk = new StringBuilder();

            while ((thisMarker < s1.Length) && (thisChunk.Length == 0 || InChunk(thisCh, thisChunk[0])))
            {
                thisChunk.Append(thisCh);
                thisMarker++;

                if (thisMarker < s1.Length)
                {
                    thisCh = s1[thisMarker];
                }
            }

            while ((thatMarker < s2.Length) && (thatChunk.Length == 0 || InChunk(thatCh, thatChunk[0])))
            {
                thatChunk.Append(thatCh);
                thatMarker++;

                if (thatMarker < s2.Length)
                {
                    thatCh = s2[thatMarker];
                }
            }

            int result = 0;
            // If both chunks contain numeric characters, sort them numerically
            if (char.IsDigit(thisChunk[0]) && char.IsDigit(thatChunk[0]))
            {
                thisNumericChunk = Convert.ToInt32(thisChunk.ToString());
                thatNumericChunk = Convert.ToInt32(thatChunk.ToString());

                if (thisNumericChunk < thatNumericChunk)
                {
                    result = -1;
                }

                if (thisNumericChunk > thatNumericChunk)
                {
                    result = 1;
                }
            }
            else
            {
                result = thisChunk.ToString().CompareTo(thatChunk.ToString());
            }

            if (result != 0)
            {
                return result;
            }
        }

        return 0;
    }
}

if you have time run benchmark :)
Result:

*

*01.txt

*1.txt

*1a1.txt

*1a2.txt

*1a.txt

*2.txt

*3.txt

*4.txt

*11.txt

*21.txt

*aaa.txt

*bbb01.txt

*bbb02.txt

*bbb.txt

*test.txt

*z.txt


text:
Q: How can I elide additional calls to an idempotent function? Is there a way to tell gcc that a function that has side effects should only be called once if two subsequent calls have the same arguments. I want the following behaviour:
foo(6);//run this function
foo(6);//optimize this away
foo(6);//optimize this away
foo(5);//run this function
foo(6);//run this function again

I can make foo check a global variable before it does any work, but that is less than optimal.
void inline foo(int i){
   static int last_i=i+1;
   if(last_i != i){
        last_i==i;
        //do_work...
    }
}

Since foo is an inline function the compiler should be able to look across invokations of foo() and see that it doesn't have to execute it. The problem is the compiler can't optimize like that for global variables, is there a way to let the compiler know it is safe to do so?

A:
... a function that has side effects should only be called once if two subsequent calls have the same arguments...

That function has to be idempotent then although it has side effects.
C++ standard only distinguish functions with side effects (I/O functions) and without. From compilers point of view if the function is opaque (no definition in the same translation unit) then it must have side effects and therefore it is a compiler memory barrier and the compiler cannot optimize the call away or deduce the return value (unless it is a compiler intrinsic function like memcpy).
Idempotence, computer science meaning:

In computer science, the term idempotent is used more comprehensively to describe an operation that will produce the same results if executed once or multiple times.[4] This may have a different meaning depending on the context in which it is applied. In the case of methods or subroutine calls with side effects, for instance, it means that the modified state remains the same after the first call. In functional programming, though, an idempotent function is one that has the property f(f(x)) = f(x) for any value x.[5]

And C++ does not have that notion.

A: You could use static variables:
int foo(int param){
   static int last=0;
   static int result=1;
   if(last==param) return result;
   else{
      last=param;
      result=param/2+1;
      return result;
   }
}

A: in order for a compiler to optimize away a function with side effects it would have to understand the side effects it produces. GCC has no annotation to describe the type of side effects so it is not possible.
If the function is in the same compilation unit the compiler might be able to figure out the calls are redundant, but as that only works if the function is simple enough for the compiler to completely understand which is seldom the case. You are better of putting that logic into the caller or callee.
For completeness, if the function does not have side affects you can use __attribute__((pure)) and __attribute__((const)) to tell the compiler this.

A: You can use functor:
class{
        auto foo(int a);
        int last_arg;
        bool first_invoke=true;
    public:
        auto operator(int a){
            if(first_invoke){
                first_invoke=false;
                last_arg=a;
                return foo(a);
            }
            if(a==last_arg)
                //do_something_special;
            else{
                last_arg=a;
                return foo(a);
            }
        }
}foo;

This solution is Standard-dependent, not compiler-dependent.
Or you can play with foo's static varaibles.

A: No. This behavior is not part of the semantics of any language of the many I have seen and certainly not C/C++. Gcc can't provide options to compile code with wrong semantic behavior!
The reverse is possible however. If a function foo() is "pure" ie with no side effects then a good compiler will deal with eg y=foo(x)+foo(x); using only a single call to foo().  The Ada language provides a pragma to assert pureness for this purpose.

A: So the reason I was hesitant to just put a check against the last arguments used is that the function call was inside some very tight inner loops, so the extra comparison and branch instructions would be annoying especially on platforms with (or very poor) branch prediction.
I decided to see what gcc does when I tried it. I used the following code:
#include <stdio.h>
int check;

void myfun(int num){
        printf("changing to %d\n",num);
}
static inline __attribute__((always_inline)) void idem(int num){
    if(num!=check){
        myfun(num);
        check=num;
    }
}

int main(){
    idem(5);
    idem(5);
    idem(4);
    idem(4);
    return 0;
}

This compiles (gcc -O2 main.c) on x86 (not my final target) to :
0000000000400440 <main>:
  400440:       48 83 ec 08             sub    $0x8,%rsp
  400444:       83 3d e5 0b 20 00 05    cmpl   $0x5,0x200be5(%rip)        # 601030 <check>
  40044b:       74 14                   je     400461 <main+0x21>
  40044d:       bf 05 00 00 00          mov    $0x5,%edi
  400452:       e8 09 01 00 00          callq  400560 <myfun>
  400457:       c7 05 cf 0b 20 00 05    movl   $0x5,0x200bcf(%rip)        # 601030 <check>
  40045e:       00 00 00
  400461:       bf 04 00 00 00          mov    $0x4,%edi
  400466:       e8 f5 00 00 00          callq  400560 <myfun>
  40046b:       c7 05 bb 0b 20 00 04    movl   $0x4,0x200bbb(%rip)        # 601030 <check>
  400472:       00 00 00
  400475:       31 c0                   xor    %eax,%eax
  400477:       5a                      pop    %rdx
  400478:       c3                      retq
  400479:       90                      nop
  40047a:       90                      nop
  40047b:       90                      nop

So as you can see myfun is only called twice like I want. Therefore it looks like it is possible for gcc to do this correctly. If someone would like to chime in on any limitations to the optimizations here I would be very intererested


text:
Q: How to access JS object properties in Wasm (Rust)? I'm using wasm bindgen and I have following function :
#[wasm_bindgen]
pub fn obj(o: &JsValue){
console::log_1(o);
}

and in js I call this function obj({name: "john"});
and it works fine, but when i try to console::log_1(o.name);
it gives error unknown field pointing at name

A: JsValue does not have a field name. To get this field you have to declare the JS object.
Variant 1
Add serde to your dependencies:
serde = "^1.0.101"
serde_derive = "^1.0.101"

Rust code:
extern crate serde;

#[derive(Serialize, Deserialize)]
pub struct User {
    pub name: String,
}

#[wasm_bindgen]
pub fn obj(o: &JsValue){
    let user: User = o.into_serde().unwrap();
    console::log_1(user.name);
}

Variant 2
Another way is to use wasm-bindgen directly but I never used it. It should work like this I think:
#[wasm_bindgen]
pub struct User {
    pub name: String,
}

#[wasm_bindgen]
pub fn obj(o: User){
    console::log_1(o.name);
}


text:
Q: How can I make sure the stepper title does't go out of view onTap? I am implementing a stepper in which the content displays a list of choices.  Depending where the step is on the screen the scroller pushes the title out of view and only shows part of the list on tap.  This doesn't feel right from a UX point of view.
I've tried altering the physics to ClampingScrollPhysics() as advised in the widget comments but this doesn't fix the issue.  A cut down version of the program is below to help others recreate - just paste into the flutter demo project.
I've also updated flutter :-)
class _MyHomePageState extends State<MyHomePage> {
  static YourAge yourAge = YourAge();

  static Widget _ageSelector = CustomSelectorFromList(
      selections: yourAge.valueList,
      initialSelection: yourAge.currentSelectionIndex,
      onSelectionChanged: (int choice) {
        yourAge.value = yourAge.valueList[choice];
      });

  List<Step> _listSteps = [
    Step(
      title: Text("Step 1"),
      content: _ageSelector,
    ),
    Step(
      title: Text("Step 2"),
      content: _ageSelector,
    ),
    Step(
      title: Text("Step 3"),
      content: _ageSelector,
    ),
    Step(
      title: Text("Step 4"),
      content: _ageSelector,
    ),
    Step(
      title: Text("Step 5"),
      content: _ageSelector,
    ),
    Step(
      title: Text("Step 6"),
      content: _ageSelector,
    ),
    Step(
      title: Text("Step 7"),
      content: _ageSelector,
    ),
  ];

  static int _currentStep = 0;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text(widget.title),
        ),
        body: Column(
          children: <Widget>[
            Expanded(
              child: Container(
                child: Stepper(
                  steps: _listSteps,
                  physics: ClampingScrollPhysics(),
                  currentStep: _currentStep,
                  onStepTapped: (step) {
                    setState(() {
                      _currentStep = step;
                    });
                  },
                ),
              ),
            ),
          ],
        ));
  }
}

abstract class DiscreteParameter {
  final String _yourValueKey;
  final List<String> _valueList;
  final String _defaultValue;

  DiscreteParameter(this._yourValueKey, this._valueList, this._defaultValue);

  String _value;

  String get value => _value;
  set value(String value) {
    _value = value;
  }

  int get currentSelectionIndex => _valueList.indexOf(_value);
  set currentSelectionIndex(int index) => () {
        _value = _valueList[index];
      };

  List<String> get valueList => _valueList;
}

class YourAge extends DiscreteParameter {
  static String _yourAgeKey = 'yourAge';
  YourAge() : super(_yourAgeKey, _ageList, aged26to35);

  //String _yourAge = aged26to35;
  static const String agedUpto15 = "<15";
  static const String aged16to25 = "16-25";
  static const String aged26to35 = "26-35";
  static const String aged36to45 = "36-45";
  static const String aged46to55 = "46-55";
  static const String aged56to65 = "56-65";
  static const String aged66plus = "66+";
  static const List<String> _ageList = [
    agedUpto15,
    aged16to25,
    aged26to35,
    aged36to45,
    aged46to55,
    aged56to65,
    aged66plus
  ];
}

class CustomSelectorFromList extends StatefulWidget {
  final Function(int) onSelectionChanged;
  final int initialSelection;
  final List<String> selections;

  @override
  _CustomSelectorFromListState createState() => _CustomSelectorFromListState(
      onSelectionChanged: onSelectionChanged,
      initialSelection: initialSelection,
      selections: selections);

  //include a callback function to parent to react to state change
  CustomSelectorFromList(
      {Key key,
      @required this.selections,
      @required this.onSelectionChanged,
      @required this.initialSelection});
}

class _CustomSelectorFromListState extends State<CustomSelectorFromList> {
  Function(int) onSelectionChanged;
  final int initialSelection;
  final List<String> selections;
  int _listLength;
  int _value = 0;

  _CustomSelectorFromListState(
      {Key key,
      @required this.selections,
      @required this.onSelectionChanged,
      @required this.initialSelection}) {
    //state is preserved so can be set from user "shared preferences"
    _value = initialSelection;
    _listLength = selections.length;
  }

  @override
  Widget build(BuildContext context) {
    //debugPrint("list length: ${selections.length.toString()}");
    return Wrap(
      direction: Axis.vertical,
      children: List<Widget>.generate(
        _listLength,
        (int index) {
          return ChoiceChip(
            label: Text(
              "${selections[index]}",
              style: TextStyle(
                  color: _value == index ? Colors.white70 : Colors.blueGrey),
            ),
            selectedColor: Colors.blueGrey,
            disabledColor: Colors.white70,
            //labelPadding: EdgeInsets.symmetric(),
            padding: const EdgeInsets.all(10),
            selected: _value == index,
            onSelected: (bool selected) {
              setState(() {
                _value = selected ? index : null;
              });
              //callback to parent widget - index of selected item
              onSelectionChanged(index);
            },
          );
        },
      ).toList(),
    );
  }
}

I expect onTap of a step to scroll to show the step title and content below.  But if I reveal step 1, don't scroll and click step 2 then the title shoots upwards out of view and just the bottom few choice chips are shown, forcing the user to drag the list back down to view all options.

A: The given behaviour is a result of using the combination of: Column => Expanded => Stepper. The Column widget itself is not scrollable therefore if the children exceed the height (for example screen height) it will result in overflowing pixels. So the combination of Column => Stepper won't achieve the desired result. It is working in your case because you wrapped your Stepper with the Expanded widget which can be used for widgets which implements RenderFlex (what Stepper does) and will use all available space to render it and make it scrollable if necessary. So basically you could just use Stepper as the body of your Scaffold and you would achieve the same - just wanted to point that out as this might help you!
Looking into the implementation of the Stepper's onStepTapped callback, it will call the Scrollable.ensureVisible(...) function to make sure the content of one Step will be visible after being tapped. So flutter tries to avoid your given behaviour at this point. It seems as the offset which will be set in this case is being miscalculated by the combination of Column => Expanded => Stepper.
To yield a better result I tried a different approach: ListView => Stepper and set the scrollPhysics of Stepper to NeverScrollableScrollPhysics so the Stepper won't consume any scrolling input and the ListView is being used as the main scroll handler:
return Scaffold(
  appBar: AppBar(
    title: Text(widget.title),
  ),
  body: ListView(
    children: <Widget>[
      Stepper(
        steps: _listSteps,
        physics: NeverScrollableScrollPhysics(),
        currentStep: _currentStep,
        onStepTapped: (step) {
          setState(() {
            _currentStep = step;
          });
        },
      ),
    ],
  ),
);


text:
Q: Converting different classes to void* and back safely in C++ I have a map of callbacks that pass information and execute various functions throughout code, very much like events in C# but in C++.
The map is defined as
std::map<std::string, std::function<void(uint8_t*)>> mCallbacks
It is passed by reference to all subprograms
Then each class binds its callbacks as such
mCallbacks["Status_Label"] = std::bind(&MenuHandler::LabelEditCallback, this, std::placeholders::_1);
Where
bool MenuHandler::LabelEditCallback(uint8_t * m_label_data)
{
    int text_size = ((int*)m_label_text)[0];
    char* v_text = (char*)&m_label_text[1];
}

And each event gets called from a different subprogram like this:
if (mCallbacks.find("Status_Label") != mCallbacks.end())
    mCallbacks.at("Status_Label")((uint8_t*)selected_text);

This makes it easy to pass data and events around the program without making a mess of objects and references
As you can see, this is extremely unsafe, and converting from a uint8_t pointer to various data formats can easily lead to corrupted stack.
The problem is, I don't have a specific structure for callback arguments, some of them may be sending text data, others may be sending numbers.
My solution is to define structs that will be cast to void* when calling the event, and back in the callback function
Something like this (untested):
struct Label_Callback_Data
{
    Label_Callback_Data(std::string v_name, std::string v_text)
    {
        labelName = v_name;
        labelText = v_text;
        size_of = sizeof(this);
    }
    int size_of;
    std::string labelName;
    std::string labelText;
};

And I would call it like this:
if (mCallbacks.find("Status_Label") != mCallbacks.end())
    mCallbacks.at("Status_Label")((uint8_t*)Label_Callback_Data("Status_Label_name", "TEXT"))

But then how would I recover it here? If I dont know the exact size of the object?
bool  MenuHandler::LabelEditCallback(uint8_t * m_label_data)
{
    //??  Label_Callback_Data text_size =  (Label_Callback_Data*)m_label_text
}

One solution is to use object with fixed size arrays, but there has to be a C++11 solution that is safe to use, maybe something using dynamic_pointer_casts?
Also, as a bonus question, how would I know if the object passed to the callback function is smaller in size than it is expecting? Is it possible to check this and just return a false from the callback function so the program doesn't crash?
Thank you,
This code is not tested, so there may be logical mistakes I'm willing to correct per responses.

A: You should generally prefer to use a lambda instead of std::bind().
Try something more like this:
std::map<std::string, std::function<void(void*)>> mCallbacks;

struct Label_Callback_Data
{
    std::string labelName;
    std::string labelText;

    Label_Callback_Data(std::string v_name, std::string v_text)
        : labelName(v_name), labelText(v_text) { }
};

...

mCallbacks["Status_Label"] = [this](void *data){ this->LabelEditCallback(data); };

...

auto iter = mCallbacks.find("Status_Label");
if (iter != mCallbacks.end())
{
    Label_Callback_Data data("Status_Label_name", "TEXT");
    iter->second(&data);
}

...

bool MenuHandler::LabelEditCallback(void *m_label_data)
{
    Label_Callback_Data *data = static_cast<Label_Callback_Data*>(m_label_text);
    // use data->labelName and data->labelText as needed...
}

Alternatively, you could move the type-cast into the lambda itself, so LabelEditCallback() doesn't need to deal with void* at all:
std::map<std::string, std::function<void(void*)>> mCallbacks;

struct Label_Callback_Data
{
    std::string labelName;
    std::string labelText;

    Label_Callback_Data(std::string v_name, std::string v_text)
        : labelName(v_name), labelText(v_text) { }
};

...

mCallbacks["Status_Label"] = [this](void *data){ this->LabelEditCallback(static_cast<Label_Callback_Data*>(data)); };

...

auto iter = mCallbacks.find("Status_Label");
if (iter != mCallbacks.end())
{
    Label_Callback_Data data("Status_Label_name", "TEXT");
    iter->second(&data);
}

...

bool MenuHandler::LabelEditCallback(Label_Callback_Data *m_label_data)
{
    // use m_label_data->labelName and m_label_data->labelText as needed...
}

A: This is how I did it
...
//The container

std::map<std::string, std::function<void(std::shared_ptr<CallbackData::BlankData>)>> mCallbacks
...
//CALLBACK FUNCTION
bool InputManager::KeyboardCallback(std::shared_ptr<CallbackData::BlankData> callback_data)
{
    std::shared_ptr<CallbackData::Keyboard> keyboard_data = std::dynamic_pointer_cast<CallbackData::Keyboard>(callback_data);

    if (keyboard_data == nullptr)
        return false;

    ///...
}

...
//CALLBACK EVENT
if (mCallbacks.find("Keyboard") != mCallbacks.end())
{
    std::shared_ptr<CallbackData::Keyboard> keyboard_data = std::make_shared<CallbackData::Keyboard>(m_keyboardState);
    mCallbacks.at("Keyboard")(std::dynamic_pointer_cast<CallbackData::BlankData>(keyboard_data));
}

...
//Data structure
namespace CallbackData
{
    struct BlankData
    {
        virtual ~BlankData() {};
    };

    struct Keyboard : public BlankData
    {
        Keyboard(uint8_t* kb_data)
        {
            kbData = kb_data;
        }
        uint8_t* kbData;
    };
}


text:
Q: Parse CV Rule from CVM List for EMV I have succesfully retrieved the CVM List from EMV card.
0000 0000 0000 0000 4103 4203 1E03 1F02

From the EMV specification book 3, the first 4 bytes and second 4 bytes are amount and rest is CV rules. Making these the CV Rule 4103 4203 1E03 1F02
The book also shows how to parse the CV rules, as shown below:

I am assuming that I need to convert the first two bytes in a CV rule to binary and match with the table above? But why does the table above have empty cells?
Also can someone explain in a simple pseudo code algorithm to parse this?

A: Have you referred section 10.5.5 CVM Processing Logic in the same book ? It has it detailed and even as a flow cart.
As to the empty bits read as RFU.
This is how your sample is parsed.

41 03

41 => 0100 0001
Apply succeeding CV Rule if this CVM is unsuccessful
Plaintext PIN verification performed by ICC

03
If terminal supports the CVM
---------------------------------------------------

Similarly,
42 03

42
Apply succeeding CV Rule if thisCVM is unsuccessful
Enciphered PIN verified online

03
If terminal supports the CVM
----------------------------------------------------

1E03

1E
Signature (paper)

03
If terminal supports the CVM

----------------------------------------------------

1F 02

1F
No CVM required

02
If not unattended cash and not manual cash and not purchase
with cashback

A: Q: (DO) I need to convert the first two bytes in a CV rule to binary and match with the table above?
A: In the example tag 0x8E value you have:

*

*2 amounts each 4 bytes length, 8 bytes in total.

*group of 4 Cardholder Verification (CV) Rules each 2 bytes, 8 bytes total CVM list length. Where in each 2 bytes rule:

*

*Byte 1 is "Cardholder Verification Method (CVM) Code" which is binary table of in your request. Example: HEX value needs to be converted to binary format. Where HEX 0x41 == binary b01000001. Then match bits to the table 39 with CVM Codes.

*Byte 2 is "Cardholder Verification Method (CVM) Condition Code". The table with descriptions presented in EMV specification.

Q: But why does the table above have empty cells?
A: Because there are two Amounts 4 bytes each (8 HEX characters) in front of Tag value. Then exactly CVM rules list.
Q: Also can someone explain in a simple pseudo code algorithm to parse this?
A: See example of parsing CVM List tag 0x8E value.
---
# Cheef's parser.
# Copyright (C) 2008-2017 Alexander Shevelev. https://iso8583.info/
# lib   : "/lib/EMV/" - Integrated Circuit Card Specifications for Payment Systems
# tool  : "TV"
# stat  : 18 nodes, 4 lookup tables, 100.00% passed (4/4)

TV:#"8E0000000000000000410342031E031F02" # EMV, Cardholder Verification Method (CVM) List
- tag: "8E"
- val:#"0000000000000000410342031E031F02" # Cardholder Verification Method (CVM) List.
  - AmountX: "00000000" # Amount X
  - AmountY: "00000000" # Amount Y
  - CVRs:#"34313033343230333145303331463032" # CVM List
    - S1:#"4103" # Cardholder Verification Rule
      - CVMCode: "41" # Cardholder Verification Method (CVM) Code
        # _1______ - Apply succeeding CVR if CVM fails
        # __000001 - ICC Plain PIN verification
      - CVMCondition: "03" # Cardholder Verification Method (CVM) Condition Code // If terminal supports the CVM
    - S2:#"4203" # Cardholder Verification Rule
      - CVMCode: "42" # Cardholder Verification Method (CVM) Code
        # _1______ - Apply succeeding CVR if CVM fails
        # __000010 - Online Enciphered PIN verification
      - CVMCondition: "03" # Cardholder Verification Method (CVM) Condition Code // If terminal supports the CVM
    - S3:#"1E03" # Cardholder Verification Rule
      - CVMCode: "1E" # Cardholder Verification Method (CVM) Code
        # _0______ - Fail cardholder verification if CVM is unsuccessful
        # __011110 - Signature (paper)
      - CVMCondition: "03" # Cardholder Verification Method (CVM) Condition Code // If terminal supports the CVM
    - S4:#"1F02" # Cardholder Verification Rule
      - CVMCode: "1F" # Cardholder Verification Method (CVM) Code
        # _0______ - Fail cardholder verification if CVM is unsuccessful
        # __011111 - No CVM required
      - CVMCondition: "02" # Cardholder Verification Method (CVM) Condition Code // If not cash or cashback


text:
Q: Downgrade small law firm from DC to samba or workgroup? I've got a law office of about 12 attorneys and 22 total users.  Their email is hosted (Kerio), the workstations are XP Pro with Office 2003 (soon to be replaced with win7 boxes with Office 2010) and their servers (3 total) are win 2003 virtualized in a fairly complex server room.  All they've got going on is file & print, Juris for accounting (3 users) and a calendaring app called Abacus law (running from an old 2000 install on a vm).  Couldn't they do without AD?  Couldn't they switch it up to a pair of mac mini's or something much simpler?  I mean, the complexity is eating them alive and I can't help but think theres a much better way.  Has anyone ever been through the process of downgrading someone out of a domain / AD setup?  Should I tackle this?  What would be the best way to secure the centralized files if I did this?  Thanks!

A: I would continue to use Active Directory in this scenario.
Can you elaborate on the pain-points of the current setup? What seems complex and what are the user-felt experiences with the setup?
I have 8-user Active Directory installations, and they benefit from the central auth/management and policies like folder redirection. There's no downside to this type of setup, as there's a deep pipeline of Windows engineers who can help establish the initial configuration properly.
I'd reach out to a consultant to help develop a migration path. This doesn't appear to be a complex situation.


text:
Q: print 2 functions with a space between? Im trying to echo the returned value of 2 functions with a space in between, I've tried:
class="<?php echo strtolower($class).' '.is_array($arr) ? 'yes' : 'no'; ?>"

But the above doesn't output anything. Where am I going wrong?

A: Your code says "is the concatenation of strtolower(…), ' ' and a boolean truthy?" And since that's always so, it should always be outputting yes. This can best be avoided by not using concatenation but passing separate arguments to echo:
echo strtolower($class), ' ', is_array($arr) ? 'yes' : 'no';

Now the last ternary expression is unrelated to the previous two.

A: Just group up the ternary part.
echo strtolower($class).' '.(is_array($arr) ? 'yes' : 'no');

A: <?php echo strtolower('someText').' '.(is_array([]) ? 'yes' : 'no'); ?>

result: sometext yes

A: Use this:
class="<?php echo strtolower($class); ?> <?php is_array($arr) ? echo 'yes' : echo 'no'; ?>"

You print out the result of a function (which is TRUE or FALSE). In this way you output a String Yes or No.

A: I think you have to put
class="<?php echo strtolower($class).' '.(is_array($arr) ? 'yes' : 'no'); ?>"

Note the "()" around is_array


text:
Q: Execute javascript function after php redirect I have a page where a user creates an item to auction it. If he submits the item creation form, the browser automatically redirects him to the newly created page via the following line of php code:
header('Location: item.php?itemid='.$itemid);

I would like to display a notification right after the item creation (on the newly created page) saying that the item has been created. This is the (working) code I use to call the notifications:
    <script type="text/javascript">
        $(function(){
            $container = $("#container").notify();
            notifyItemCreation();
        });
    </script>

EDIT: I think people are misunderstanding the problem.
So my sellitem.php page contains a form to sell an item, if this is submitted it gets send to createitem.php, this is where I do the validation checks.
If everything is okay this is where I redirect to the newly created item.php?item='$itemid' page. I want on this (item.php?item='$itemid') page the notification to be displayed.
EDIT2: I do know how to create the item.php?itemid='$itemid' page, this gets done perfectly, it is the notification to appear that is the problem. I am using the notifications from http://www.erichynds.com/blog/a-jquery-ui-growl-ubuntu-notification-widget
Can the people who are downvoting also explain why they are.

A: You can use session variables. In the next request if a certain variable exists or indicates that the current item is new, you can echo the script tag and unset the variable.

A: You could just wrap the JS in a condition
<?php if(is_numeric($itemid)){ ?>

  <script type="text/javascript">
        $(function(){
            $container = $("#container").notify();
            notifyItemCreation();
        });
    </script>

<?php } ?>

You could use ISSET() as well


text:
Q: How did dwarves living underground handle trash and sewage? Sure, nobody really poops anyways, but maybe some dwarf somewhere did once need to poop or pee and the rest of the dwarves made some accommodation for such a contingency.
Is there any info about this in the books, any of them?
Is there any reasonable speculation about this that is either insightful or amusing?

A: This answer will mostly be opinion based, but I'll use some canonical sources to try and support my arguments and answers.
Waste
Firstly, I highly doubt Dwarves produced waste other than food waste due to the lifestyle they lead.
Food Waste
I don't think there would be much waste created by the Dwarves. They likely don't waste anything they eat, this could be because they have big appetites or because they simply dislike wasting. If any waste food is created they may be able to trade back with the Men they originally traded with for food:

Men became the chief providers of food, as herdsmen, shepherds, and land-tillers, which the Dwarves exchanged for work as builders, roadmakers, miners, and the makers of things of craft, from useful tools to weapons and arms and many other things of great cost and skill.
The History of Middle Earth: The People's of Middle Earth - Of Men and Dwarves

The Men may have found out that food waste could be used as fertilisers and would therefore be "of great cost" and the Dwarves could therefore trade that for other food.
Furthermore, one of the Dwarves in the First Age (Mîm) talked about eating roots, which could be cooked as well as hoarded "like the nuts of a squirrel"

But when they were cooked these roots proved good to eat, somewhat like bread; and the outlaws were glad of them, for they had long lacked bread save when they could steal it. 'Wild Elves know them not; Grey-elves have not found them; the proud ones from over the Sea are too proud to delve,' said Mîm.
'What is their name?' said Turin.
Mîm looked at him sidelong. 'They have no name, save in the dwarf-tongue, which we do not teach,' he said. 'And we do not teach Men to find them, for Men are greedy and thriftless, and would not spare till all the plants had perished; whereas now they pass them by as they go blundering in the wild. No more will you learn of me; but you may have enough of my bounty, as long as you speak fair and do not spy or steal.' Then again he laughed in his throat. 'They are of great worth,' he said. 'More than gold in the hungry winter, for they may be hoarded like the nuts of a squirrel, and already we were building our store from the first that are ripe. But you are fools, if you think that I would not be parted from one small load even for the saving of my life.'
The Children of Hurin: Chapter VII - Of Mîm the Dwarf

Mîm's roots may mean that dwarves didn't have to waste food as they could cook as many roots as they needed to eat. Although as isanae pointed out, Mîm is what's known as a "Petty-Dwarf", which "were banished in ancient days from the great Dwarf-cities of the east". Although, this may not make them a good representation, their name in the dwarf-tongue is known and therefore makes it likely he learnt of them when he still lived (or his ancestors) in the "great Dwarf-cities" of old.
Sewage
Dwarves show an aptitude for building tunnels or shafts to the outside. This would suggest the possibility of having shafts out of the mountain which would be used for body waste removal (and possibly other/food waste as well).

There used to be great windows on the mountain-side, and shafts leading out to the light in the upper reaches of the Mines.
[...]
huddled close together in a corner to escape the draught: there seemed to be a steady inflow of chill air through the eastern archway.
The Lord of the Rings: The Fellowship of the Ring, Chapter IV - A Journey in the Dark

Other options would include waterways or simply pumping out the waste with hand-pumps or Archimedes screws. Dwarves may have possibly used aqueducts and leats to provide flowing water to their mansions, and be used as sewage. They may also have used pumps similar to that of the Romans (below) to pump waste water out of the mountain, possibly having waste reservoirs to pump to, until having either pumped out of the mountain or up to the surface (Bearing in mind that simply because they were underground didn't mean they couldn't be at a higher altitude to the base of the mountain).

A: I always assumed they were really big into mulching and food efficiency. Sewage and crop waste goes back into the fields/mushroom fields. The high parasite risk the reprocessing would create was why dwarves were always shown to have really robust immune systems.
The dwarves in the games I run have a huge food waste taboo, and a lesser waste in general taboo. The idea of a garbage pit makes no sense to them, everything has a use. This meshes with their utilitarian industrial mind set.


text:
Q: Simple model selection example in PYMC I am currently experimenting with PYMC and I am trying out a simple example so that I start learning how things work (I am also a Python beginner, but an experienced machine learner).
I have set myself the following very simple model selection task:
Imagine we have a dataset that has been entirely generated either from model 0 or model 1 (not a mixture).

*

*Model 0 is a normal distribution with mean m0 and standard deviation
s0.

*Likewise, model 1 is also a normal distribution with mean m1 and
standard deviation s1.

*We assume that we know all parameters m0,s0,m1,s1.

*We postulate a hidden binary random variable V which indicates the model that really generated the dataset.
What we would like to do is infer the posterior of V.
I have made an attempt in the code below, but unfortunately after trying for a couple of days, I capitulate and throw myself at your feet for assistance.
The example is of course very simple and may appear contrived. What I would like to do in the future, is use PYMC for model selection. Hence, how one correctly handles a hidden indicator variable like V is important to me. Unfortunately, in my code I keep getting weird results for the posterior of V.
I hope the code below makes sense.
I thank you all for your time.
from pymc  import *
import matplotlib
from pylab import hist, show, plot, title, figure
import numpy as np
from numpy import *

#-----------------------------------------------
# Generate some data
#-----------------------------------------------

# Define means for gaussians
mu0 =  5.0
mu1 = -5.0

# Define standard deviations for gaussians
s0 = 1.0
s1 = 1.0

# This variable chooses from which model we generate the observed data.
# It can be either 0 or 1
true_model = 0

# number of data items
numData = 100

if true_model==0:
    # Generate data from first model
    data = np.random.randn(numData,1)*s0 + mu0
elif true_model==1:
    # Generate data from second model
    data = np.random.randn(numData,1)*s1 + mu1

#-----------------------------------------------
# Define variables
#-----------------------------------------------
PR = Dirichlet("priorOnModels", theta=(0.5,0.5)) # both models are equally likely
V  = Categorical('V', p=PR)

#-----------------------------------------------
# Define model log-likelihood
#-----------------------------------------------
@potential
def mymodel_loglikel(sw=V):

    if sw==0:
        loglikel = distributions.normal_like(data, mu0, 1.0/s0**2)

    elif sw==1:
        loglikel = distributions.normal_like(data, mu1, 1.0/s1**2)

    return loglikel

#-----------------------------------------------
# Run sampler
#-----------------------------------------------
simplemodel = Model([mymodel_loglikel, PR, V])
mc = MCMC(simplemodel)
mc.sample(iter=12000,burn=2000)

figure()
hist(data)
Matplot.plot(mc)
print "expectation of V variable is %.3f" % np.mean(mc.trace('V')[:])

show()

EDIT 2: Updated after Tom's suggestions
In response to a comment below, the weird behaviour I get concerning V, is that its mean posterior is always 0.0. Judging from the trace, it seems that V is not properly sampled. I suspect a minor programming error somewhere, but can't pinpoint it.
I attach  below a figure of the trace plots of V.

A: When defining a potential, the function should return the log-probability.  So instead of
return np.exp(loglikel)

You want
return loglikel

Another thing to watch out for is the expression 1/s0**2.  Make sure that s0 is float in this expression, or change it to 1.0/s0**2.
PyMC also has a bug in its choice of proposals for binary variables (documented in section 5.7.3), which I first noticed in another answer.  The fix is to add the line:
mc.use_step_method(DiscreteMetropolis, V, proposal_distribution='Prior')


text:
Q: Design an emitter-follower amplifier with bjt I'm studying the emitter-follower configuration for bjt on the book "Practical Electronics for Inventors". On pag 439 there is an example related to the design of this system. In this problem it knows the parameters Rload, Vcc, hfe and f3db, and the target is to find the other parameters:

*

*choose the value of Ic = 1mA;

*Find the resistance Re = (0.5*Vcc)/Ic;

*Find the ratio of R1/R2 such that Ve = Vb-0.6V;

Than it says that R1//R2 <= 0.1 Rin(base),dc because this prevents the voltage divider's output from lowering under loading conditions. I don't understand this statement.
My first question is: why R1 and R2 are in parallel? If you apply the simplified model (I show after) to find the quiescent operating point R2//Rin not R1//R2.
Am I wrong? Con you explain the meaning of this statement?
Thanks

Equivalent model

simulate this circuit – Schematic created using CircuitLab

A:
this prevents the voltage divider's output from lowering under loading conditions

This is correct.
R1 and R2 act as biasing resistors -- they're meant to generate a DC voltage that biases the transistor in a suitable operating point. The signal itself is injected via C1.
You could think of the four currents going into or out of this node: those from/to C1, R1, R2 and the BJT's base terminal. If we took out C1, then we'll have a certain voltage at the BJT's base terminal, biasing it at a certain operating point.
When you add C1 back in, it's going to source/sink a certain current from that equilibrium point, and therefore change the voltage on that node (by sourcing/sinking extra current from the other nodes; after all, Kirchhoff's current law must still hold.) If the current is significant in comparison to the equilibrium, then it's going to disturb the operation point and exacerbate the non-linearities of the BJT.
Therefore, making sure the bias resistors' current is significantly higher (10x in this case) than the input current is an attempt to bound the errors due to the BJT's non-linearities.

why R1 and R2 are in parallel?

Forgetting about the input voltage for a moment, transform the circuit composed of Vcc, R1 and R2 into its Thevenin equivalent model. What do you get?

If you apply the simplified model (I show after) to find the quiescent operating point R2//Rin not R1//R2. Am I wrong?

You are wrong. Nobody models BJT circuits this way. Google for (or look up in your book) "hybrid-pi model" or "T model".


text:
Q: Turborepo: Unable to resolve "expo" from "index.ts" I'm trying to run expo on a turborepo.
Running pnpm dev gives me the following error:
Unable to resolve "expo" from "index.ts"

And the simulator the following screen with the following error:
Unable to resolve module expo from /Users/xx/main/apps/expo/index.ts: expo could not be found within the project or in these directories:
  node_modules
  ../../node_modules
> 1 | import { registerRootComponent } from "expo";
    |                                        ^
  2 |
  3 | import { App } from "./src/_app";
  4 |

I have tried to delete all my node_modules.
I have tried to clean my entire project.
I have no idea what to do next.
Here is my metro.config.js:
// Learn more: https://docs.expo.dev/guides/monorepos/
const { getDefaultConfig } = require("expo/metro-config");
const path = require("path");

const projectRoot = __dirname;
const workspaceRoot = path.resolve(projectRoot, "../..");

// Create the default Metro config
const config = getDefaultConfig(projectRoot);

// Add the additional `cjs` extension to the resolver
config.resolver.sourceExts.push("cjs");

// 1. Watch all files within the monorepo
config.watchFolders = [workspaceRoot];
// 2. Let Metro know where to resolve packages and in what order
config.resolver.nodeModulesPaths = [
  path.resolve(projectRoot, "node_modules"),
  path.resolve(workspaceRoot, "node_modules"),
];
// 3. Force Metro to resolve (sub)dependencies only from the `nodeModulesPaths`
config.resolver.disableHierarchicalLookup = true;

module.exports = config;

Here is my package.json:
{
  "name": "@acme/expo",
  "version": "0.1.0",
  "main": "index.ts",
  "scripts": {
    "clean": "rm -rf .expo .turbo node_modules",
    "dev": "expo start --ios",
    "dev:android": "expo start --android",
    "dev:ios": "expo start --ios",
    "lint": "eslint",
    "type-check": "tsc --noEmit"
  },
  "dependencies": {
    "expo": "~47.0.12",
    "expo-status-bar": "~1.4.2",
    "react": "18.1.0",
    "react-dom": "18.1.0",
    "react-native": "0.70.5",
    "react-native-safe-area-context": "4.4.1",
    "expo-splash-screen": "~0.17.5"
  },
  "devDependencies": {
    "@babel/core": "^7.19.3",
    "@babel/preset-env": "^7.19.3",
    "@babel/runtime": "^7.19.0",
    "@expo/config-plugins": "^5.0.4",
    "@types/react": "^18.0.25",
    "@types/react-native": "~0.70.8",
    "eslint": "^8.30.0",
    "typescript": "^4.9.4"
  },
  "private": true
}

Thanks you for helping.

A: I couldn't get it working with pnpm (I tried for way too long), so I switched over to yarn 1 (classic) workspaces and it worked. Yarn 1 workspaces are the only workspace solution that Expo supports, so I recommend going with that.


text:
Q: import module == from module import *? I had a problem with the Django tutorial so I asked a question here.  No-one knew the answer, but I eventually figured it out with help from Robert.  Python seems to be treating import datetime the same as from datetime import *.
Working code:
import datetime
from django.db import models

class Poll(models.Model):
    question = models.CharField(max_length=200)
    pub_date = models.DateTimeField('date published')
    def __unicode__(self):
        return self.question

    def was_published_today(self):
        return self.pub_date.date() == date.today()

Not working code: (The only differences are the import statements and the last line.)
from django.db import models
import datetime

class Poll(models.Model):
    question = models.CharField(max_length=200)
    pub_date = models.DateTimeField('date published')
    def __unicode__(self):
        return self.question

    def was_published_today(self):
        return (self.pub_date() == datetime.date.today())

EDIT: I guess I wasn't clear enough.  The code produces the exact same traceback with the last line being return (self.pub_date.date() == datetime.date.today())  Me originally forgetting to add .date() is NOT the error I'm asking about.
The traceback produced by the not working code:
Traceback (most recent call last):
  File "<console>", line 1, in <module>
  File "/myDir/mySite/polls/models.py", line 11, in was_published_today
    return (self.pub_date() == datetime.date.today())
TypeError: 'datetime.datetime' object is not callable

Why on earth is it doing this?
My question is NOT about forgetting .date().  My question is: Why is datetime in my namespace without me using from datetime import *.
Note: The first question asked what it was doing.  This question asks why.
UPDATE: Suddenly it works.  With datetime.date.today() AND date.today().  My question remains though, why does date.today() work?  It seems datetime is in my local namespace without me putting there.  Why?

A: The problem in the latter snippet is with this part of your code:
return (self.pub_date() == datetime.date.today())

self.pub_date contains a datetime.datetime instance. It's not callable like that. For example:
>>> import datetime
>>> d = datetime.datetime.now()
>>> d()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'datetime.datetime' object is not callable
>>>

If you want to compare only the date, you should call it thus:
return (self.pub_date.date() == datetime.date.today())

A: As we discussed in the comments, the problem is not with the code, but the way you are updating the source. python caches modules in sys.modules. You can reload individual modules using the reload function, but for many changes it's best to reload the entire shell. In many cases it looked as though the changes had propagated because the error messages seemed to have changed, this is because python doesn't cache the source code of the file, so when it references code, it shows you the newest version. Hopefully now, you can apply the other answers with more success.

A: "My question is: Why is datetime in my namespace without me using from datetime import *."
Because you did import datetime. Then you have datetime in your namespace. Not the CLASS datetime, but the MODULE.
Python does not treat import datetime the same way as from datetime import *. Stop asking why it does that, when it does not.
>>> import datetime
>>> date.today()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'date' is not defined
>>>

There is something else happening. If it's Django magic or not, I don't know. I don't have a Django installation where I can try this at the moment. (If there is a super-quick way of making that happen, tell me. easy_installing Django wasn't enough. :) )


text:
Q: Private setters and getters I am learning OOP - I have read this answer a number of times and now slowly start to understand some of the practical uses of public interfaces (getters and setters). I understand there is no need to provide public accessors/mutators to every single object property as that breaks encapsulation.
However, in the answer, it is implied that any properties to be manipulated only within that object (i.e. those that don't have a public interface) don't require setters at all. Following this thought, that would imply the same about getters too.
When following S in SOLID, classes become quite small. As such I still use getters and setters for all my properties since adding validation to setters is easy. However, any property that shouldn't be accessed from outside the object I simply designate those setters / getters as protected.
This allows me to keep the validation for use within private methods while still restricting public access. I understand that getters and setters are used to stop other objects directly manipulating another objects properties, but as for 'private' setters / getters - is this necessary (validation aside) or even general practice?
The only other place I see reference to 'private' setters / getters is this answer which touches on inheritance and using private setters / getters to access the parent properties, which makes sense from an encapsulation perspective.

A: Consider these points:

*

*The "S" in solid does not mean "do one thing."  It means "have one responsibility."  If you find that your classes are proliferating, they may be too small.  There's nothing wrong with a class doing many things, so long as those things all pertain to a single responsibility.  Consider the case of a repository, which has several methods for accessing data, but only one responsibility (that of accessing data).

*You can validate information inside a class using ordinary methods.  Getters and setters are intended to be consumed by a client.  All other things being equal, you will confuse the fellow programmer who has to read your code after you write it, for no good reason.

A: Private getters and setters wouldn't even make that much sense, really. You would be encapsulating the encapsulation and bloat your class, making it hard to read.
The reason people create getters and setters is to restrict the client from doing something stupid with the class data, and for hiding what the class does to the data from the client.


text:
Q: Alternate app icons as on-demand resources Our largest contributor to binary size is alternate app icons. To reduce binary size and to prevent the unused alternate app icons from impacting everyone who uses our app, we'd like to move alternate app icons into Apple's on-demand resources.
Is this possible?
Currently our app icon files lack the Attributes Inspector section for on-demand resource tags, suggesting that this is not possible. (See below images.)

Image with On Demand Resource Tag section

Image without On Demand Resource Tag section


text:
Q: Criteria Query fetches all the related entities if the where clause is not specified I am trying to run a simple criteria Query. However, the output shows 4 queries being executed instead of a single query which is quite unexpected.
I am wondering, have I missed any constraints in the Domain model or Criteria Query.
Below is the domain model.

Student
    @Entity
    public class Student {

      @Id
      @GeneratedValue
      private Long id;

      @Column(nullable = false)
      private String name;

      @OneToOne(mappedBy="student", fetch = FetchType.LAZY)
      private Passport passport;

    ...
    }

Passport
@Entity
public class Passport {

    @Id
    @GeneratedValue
    private Long id;

    @Column
    private String number;

    @OneToOne
    private Student student;

}

I have used the below criteria query to fetch the student records.
I would also like to mention few points about the relationship mapping.

*

*@ManyToMany and @OneToMany relationship is by default LazyLoad.

*I have explicitly set @OneToOne as Lazy load.
CriteriaBuilder builder = em.getCriteriaBuilder();
CriteriaQuery<Student> cq = builder.createQuery(Student.class);
Root<Student> root = cq.from(Student.class);
cq.select(root);
//cq.where(builder.equal(root.get("id"), 10001L));
List<Student> resultList = em.createQuery(cq).getResultList();
resultList.forEach(s -> log.info("{}",s));

Following is the output:
    2019-01-30 15:34:40.883  INFO 13760 --- [           main] o.h.h.i.QueryTranslatorFactoryInitiator  : HHH000397: Using ASTQueryTranslatorFactory
    Hibernate:
        select
            student0_.id as id1_4_,
            student0_.name as name2_4_
        from
            student student0_
    2019-01-30 15:34:41.436 TRACE 13760 --- [           main] o.h.type.descriptor.sql.BasicExtractor   : extracted value ([id1_4_] : [BIGINT]) - [2001]
    2019-01-30 15:34:41.444 TRACE 13760 --- [           main] o.h.type.descriptor.sql.BasicExtractor   : extracted value ([name2_4_] : [VARCHAR]) - [Irshad]
    2019-01-30 15:34:41.445 TRACE 13760 --- [           main] o.h.type.descriptor.sql.BasicExtractor   : extracted value ([id1_4_] : [BIGINT]) - [2002]
    2019-01-30 15:34:41.446 TRACE 13760 --- [           main] o.h.type.descriptor.sql.BasicExtractor   : extracted value ([name2_4_] : [VARCHAR]) - [Ahmad]
    2019-01-30 15:34:41.446 TRACE 13760 --- [           main] o.h.type.descriptor.sql.BasicExtractor   : extracted value ([id1_4_] : [BIGINT]) - [2003]
    2019-01-30 15:34:41.446 TRACE 13760 --- [           main] o.h.type.descriptor.sql.BasicExtractor   : extracted value ([name2_4_] : [VARCHAR]) - [Sheikh]
    2019-01-30 15:34:41.460 TRACE 13760 --- [           main] org.hibernate.type.CollectionType        : Created collection wrapper: [com.initgrep.jpademo.student.Student.addresses#2001]
    2019-01-30 15:34:41.460 TRACE 13760 --- [           main] org.hibernate.type.CollectionType        : Created collection wrapper: [com.initgrep.jpademo.student.Student.courses#2001]
    Hibernate:
        select
            passport0_.id as id1_2_1_,
            passport0_.number as number2_2_1_,
            passport0_.student_id as student_3_2_1_,
            student1_.id as id1_4_0_,
            student1_.name as name2_4_0_
        from
            passport passport0_
        left outer join
            student student1_
                on passport0_.student_id=student1_.id
        where
            passport0_.student_id=?
    2019-01-30 15:34:41.465 TRACE 13760 --- [           main] o.h.type.descriptor.sql.BasicBinder      : binding parameter [1] as [BIGINT] - [2001]
    2019-01-30 15:34:41.466 TRACE 13760 --- [           main] o.h.type.descriptor.sql.BasicExtractor   : extracted value ([id1_4_0_] : [BIGINT]) - [2001]
    2019-01-30 15:34:41.466 TRACE 13760 --- [           main] o.h.type.descriptor.sql.BasicExtractor   : extracted value ([id1_2_1_] : [BIGINT]) - [4001]
    2019-01-30 15:34:41.467 TRACE 13760 --- [           main] o.h.type.descriptor.sql.BasicExtractor   : extracted value ([number2_2_1_] : [VARCHAR]) - [E1001]
    2019-01-30 15:34:41.467 TRACE 13760 --- [           main] o.h.type.descriptor.sql.BasicExtractor   : extracted value ([student_3_2_1_] : [BIGINT]) - [2001]
    2019-01-30 15:34:41.475 TRACE 13760 --- [           main] org.hibernate.type.CollectionType        : Created collection wrapper: [com.initgrep.jpademo.student.Student.addresses#2002]
    2019-01-30 15:34:41.476 TRACE 13760 --- [           main] org.hibernate.type.CollectionType        : Created collection wrapper: [com.initgrep.jpademo.student.Student.courses#2002]
    Hibernate:
        select
            passport0_.id as id1_2_1_,
            passport0_.number as number2_2_1_,
            passport0_.student_id as student_3_2_1_,
            student1_.id as id1_4_0_,
            student1_.name as name2_4_0_
        from
            passport passport0_
        left outer join
            student student1_
                on passport0_.student_id=student1_.id
        where
            passport0_.student_id=?
    2019-01-30 15:34:41.476 TRACE 13760 --- [           main] o.h.type.descriptor.sql.BasicBinder      : binding parameter [1] as [BIGINT] - [2002]
    2019-01-30 15:34:41.477 TRACE 13760 --- [           main] o.h.type.descriptor.sql.BasicExtractor   : extracted value ([id1_4_0_] : [BIGINT]) - [2002]
    2019-01-30 15:34:41.477 TRACE 13760 --- [           main] o.h.type.descriptor.sql.BasicExtractor   : extracted value ([id1_2_1_] : [BIGINT]) - [4002]
    2019-01-30 15:34:41.477 TRACE 13760 --- [           main] o.h.type.descriptor.sql.BasicExtractor   : extracted value ([number2_2_1_] : [VARCHAR]) - [E1002]
    2019-01-30 15:34:41.478 TRACE 13760 --- [           main] o.h.type.descriptor.sql.BasicExtractor   : extracted value ([student_3_2_1_] : [BIGINT]) - [2002]
    2019-01-30 15:34:41.478 TRACE 13760 --- [           main] org.hibernate.type.CollectionType        : Created collection wrapper: [com.initgrep.jpademo.student.Student.addresses#2003]
    2019-01-30 15:34:41.478 TRACE 13760 --- [           main] org.hibernate.type.CollectionType        : Created collection wrapper: [com.initgrep.jpademo.student.Student.courses#2003]
    Hibernate:
        select
            passport0_.id as id1_2_1_,
            passport0_.number as number2_2_1_,
            passport0_.student_id as student_3_2_1_,
            student1_.id as id1_4_0_,
            student1_.name as name2_4_0_
        from
            passport passport0_
        left outer join
            student student1_
                on passport0_.student_id=student1_.id
        where
            passport0_.student_id=?
    2019-01-30 15:34:41.479 TRACE 13760 --- [           main] o.h.type.descriptor.sql.BasicBinder      : binding parameter [1] as [BIGINT] - [2003]
    2019-01-30 15:34:41.479 TRACE 13760 --- [           main] o.h.type.descriptor.sql.BasicExtractor   : extracted value ([id1_4_0_] : [BIGINT]) - [2003]
    2019-01-30 15:34:41.479 TRACE 13760 --- [           main] o.h.type.descriptor.sql.BasicExtractor   : extracted value ([id1_2_1_] : [BIGINT]) - [4003]
    2019-01-30 15:34:41.480 TRACE 13760 --- [           main] o.h.type.descriptor.sql.BasicExtractor   : extracted value ([number2_2_1_] : [VARCHAR]) - [E1003]
    2019-01-30 15:34:41.480 TRACE 13760 --- [           main] o.h.type.descriptor.sql.BasicExtractor   : extracted value ([student_3_2_1_] : [BIGINT]) - [2003]
    2019-01-30 15:34:41.480 DEBUG 13760 --- [           main] o.h.stat.internal.StatisticsImpl         : HHH000117: HQL: select generatedAlias0 from Student as generatedAlias0, time: 61ms, rows: 3
    2019-01-30 15:34:41.484  INFO 13760 --- [           main] i.StatisticalLoggingSessionEventListener : Session Metrics {
        170294 nanoseconds spent acquiring 1 JDBC connections;
        0 nanoseconds spent releasing 0 JDBC connections;
        **5107615 nanoseconds spent preparing 4 JDBC statements;
        5699493 nanoseconds spent executing 4 JDBC statements;**
        0 nanoseconds spent executing 0 JDBC batches;
        0 nanoseconds spent performing 0 L2C puts;
        0 nanoseconds spent performing 0 L2C hits;
        0 nanoseconds spent performing 0 L2C misses;
        0 nanoseconds spent executing 0 flushes (flushing a total of 0 entities and 0 collections);
        0 nanoseconds spent executing 0 partial-flushes (flushing a total of 0 entities and 0 collections)

I am assuming, the Criteria Query does not respect the declared FetchType.LAZY on the entity. Since Student -> Passport is a 1-1 relationship. It is fetched eagerly.
If I add the below where clause.
cq.where(builder.equal(root.get("id"), 10001L))

It only fetches the student and no other relationships are fetched as verified by the below output.
        Hibernate:
        select
            student0_.id as id1_4_,
            student0_.name as name2_4_
        from
            student student0_
        where
            student0_.id=10001
    2019-01-30 15:43:12.662 DEBUG 5964 --- [           main] o.h.stat.internal.StatisticsImpl         : HHH000117: HQL: select generatedAlias0 from Student as generatedAlias0 where generatedAlias0.id=10001L, time: 22ms, rows: 0
    2019-01-30 15:43:12.665  INFO 5964 --- [           main] i.StatisticalLoggingSessionEventListener : Session Metrics {
        169108 nanoseconds spent acquiring 1 JDBC connections;
        0 nanoseconds spent releasing 0 JDBC connections;
        4718825 nanoseconds spent preparing 1 JDBC statements;
        7554940 nanoseconds spent executing 1 JDBC statements;
        0 nanoseconds spent executing 0 JDBC batches;
        0 nanoseconds spent performing 0 L2C puts;
        0 nanoseconds spent performing 0 L2C hits;
        0 nanoseconds spent performing 0 L2C misses;
        0 nanoseconds spent executing 0 flushes (flushing a total of 0 entities and 0 collections);
        0 nanoseconds spent executing 0 partial-flushes (flushing a total of 0 entities and 0 collections)

UPDATE: Insert script.

INSERT INTO STUDENT(id,name) VALUES (2001, 'Irshad');
INSERT INTO STUDENT(id,name) VALUES (2002, 'Ahmad');
INSERT INTO STUDENT(id,name) VALUES (2003, 'Sheikh');

INSERT INTO PASSPORT(id, number, student_id) VALUES (4001, 'E1001', 2001);
INSERT INTO PASSPORT(id, number, student_id) VALUES (4002, 'E1002', 2002);
INSERT INTO PASSPORT(id, number, student_id) VALUES (4003, 'E1003', 2003);

A: since you are using mappedby in the Student entity, it makes Passport the owner of relation and it has to be loaded when you load the Student.
One option is to make Student the owner like this:
Student mapping
 @OneToOne( fetch = FetchType.LAZY)
 private Passport passport;

Passport mapping
@OneToOne(mappedBy="passport")
private Student student;

by doing this passport_id will be added to student table. If that is not possible for you you can either make the OneToOne relation unidirectional(Student -> Passport) or use NO_PROXY option.