text:
Q: Is it better to use Python's lru_cache / memoize feature on public functions or lower-level private functions, or does it matter? In Python 3, given public & private functions, something like this:
def my_public_function(a, b, c) -> int:
    rv = _my_private_function(a, b, c)
    return rv

def _my_private_function(a, b, c) -> int:
    return a + b + c

If I want to optimize this using functools.lru_cache, am I better to do that on the public function or the private one?
My instinct is the public function so that it's cached as early as possible and returned without touching anything further.
from functools import lru_cache

@lru_cache()
def my_public_function...

Is there any design pattern or other design principle which would suggest using @lru_cache() on _my_private_function instead?

A: You save time (a function call and 2 adds) by handling this in the public function.  In python there isn't really a notion of "private" functions.  The convention starting a name with _ to tell others to stay away but there is nothing language specific to it.  So it has no affect on any calling function, including lru_cache.

A: There is no general-purpose answer to this, because there basically aren't any cases where the choice of where to put the cache has no effect. If there were such a case, put it on the public function to skip the extra function call and whatever other setup work the public function has to do. But that's just never going to come up. Instead, it's going to be something like:

*

*The helper function is trivial, as in your example, and the cost of the extra function call is on the same scale as the other things you're trying to optimize away. Then you almost certainly want to inline the helper into the public function, and then there's only one place to memoize.

*The helper function is trivial, but it's called by a bunch of different public functions. Giving each public function its own cache that duplicates the work done by all the other caches is going to waste far lot more resources, and lead to a lot more cache misses, than optimizing out the wrapper stuff will save.

*The helper is nontrivial, leading to an actual semantic difference between LRU'ing the helper cache vs. the top-level cache. So you have to decide based on which one is correct, not based on a performance issue.

*The helper is nontrivial, and it doesn't really matter semantically when you cache things—but you regularly call the helper with the same values even for different inputs to the public function. So the gain from memoizing the helper will vastly swamp the microoptimization of memoizing before the extra function call instead of after it.

And so on.


text:
Q: Java - Looping over complex collection of Objects I have a general question about looping over a collection containing a complex object.

*

*I have a Collection<Object>, which contains an Array<E> of LinkedHashMap<K,V> that I'm trying to extract values from.

*I have tried various loops to get to the Key, Value pair but with no luck, something like;

The object looks like;

Collection<Object> dsidsToExclude = Arrays.asList(param.get("idsToExclude"));
    for(Object id : dsidsToExclude) {
            if(id instanceof ArrayList) {
            // Loop over the list of <K,V>
            for(Object kv : id) {
               // I want to get extract the kv pairs here..
              }
            }
        }

I want to know what the best way of doing this efficiently, any suggestions? Thanks.

A: As long as the contents of the input collection may be specified as Collection<List<Map<K, V>>> (note use of interfaces List and Map instead of implementations ArrayList and LinkedHashMap), it would be more appropriate to implement a generic method typed with K, V to get rid of instanceof and explicit casting:
public static <K, V> doSomething(Collection<List<Map<K, V>>> input) {
    for (List<Map<K, V>> list : input) {
        for (Map<K, V> map : list) {
            for (Map.Entry<K, V> entry : map.entrySet()) {
                // do what is needed with entry.getKey() , entry.getValue()
            }
        }
    }
}

Similarly, methods forEach may be used for the collection, list, and map:
public static <K, V> doSomethingForEach(Collection<List<Map<K, V>>> input) {
    input.forEach(list ->
        list.forEach(map ->
            map.forEach((k, v) -> // do what is needed with key k and value v
                System.out.printf("key: %s -> value: %s%n", k, v);
            );
        )
    );
}

Also, it is possible to use Stream API, particularly flatMap to access contents of all innermost maps. Optionally, null values may be filtered as shown below
public static <K, V> doSomethingStream(Collection<List<Map<K, V>>> input) {
    input.stream()                 // Stream<List<Map<K, V>>>
         .filter(Objects::nonNull) // discard null entries in collection
         .flatMap(List::stream)    // Stream<Map<K, V>>
         .filter(Objects::nonNull) // discard null entries in list
         .flatMap(map -> map.entrySet().stream()) // Stream<Map.Entry<K, V>>
         .forEach(e -> System.out.printf(
             "key: %s -> value: %s%n", e.getKey(), e.getValue()
         ));
}

A: Arrays.asList(something) will generate list with one element. You do not need to do it.
Object object = param.get("idsToExclude");

You can check object and cast to list.
if (object instanceof List) {
  List list = (List) object;
}

Every item in the list needs to be checked and cast.
for (Object item : list) {
  if (item instanceof Map) {
    Map map = (Map) item;
  }
}

You can get key and value from map item.
Object key = map.getKey();
Object value = map.getValue();

Full example:
Object object = param.get("idsToExclude");
if (object instanceof List) {
  List list = (List) object;
  for (Object item : list) {
    if (item instanceof Map) {
      Map map = (Map) item;
      Object key = map.getKey();
      Object value = map.getValue();
      // You can cast key and value to other object if you need it
    }
  }
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Google App Engine get PolyModel as child class When I run Google App Engine likeso:
 from google.appengine.ext import db
 from google.appengine.ext.db import polymodel

 class Father(polymodel.PolyModel):
      def hello(self):
          print "Father says hi"

 class Son(Father):
      def hello(self):
          print "Spawn says hi"

When I run, e.g.
 s = Son()
 s.put()

 son_from_father = Father.get_by_id(s.key().id())

 son_from_father.hello()

This prints "Father says hi". I would expect this to print "Son says hi". Does anyone know how to make this do what's expected, here?
EDIT:
The problem was, ultimately, that I was saving Spawn objects as Father objects. GAE was happy to do even though the Father objects (in my application) have fewer properties. GAE didn't complain because I (silently) removed any values not in Model.properties() from the data being saved.
I've fixed the improper type saving and added a check for extra values not being saved (which was helpfully a TODO comment right where that check should happen). The check I do for data when saving is basically:
def save_obj(obj, data, Model):
   for prop in Model.properties(): # checks/other things happen in this loop
      setattr(obj, prop, data.get(prop))

   extra_data = set(data).difference(Model.properties())
   if extra_data:
      logging.debug("Extra data!")

The posts here were helpful - thank you. GAE is working as expected, now that I'm using it as directed. :)

A: I can't reproduce your problem -- indeed, your code just dies with an import error (PolyModel is not in module db) on my GAE (version 1.2.5).  Once I've fixed things enough to let the code run...:
import wsgiref.handlers
from google.appengine.ext import webapp
from google.appengine.ext.db import polymodel

class Father(polymodel.PolyModel):
    def hello(self):
        return "Father says hi"

class Son(Father):
    def hello(self):
        return "Spawn says hi"

class MainHandler(webapp.RequestHandler):

  def get(self):
    s = Son()
    s.put()
    son_from_father = Father.get_by_id(s.key().id())
    x = son_from_father.hello()
    self.response.out.write(x)

def main():
  application = webapp.WSGIApplication([('/', MainHandler)],
                                       debug=True)
  wsgiref.handlers.CGIHandler().run(application)

if __name__ == '__main__':
  main()

...I see "Spawn says hi" as expected.  What App Engine release do you have?  What happen if you use exactly the code I'm giving?

A: You did a "Father.get..." so you created an object from the Father class.
So why wouldn't it say "Father says hi".
If you Father class had lastname and firstname, and your Son class had middle name, you won't get the middle name unless you specifically retrieve the 'Son' record.
If you want to do a polymorphic type query, here's one way to do it. I know it works with attributes, but haven't tried it with methods.
 fatherList = Father.all().fetch(1000)
 counter = 0
 #I'm using lower case father for object and upper case Father for your class...
 for father in fatherList:
     counter += 1
     if isinstance(father,Son):
        self.response.out.write("display a Son field or do a Son method")
     if isinstance(father,Daughter):
        self.response.out.write("display a Daughter field or do a Daughter method")

Neal Walters


text:
Q: OpenGL texture with transparency (alpha) I'm trying to render a texture with part opaque color and other part with transparency.
This is my draw function for the object:
void drawHighGrass(){
glDisable(GL_LIGHTING);
glClearColor(1.0, 1.0, 1.0, 1.0);
glColor4f(1.0, 1.0, 1.0, 1.0);

glDisable(GL_DEPTH_TEST);

glDepthMask(GL_FALSE);

glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

glEnable(GL_TEXTURE_2D);
glBindTexture(GL_TEXTURE_2D, texturas[HIGH_GRASS]);

glPushMatrix();
//glTranslatef(1000, 0, 1000);
glBegin(GL_QUADS);
glTexCoord2f(0.0f, 0.0f); glVertex3f(0, 0, 0);
glTexCoord2f(1.0f, 0.0f); glVertex3f(100, 0, 0);
glTexCoord2f(1.0f, 1.0f); glVertex3f(100, 40, 0);
glTexCoord2f(0.0f, 1.0f); glVertex3f(0, 40, 0);
glEnd();

glPopMatrix();

glDisable(GL_TEXTURE_2D);

glEnable(GL_DEPTH_TEST);
glDisable(GL_BLEND);
glDepthMask(GL_TRUE);
glEnable(GL_LIGHTING);

}

The problem is that in the transparent part it's showing solid white. I can make the texture transparent by using glColor4f(1.0, 1.0, 1.0, 0.5) but that's not what I want because it makes the entire texture transparent and not only the transparent part.
I've checked, my texture files is a PNG with transparency.

A: Restating the solution here so others can find it easily.
Your rendering code seems to be correct, so what seems to have been the problem was the texture loading code. When loading a texture, you must be sure that you are passing in the correct flags for the internal texture pixel format (GL_RGBA8, GL_RGBA16, etc.) as well as the source image pixel format (GL_RGBA or GL_BGRA, etc.).


text:
Q: How to change what a zombie is holding Problem
I am setting up a disguising system on Minecraft meant for a server that my friends and I are recording on. What I have right now is this:
tp @e[type=Zombie,name=Rocket] jackmaster110

The idea is that these stay in a repeating command block and the mob seems to be you. The problem is that the items you hold still appear and the mob doesn't hold it. I though, "No problem, I can just use some testfor commands." I set up commands to check which hotbar slot the player is on, and since the series is a roleplay, the hotbar will be preset. Anyway, after setting this up, I realized I had no idea how to make the mob switch items. I did some digging online and found nothing useful. The testfor command is here if you're wondering:
testfor jackmaster110 {SelectedItemSlot:0}

I am aware there is a plugin for this, but it isn't compatible with the replay mod which is what I'm using to record most of the shots.
Background
The series is a Guardians of the Galaxy 1.5 roleplay and we need a Baby Groot (retextured baby zombie pigman), a Rocket (retextured baby zombie), and a Drax (retextured iron golem). That's why we need the disguising.
Other Help
If this isn't possible, does anyone know a disguise plugin that will work with the mod, want to be our camera, or know of a different mod that can work with iDisguise. The last thing I wanted to ask is if anyone knows a way to stop the weird head movement the mob has.

A: This will probably work:
/replaceitem entity <selector> <slot> <item> [amount]
(entity is not a placeholder)
In the above command:
<selector> must be a player name or entity selector.
<slot> is the inventory slot where the item must be placed (see below).
<item> is the item ID (e.g. minecraft:golden_sword).
[amount] is the how many of the items to stack (must be between 0 and 65, but is optional).
Slots for mobs include:
slot.armor.chest
slot.armor.feet
slot.armor.head
slot.armor.legs
slot.weapon.mainhand
slot.weapon.offhand
Remember, not all mobs will show or make use of the added item. A spider might have a sword, but what is it supposed to do with it?
Oh, and how are you supposed to know which zombie/Rocket you want to mess with? Selectors in Minecraft are a bother, but they work. You'll probably have to give it a custom attribute, such as a name. Give a Summoned mob a name like so:
/summon Zombie x y z {CustomName:"Rocket",IsBaby:1b}
(I don't think you can use spaces for the selecting in the replaceitem command, so best just to use one word names for now. Even underscores can work.)
Now, to give it a sapling!
/replaceitem entity @e[name="Rocket"] slot.weapon.mainhand minecraft:sapling 4 1
There are more things you can do with this command, but I think that this is all you need for what you want to accomplish. I got this information from the Minecraft Gamepedia site for commands, and the more complicated stuff can also be found there.


text:
Q: How to pass sensitive data to the IConfiguration interface during startup? I want to use the configuration setup for my .NET Core Web API. I installed the Microsoft.Extensions.Configuration package for the DI container.
First of all I have 4 config files

*

*appsettings.json
Whenever all three environments use the same config value, this is the file where to put it

*appsettings.Development.json
Basic config values for development purposes only. E.g. database connection points to localhost and token secret is "secret", example:
.
{
  "Database": {
    "ConnectionString": "Server=localhost;Port=3306;Database=db;Uid=root;Pwd=admin;Pooling=true;"
  }
}

*

*appsettings.Staging.json
Almost the same as the development file

*appsettings.Production.json
Things are different here. I can't put sensitive information to that file, e.g. token secret. These values should come from the environment variable
So in my code I can access the config values via dependency injection
public class MyClass
{
    public MyClass(IConfiguration configuration)
    {
        string databaseConnectionString = configuration["Database:ConnectionString"];
    }
}

but what if the code runs in production mode? The information doesn't exist in the production file so I would have to read from the environment variables.
Would I have to create an environment variable called Database:ConnectionString and .NET Core maps all the system environment variables into the configuration file during startup if they don't exist? Or how would I pass in sensitive data to the configuration?

A: With the default builder, ASP.NET Core will load the configuration from multiple sources, where later sources have the chance to overwrite earlier ones. The default sources in non-development environments are the following:

*

*General JSON configuration from appsettings.json

*Environment-specific JSON configuration from appsettings.<Environment>.json

*Environment variables, e.g. ConnectionStrings:DefaultConnection or ConnectionStrings__DefaultConnection (both map to the same configuration path)

*Command-line arguments

So you have the ability to overwrite the configuration from the JSON files by default using both environment variables and command line arguments.
When it comes to production use, there are also other means to protect the secrets. For example, you could simply edit the appsettings.Production.json during deployment, so that the values will never leave the machine itself.

A: There are several solutions for this. But obviously you want to keep things such as connection strings away from version controlled files.
If running locally i would sugest using the user secrets functionality in visual studio.
However you can also set environment variables from the cli. This is an example from the documentation about configuration:
set MyKey="My key from Environment"
set Position__Title=Environment_Editor
set Position__Name=Environment_Rick
dotnet run

Of course when running in azure the key vault is a good place to put these kinds of secrets and also has great integration into .Net.


text:
Q: Improve client-server data sync functionality with deltas The app
I have a web app that currently uses AppCache for offline functionality since users of the system need to create documents offline. The document is first created offline and when internet access is available, the user can click "sync" which will send the document to the server and save it as a revision. To be more specific, the app does not save the change delta as a revision (the exact field modified) but rather the whole document in its entirety. So in other words, a "snapshot" document is saved.
The problem
Users can login from different browsers and devices and work on their documents. When they click "sync", if the server's document is newer, the entire client's version will be overridden by the server's. This leads to one main issue that is depicted in the image below.

The scenario above occurs because of the current implementation which does not rely on deltas (small changes) and rather relies on snapshot revisions.
Some questions
1) My research indicates that I should be upgrading the "sync" mechanism to be expressed in deltas (small changes that can be applied independently). Is this a sound approach?
2) Should each delta be applied independently?
2) According to my research, revision deltas have a numeric value and not a timestamp. What should the value for this be exactly? How would I ensure both the server and the client agree on what the revision number should be?
Stack information

*

*Angular on the frontend

*IndexedDB to save documents locally (offline mode)

*Postgres DB with JSONB in the backend

A: What your describing is a version control issue like in this question. The choice is yours with how to resolve. Here are a few examples of other products with this problem:

*

*Google docs: A makes edit offline, B makes edit online, A goes online, Sync, Google Docs combines A and B's edits

*Apple notes: Same as Google Docs

*Git/Subversion: Throw an error, ask user to resolve conflicts

*Wunderlist: Last edit overwrites previous

For your case, this simplest solution is to use Wunderlist's approach, but it seems that may cause a usability issue. What do your users expect to happen?
Answering your questions directly:

*

*A custom sync implementation is necessary if you don't want overwrites.

*This is a usability decision, what does the user expect?

*True, revisions are numeric (e.g r1, r2). To get server agreement, alter the return value of the last sync request. You can return the entire model to the client each time (or just a 200 OK if a normal sync happened). If a model is returned to the client, update the client with the latest model.

In any case, the server should always be the source of truth. This post provides some good advice on server/mobile referential integrity:

To track inserts you need a Created timestamp ... To track updates you need to track a LastUpdate timestamp on your rows ... To track deletes you need a tombstone table.
Note that when you do a sync, you need to check the time offset between the server and the mobile device, and you need to have a method for resolving conflicts. Inserts are no big deal (they shouldn't conflict), but updates could conflict, and a delete could conflict with an update.


text:
Q: CakePHP Pagination sort() on Related Models I have two models: Plans and PlanDetails.
Relationship is: PlanDetails hasMany Plans. Plans belongTo PlanDetails.
In the PlanDetails view.ctp, I am pulling in related Plans.
I am trying to sort the Plans by ANY field (I've tried them all), and I cannot get it working. I assume I am overlooking something very simple.
Here is my base code:
PlanDetail >> view.ctp:
...foreach ($planDetail['Plan'] as $plan_edit) :
$class = null;
if ($i++ % 2 == 0) {
    $class = ' class="altrow"';
}...

<?php echo $this->Paginator->sort('Plan ID', 'Plan.id'); ?>...

...<?php echo $plan_edit['id']; ?>

plan_details_controller.php:
...function view($id = null) {
    if (!$id) {
        $this->Session->setFlash(__('Invalid plan detail', true));
        $this->redirect(array('action' => 'index'));
    }
    $this->PlanDetail->recursive = 2; // To run the editable form deeper.
    $this->set('planDetail', $this->PlanDetail->read(null, $id));
    $this->set('plan', $this->paginate('Plan'));
}...

I should add, no errors are being thrown and the sort() arrows on the ID field are showing as expected, but the sort order DOES not change when clicked either way.

A: Sorry, I'm not able to comment on the question itself, but I've noticed that in your action, you set planDetail to be the PlanDetail record you read (with recursive set to 2), and then you set plan to be the result of the paginate call.
Then, in your view template, you're iterating over $planDetail's contained Plan association, like this:
foreach ($planDetail['Plan'] as $plan_edit):

But in order to get the sorting and pagination done, you need to be displaying the results of the paginate call i.e. iterate over the records contained in $plan.
Do a debug($plan) in your view template to see what results you get there and to see if the records' ordering changes when you sort by different fields.
Also, perhaps you're using syntax I'm not aware of, but if you simply call $this->paginate('Plan') in your controller, I don't know that you're going to get only the related Plan records for your particular PlanDetail record. (There's nothing tying the $id passed into your view action with the Plan records.) You might need to add some conditions to the paginate call, like so:
$this->paginate['Plan'] = array('conditions' => array('Plan.plan_detail_id' => $id));
$this->set('plans', $this->paginate('Plan'));

A: Here is what I did to solve this. Based on some helpful direction from johnp & tokes.
plan_details/view.ctp:
...$i = 0;
foreach ($plan as $plan_edit) : // note $plan here.
}...

In my plan_details_controller.php view action:
$conditions = array("Plan.plan_detail_id" => "$id");
$this->set('plan', $this->paginate('Plan', $conditions)); // note "plan" in the first argument of set (this is required to pass the results back to the view). Also. The $condition is set to return ONLY plans that match the plan_detail_id of id (on the plan_details table).

And in my view, in order to get my results (because I changed the array name), I had to change the way I was getting the values to:
$plan_edit['Plan']['modified'] // note I placed ['Plan'] in front of these calls as the array called for this to get the data...

Well until the next problem! SOLVED.


text:
Q: How to move a tab after the last pinned tab? The extension is designed so that when you click a pinned tab, it moves it to the rightmost position out of all the pinned tabs. It works a few times before I keep getting the issue:

Error during tabs.move: Tabs cannot be edited right now (user may be
  dragging a tab).
  chromeHidden.handleResponse

When I use the debugger though, it works every single time.
Code:
chrome.tabs.onActivated.addListener(function(tab) {
    chrome.windows.getAll({"populate":true}, function(windows) {
        var tabs = [];
        for (var i = 0; i < windows.length; i++) {
            var win = windows[i];
            if (win.id == tab.windowId) {
                tabs = win.tabs;
                for (var k = 0; k < tabs.length; k++) {
                    var tempTab = tabs[k];
                    if (tempTab.id == tab.tabId && tempTab.pinned == true) {
                        for (var j = k; tabs[j+1] && tabs[j+1].pinned; j++) {
                            chrome.tabs.move(tab.tabId, {"index":j+1});
                        }
                        break;
                    }
                }
            }
        }
    });
});

A: Your current code has some flaws:

*

*Inefficiency: You select all windows and tabs, while only the pinned tabs in the current window are needed.

*Incorrect use of the asynchronous chrome.tabs.move method: You're moving the single tab after the last pinned tab by repeatedly moving the tab to the right. As I said, chrome.tabs.move is asynchronous, so when you call chrome.tabs.move again, the previous "move request" might not have finished yet. Hence your error.

To get more efficient, use the chrome.tabs.query method with the relevant filters:
chrome.tabs.onActivated.addListener(function(activeInfo) {
    var tabId = activeInfo.tabId;
    chrome.tabs.query({
        currentWindow: true,
        pinned: true
    }, function(tabs) {
        // Only move the tab if at least one tab is pinned
        if (tabs.length > 0) {
            var lastTab = tabs[ tabs.length - 1 ];
            var tabIndex = lastTab.index + 1;
            for (var i=0; i<tabs.length; ++i) {
                if (tabs[i].id == tabId) {
                    // Current tab is pinned, so decrement the tabIndex by one.
                    --tabIndex;
                    break;
                }
            }
            chrome.tabs.move(tabId, {index: tabIndex});
        }
    }); // End of chrome.tabs.query
});  // End of chrome.tabs.onActivated.addListener

If you want to do something else after moving the tab, pass a callback to chrome.tabs.move:
chrome.tabs.move(tabId, {index: tabIndex}, function() {
    console.log('Moved tab!');
});

Note: The tab won't move if you keep the mouse pressed. Also, always moving the tab when a tab is focused is a bit unfriendly in terms of user experience. You'd better use a browser action button to activate this feature. Yes, it's one additional click to move the tab, but at least the user will have a choice to not move tabs if they want to.
chrome.browserAction.onClicked.addListener(function(tab) {
    var tabId = tab.id;
    chrome.tabs.query({currentWindow: true, pinned: true}, ...);
});


text:
Q: Equivalent to F# _ wildcard in C# type parameter F# allows you to let the compiler work out what type paramters should be.
let foo = [| 1 |]
let bar = Array.head<_> foo

(you'd never actually do this, you'd drop the parameter, but this is just illustrative).
Is there something in C# that's equivalent?
The problem is...I have F# code that takes literally 30 type parameters, calling this code from F# is trivial, the compiler just works it out (and if it couldn't, then specifying 1 parameter and wildcarding the rest would nicely hint to the compiler what to do), calling this code from C# is horrific, as you have to painstakingly work out the parameters (if you leave them out completely, it stubbornly refuses to infer them).
P.S.
even nasty hacks like getting the IDE to explicitly specify these parameter in F# code, that can then be largely pasted into the C# code would help.
(I understand why C#'s inference is weaker, it's life, but my examples are actually pretty mechanical)

A: Actually I've solved it.
If I wrap the ultra generic function with a call from the specific types AND WRITE THAT IN F#, I can then call this function, which isn't type parametric at all, from my C# code, and not spend 15 minutes trying to work out what the types are.
The cost is having an F# wrapper of an external F# library, but the code is trivial.


text:
Q: Email last failed NAnt Target using CruiseControl.NET email publisher? Since I am using CruiseControl to handle failed and successful build messages, I thought it would neat to have it email just the last failed target rather than emailing the entire failed build logs. I believe this might be handled in the NAnt.xsl file but unsure how to accomplish this. Any ideas?

A: Using a for each loop in the xsl to get the last target worked perfectly <xsl:if test="position()=last()">


text:
Q: Is tensorflow embedding_lookup differentiable? Some of the tutorials I came across, described using a randomly initialized embedding matrix and then using the tf.nn.embedding_lookup function to obtain the embeddings for the integer sequences. I am under the impression that since the embedding_matrix is obtained through tf.get_variable, the optimizer would add appropriate ops for updating it.
What I don't understand is how backpropagation happens through the lookup function which seems to be hard rather than being soft. What is the gradient of the this operation wrt. one of it's input ids?

A: Embedding matrix lookup is mathematically equivalent to dot product with the one-hot encoded matrix (see this question), which is a smooth linear operation.
For example, here's a lookup at the index 3:

Here's the formula for the gradient:

... where left-hand side is the derivative of negative log-likelihood (i.e., the objective function), x are the input words, W is the embedding matrix and delta is the error signal.
tf.nn.embedding_lookup is optimized so that no one-hot encoding conversion happens, but the backprop is working according to the same formula.


text:
Q: What is a project SDK in android studio flutter project? When a new flutter project was created in android studio then there is No SDK in Project Settings->Project->Project SDK by default.
What should I use as Project SDK for flutter project and why it isn't defined by default?

A: You can go to open project->setting->Flutter->  and you can see SDK and also change it
enter image description here


text:
Q: SQL Datatype for math operation that having string i want to make price column that have value like this Rp27.375 since i will doing some math operation with this column i cant use varchar dataype and neither with number datatype because the column will have some string. Can someone provide me a way to solve my problem ? thanks

A: This is the problem of database design. You need to store it in different columns as others have mentioned in the comments. But if you still want to save it in a single column you need to use SUBSTR function as SUBSTR(price,3,15) which will trim the currency code for you and then need to convert the result into number using to_nummber function.


text:
Q: Creating a multilingual app in C# My application is made only in English and i want to switch it to multilingual version . But instead of user changing default language in regionaal settings i gave my application a "ToolStripMenuItem" called langauge and added a submenu for Arabic , Korean and English version .
As far i am aware three things are required -:

*

*Writing a code in click event of that Langauage subemenu say "Arabic"

*Creating a corresponding resx file

*Also i had set the Form localizable property to "True"

This is the code i added to my Program in Form1()
//this variable indicates the current language in use
    CultureInfo CurrentLocale;

    public Form1()
    {
        InitializeComponent();
        valueInit();
        //MessageBox.Show(rfidCard.PORT + "");
    }

    //Lets start adding the multilingual code here

    //change the language in real time
    private void ChangeLanguage(string lang)
    {
        CurrentLocale = new CultureInfo(lang);
        foreach (Control c in this.Controls)
        {
            ComponentResourceManager resources = new ComponentResourceManager(typeof(Form1));
            resources.ApplyResources(c, "$this");
            RefreshResources(this, resources);
        }
    }

    //refresh all the controls e sub-controls of the form
    private void RefreshResources(Control ctrl, ComponentResourceManager res)
    {
        ctrl.SuspendLayout();
        res.ApplyResources(ctrl, ctrl.Name, CurrentLocale);
        foreach (Control control in ctrl.Controls)
            RefreshResources(control, res); // recursion
        ctrl.ResumeLayout(false);
    }

    private void englishToolStripMenuItem_Click(object sender, EventArgs e)
    {
        ChangeLanguage("en-US");
    }

    private void arabicToolStripMenuItem_Click(object sender, EventArgs e)
    {
        ChangeLanguage("ar-SA");
    }

    private void koreanToolStripMenuItem_Click(object sender, EventArgs e)
    {
        ChangeLanguage("ko-KR");
    }

    // the code ends here

Second i added a resx file called Form1.ar-SA.resx and inside that just for testing added two things :
$this.Text =    Abc M البرمجيات تطبيق ويب

$this.Name =  Form1

However when i run my application and try clicking on language Arabic it still does not change anything .
can someone please help me to find where i went wrong or what am i missing ?
Also in the default.resx i found another column saying

$this.Type = System.Windows.Forms.Form, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089

Does that make any difference ?
EDIT1 : While browsing i found i also need to have  genaerated a designer.cs file cprresponding to it . The search engines talked about having some "RazorGenerator" installed  . I tried installing it from the package manager but it failed . Any light on this please
EDIT2 : Here is what I did . I created the two additional .resx files one for Korean and another for Arabic and tried changing language of form  and it worked great in the coding view. However something is still missing . Firstly I am still not able to change the language by clicking on the tool strip language option as desired . Secondly I even tried to change the locale of my system to Korean but the application picks up no change . Its always displayed in English

A: You should use system.globalization for this matter, and you don't have to create resource file, just change language in your form and start editing c# do it for you,  but why it don't affect?!
BECAUSE, c# do it after you reset your application, what you should do is save data about your application state, and restart your application after that reload it with desired localization. If you don't wanna do that don't use globalization, set whole ui like by line,
Sry that in my state (I'm in bus) can't give you the exact code, but it's how you should do it, Application.Restart() I think or some thing close by


text:
Q: glassfish start script fails through crontab I have a created a script to check to see if my glassfish server is running (installed on a freebsd system), if it isn't, the script attempts to kill the java process to ensure it's not hung, and then issues the asadmin start-domain command
If this script runs from the command line it is successful 100% of the time. When it is run from the cron tab, every line runs except the asadmin start-domain line - it does not seem to execute or at least does not complete, i.e. the server is not running after this script runs.
For anyone not familiar with glassfish or the asadmin utility used to start the server, it is my understanding that a forked process is used.  could this be causing a problem via cron?
Again, in all my tests today, the script runs to completion when run from the command line. Once it's executed through the cron, it does not complete... what would be different running this from the crontab???
thanks in advance for any help... i'm pulling my hair out trying to make this work!
#!/bin/bash

JAVA_HOME=/usr/local/diablo-jdk1.6.0/; export JAVA_HOME

timevar=`date +%d-%m-%Y_%H.%M.%S`
process_name='java'
get_contents=`cat urls.txt`

for i in $get_contents
do
echo checking $i
statuscode=$(curl --connect-timeout 10  --write-out %{http_code} --silent --output /dev/null $i)
case $statuscode in
    200)
        echo "$timevar $i $statuscode okay" >> /usr/home/user1/logfile.txt
        ;;
    *)
        echo "$timevar $i $statuscode bad" >> /usr/home/user1/logfile.txt
        echo "Status $statuscode found" | mail -s "Check of $i failed" some.address@gmail.com
        process_id=`ps acx | grep -i $process_name | awk {'print $1'}`
        if [ -z "$process_id" ]
        then
            echo "java wasn't found in the process list"
        else
            echo "Killing java, currently process $process_id"
            kill -9 $process_id
        fi
        /usr/home/user1/glassfish3/bin/asadmin start-domain domain1
        ;;
esac
done

Also, just for completeness, here is the entry in the cron tab:
*/2 * * * *  /usr/home/user1/server.check.sh >> /usr/home/user1/cron.log

A: Ok... found the answer to this on another site, but I thought I'd add the answer in here for  future reference.
The problem was the PATH!!  even though java_home was set, java itself wasn't in the path for the cron daemon.
A quick test to see what path is available to your cron, add this line:
*/2 * * * * env > /usr/home/user1/env.output

From what I can gather, the PATH initially available to cron is pretty minimal.  Since java was in /usr/local/bin, i added that to the path right in the crontab and kaboom!  it worked!
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin

*/2 * * * * /usr/home/user1/server.check.sh >> /usr/home/user1/cron.log


text:
Q: Execute default event before custom click function I'm trying to execute the default event of a button before executing my custom function
my code:
$('#Button').click( function (){
    sideMenuCheck();
});

I wan't this to be executed after the default event of the function
Like this:
$('#Button').click( function (){
    **event.default();**
    sideMenuCheck();
});

but I didn't find any solution.

Not important
I'm doing this because I have an off-canvas menu, and menu has to be with the visible height after it opens, (#Button) is the button that opens menu from the side.

A: You can wrap up your code in a setTimeout with a timeout of 0 - this will cause it to move your code to the bottom of the execution queue, and allow everything else to run first:
$('#Button').click( function (){
    window.setTimeout(function() {
        sideMenuCheck();
    }, 0);
});


text:
Q: is it possible to generate boiler plate form data entry views from templates/structs/classes in SwiftUI I need to create many data entry forms for simple structs/classes etc. I'd rather not be involved in the tedium of writing up the views manually.
Ideally I could just provide some "codable" struct/class and the view would could be generated automatically for me
As an example I have some models containing simple fields such as these
struct Person {
  let age: Int
  let firstName: String
  let lastName: String
}

struct Blah {
  let a: Int
  let b: String
  let c: Date
  let d: Float
}

etc. etc.
Any "magic" similar to "Codable" which could generate an appropriate SwiftUI view ?
for instance:
struct Person: SwiftUIView {
  ...
}

A: You can do that with Telosys ( https://www.telosys.org ) a code generator designed to reduce the programming workload by generating the "boiler plate" part of your application. It's a lightweight and pragmatic tool, easy to use.
It is based on "models" to define all your entities (just like the "struct" you mentioned) but writen with a specific (and quite simple) DSL
( see https://www.telosys.org/dsl-syntax.html )
Telosys can be used to generate any kind of programming languages. Currently it seems that there's no existing templates for SwiftUI, but it's quite simple to create your specific templates, they are based on the well known Velocity templating language ( https://velocity.apache.org/ ). Some templates examples are available on GitHub https://github.com/telosys-templates-v3.
For more information see also : https://modeling-languages.com/telosys-tools-the-concept-of-lightweight-model-for-code-generation/


text:
Q: Persistence Design General Questions I tried to learn on my own, but soon started to realize that by the end of endless books, I will know all the @Entity etc. low level stuff without ever understanding top level.

So my understanding is:

*

*We usually declare DAO interface where we define all the methods to perform on Domain Model.

*Secondly we write Domain Model to represent entity in Database.

*We write DAO implementation class which can use Hibernate, JPA , JDBC or whatever miracles we have out there and which implements our DAO interface.

(wiring up altogether with Spring)

My questions referring to points above:

We write single DAO interface per Domain Model? If we have cross-cuting behavior where participation involves more than one Domain Model we declare new pair DAO interface-implementation and call it accordingly? As example: "Customer orders from Stock, Stock checks whether Item is available -> confirms if it is" where would that go?

How Hibernate interacts with MVC? Are there any important aspects to be aware of?
In a book I noticed:
Overriding Equals and Hashcode
"In simple scenario, Hibernate is able to maintain entity equivalence without requiring any special changes to the domain objects themselves. However, if your application requires that you add entites to Java collections, such as java.util.Set, or you plan to work with detached entities, you will probably need to override the default equals() and hashCode() methods for your domain objects"
Maybe I don't understand it really well, what are detached entities? Are those the one we've taken out of Hibernate context - effectively just collections of classes?
What I want is safely to do Hibernate its work, then return me a Model which I would give to Servlet and which will delegate it to appropriate View. We extract that model by means of simple return from DAOimpl class methods or is it somewhat tricky?

If I am to do persistence tier without ORM framework, just with plain JDBC, what are my problems? I've heard that Hibernate has some smart session which  handles concurrent requests, so what will happen with JDBC?

Where does business logic resides in? Is it DAOimpl classes?

I am sorry if some of my questions are mishaps, I appreciate any critic and correction.
Thank You.

A:
We write single DAO interface per Domain Model? If we have
  cross-cuting behavior where participation involves more than one
  Domain Model we declare new pair DAO interface-implementation and call
  it accordingly? As example: "Customer orders from Stock, Stock checks
  whether Item is available -> confirms if it is" where would that go?

You could do that.  A possilby simpler way would be to have a Service manage the DAO invocations.  If you use Spring, you can define your transaction boundaries on the service methods, so all DAO methods will participate in the same transaction.  So your DAOs stay specific to their respective models, and in theory are simpler.  Keep in mind that when any DAO flushes the session, all changes get pushed to the database.  So if you have a User and a Profile model, and they are mapped appropriately in hibernate, if you create an instance of each and call flush the session they will both get saved.
This approach is appealing because DAOs should do one thing -- perform persistence operations.  If you start making complicated DAOs, you might be encapsulating the business requirements of your app in the persistence layer, which you don't want to do. Services are the place to order persistence operations to implement business requirements.

How Hibernate interacts with MVC? Are there any important aspects to
  be aware of?

MVC is a paradigm.  Model View Controller.  The intent is to define clear concerns in your application so individual components can stay focused on one thing.  A Model object should not be telling a view how to render itself, for example.  Hibernate is an ORM persistence implementation.  Hibernate code is one way to save your model objects.  MVC and hibernate have very little to do with each other, you can have MVC in an app and no Hibernate, or Hibernate in an app and no MVC.

Maybe I don't understand it really well, what are detached entities?
  Are those the one we've taken out of Hibernate context - effectively
  just collections of classes?

From the documentation "Detached - a detached instance is an object that has been persistent, but its Session has been closed."
Detached instances can still be saved later, but they need to be reassociated with the session.

If I am to do persistence tier without ORM framework, just with plain
  JDBC, what are my problems? I've heard that Hibernate has some smart
  session which handles concurrent requests, so what will happen with
  JDBC?

The main drawback is that you need to convert your jdbc results into objects, if your app uses objects to represent entities.  You also need to write the sql.  Using jdbc is not a bad idea.  ORM is an options.  JDBC is another option.  You can also mix and match, but that can be complicated.  Concurrent requests into your application should not be a concern of your persistence layer.  Just make sure that your DAOs don't save any state (i.e. use static variables) and you should be fine.

Where does business logic resides in? Is it DAOimpl classes?

It's a combination of your domain model and your services.  As already mentioned, if you need to save things in order, that can go in a service.  If you have a requirement that some field should be restricted to some values, that could be in the model itself.  It's NOT in DAOs -- those should just handle persistence.

A: I have removed the dao layer from my spring/hibernate web app - seemed unnecessary to me.   In fact I can't imagine what they would consist of now.  But this seems somewhat debatable.
For overriding equals and hashcode with hibernate I generally use the db generated auto id, again this is somewhat debatable.  As long as you are aware that the id is only present after first persisting to db, there is not a problem.

Where does business logic resides in?

On your domain objects/hibernate entities - this is less controversial.


text:
Q: Access errors when using threads #include <iostream>
#include <thread>

void hi()
{
    std::cout<<"hi"<<std::endl;
}

int main()
{
    std::thread t1(hi);
    t1.join();
}

I turned on C++ to study threads, but as soon as I started it, the following error occurred. The error only occurs when building with 64-bit debug. And the error is thrown when the main method exits. What's the problem?
enter image description here
enter image description here
video link: https://www.youtube.com/watch?v=cM6OJ5NgBMQ
Translated into English, the exception that occurred is as follows.
Exception thrown (0x00007FF670271350, test.exe): 0xC0000005: 0x0000000000006800 Access violation while writing location.

A: Please change your project name. DO NOT use "test".(I meant delete this project and create a new one with different project name.) Because test.exe is already existed in windows. Visual Studio may not run your command.


text:
Q: how to add a white color as a filter on a SKSpriteNode in Swift I have added a SKSpriteNode in the scene, and I want to add a white color on it to brighten.
let armySprite = SKSpriteNode(imageNamed: "army_img")
armySprite.position = tile.Position
scene.addChild(armySprite)
armySprite.colorBlendFactor = 1
armySprite.color = .white

However, there is nothing happened.
So, how can I add a white color filter on armySprite to make it more bright?
The original img is like this:

Then, what I want is like this :

Thanks.


text:
Q: Windows Forms application memory leak .NET There is a winforms application, where couple of forms are very complicated - using datasets, multiple bindings with grids and comboboxes..
Every time when I open the form, the memory usage grows for about 2-5 MB until I get OutOfMemoryException.
I use using statements for every IDisposable (for Forms too), tried to clear all the bindings and unsubscribe my events within Dispose(), nothing changed.
If I call GC.Collect() after disposing the form, used memory amount returns in previous state, as it was before opening the form.
I have tried some memory profilers, but they did not show anything extraordinary.

A: Because the memory grows so rapidly, the problem must be in the Paint method of one of the controls (if you paint/draw the control yourself) or in the auto-update loop of your grids (if you update the data source periodically).

*

*Check if you dispose all Brushes, Pens, Font, StringFormats in your paint loop.

*Check the update-loop of your data sources. Common errors are SqlCommand and SqlConnections which are not disposed properly.

Hope this helps. Without more detailed information about your source-code it's hard to provide any other help.

A: It is possible that your DataSet is not released correctly although you dispose it.
From MSDN

Note: Classes inherited from DataSet are not finalized by the garbage
  collector, because the finalizer has been suppressed in DataSet. The
  derived class can call the ReRegisterForFinalize method in its
  constructor to allow the class to be finalized by the garbage
  collector.

And you should read this question that can be very usefull Should I Dispose() DataSet and DataTable?

A: My employer, Red Gate Software, makes a .NET memory profiling tool you could use to investigate your problem. It has a 14-day trial which might be long enough to find your leak for free :)
http://www.red-gate.com/products/dotnet-development/ants-memory-profiler/
There is also 'dotTrace Memory' by jetBRAINS, although I've not tried it.


text:
Q: Connecting to existing Heroku Postgres DB for Sinatra app I am using Salesforce for my CRM, but need to query data (multiple records, so no Zapier) for a Heroku based Sinatra app. Heroku provides a service that replicates Salesforce objects to Postgres tables regularly which gets my data out of Salesforce.
I've coded a Sinatra app before and hosted it on Heroku so I'm a bit familiar with the process of setting up a dev db locally then pushing it to production via the many tutorials. However, i'm running into an issue finding any information that will allow me to connect to the existing production Postgres DB that already is populated with the data I need while having no need to create and connect to a local dev db.
Heroku provides me with the following

How and where to I plug in these various credentials securely so my following files have the right information to connect to tables Venue__c and Spaces__c?
app.rb
/config
- database.yml
- environments.rb

A: Assuming that you have ActiveRecord, it should just be a case of configuring your database.yml correctly. For example, to directly connect your development environment, use something like:
# database.yml
development:
  adapter: postgresql
  encoding: unicode
  database: your_database
  username: your_user
  password: your_password
  host: your_host
  port: your_port

# or alternatively, using the URI
development:
  url: postgres://your_user:your_password@your_host/your_database

A: Heroku publishes your database credentials to you through a URL in an environment variable. You should be able to access it through ENV.fetch("DATABASE_URL"). Depending on your ORM you will use different ways to connect to your database, e.g. Sequel is able to use this value directly as a parameter to Sequel.connect(ENV.fetch("DATABASE_URL")).
As you seem to use ActiveRecord you could be using ActiveRecord::Base.establish_connection(...) as suggested in this post which also exemplifies how to parse the URL (which might not be necessary anymore). This does not translate directly to a database.yml, but since you do not plan to use Rails you will have to provide your own version of environment.rb or some such and it should be easy enough to do in that place.

A: Turns out Heroku has a great tutorial that not only connects to the replicated database, but is also written for Sinatra.
https://devcenter.heroku.com/articles/getting-started-with-heroku-and-connect-without-local-dev#introduction


text:
Q: How to create a frequency table with Coordinates Looking to create a frequency table to create an interactive map. I have the coordinates of the Starbucks in California and need to separate it by region, and I'm unsure how to do this
starbucks <- data.frame(longitude = c(-122.2761, -118.374, -118.2426),
latitude = c(37.77966, 33.97764, 34.05123))

How would I create a freq. table for this data separated by regions, so I can input into a leaflet interactive map?

A: Here's an example.  It proves all 3 are in CA.
library(sf)
library(tigris)
library(dplyr)
starbucks <- data.frame(longitude = c(-122.2761, -118.374, -118.2426),
                        latitude = c(37.77966, 33.97764, 34.05123))
states <- tigris::states()
aggregate(states,
          sf::st_as_sf(starbucks, coords = c('longitude', 'latitude'), crs = st_crs(states)),
          I) %>%
  as_tibble() %>%
  select(NAME) %>%
  table()

.
California
         3


text:
Q: "Viewport" by META tag in HTML ... if iPad = X and if iPhone = Y?
Working good with iPad but not iPhone
Any code can I direction to iPad and iPhone
for iPad
<meta name="viewport" content="width=1040px, minimum-scale=0.5, maximum-scale=1.0" />

for iPhone
<meta name="viewport" content="width=440px, minimum-scale=0.5, maximum-scale=1.0" />

A: iPhone max-width is 480px not 440px
<meta name = "viewport" content = "user-scalable=no, width=device-width"/>

<meta name="apple-mobile-web-app-capable" content="yes"/>

This sets the viewpoint with the scaleable option off
<link media="only screen and (device-width: 768px)" rel="stylesheet" href="css/ipad.css" type="text/css" title="no title"/>

This is a css file for only iPad
<link media="only screen and (max-device-width: 480px)" rel="stylesheet" href="css/small-device.css" type="text/css" title="no title"/>

This is a css file for only iPhone
They are conditional comments so they will only apply to specific devices with specified max-widths.


text:
Q: Why my colors doesn't show in all terminals? I have the following piece of code.
bold=''
reset=$(echo -en '\033[0m')
black=$(echo -en '\e[1;30m')
magenta=$(echo -en '\033[00;35m')
blue=$(echo -en '\e[1;34m')
cyan=$(echo -en '\e[1;36m')
green=$(echo -en '\e[1;32m')
orange=$(echo -en '\e[1;33m')
purple=$(echo -en '\e[1;35m')
red=$(echo -en '\e[1;31m')
white=$(echo -en '\e[1;37m')
yellow=$(echo -en '\e[1;33m')
lime_yellow=$(echo -en '\e[1;33m')
power_blue=$(echo -en '\e[1;34m')
blink=$(echo -en '\e[1;31m')
reverse=$(echo -en '\e[1;31m')
underline=$(echo -en '\e[1;31m')

if [ -x /usr/bin/tput ] && tput setaf 1 &>/dev/null; then
    echo "tput color is supported."
    tput sgr0 # Reset colors
    bold=$(tput bold)
    reset=$(tput sgr0)
    black=$(tput setaf 0)
    magenta=$(tput setaf 5)
    blue=$(tput setaf 33)
    cyan=$(tput setaf 37)
    green=$(tput setaf 64)
    orange=$(tput setaf 166)
    purple=$(tput setaf 125)
    red=$(tput setaf 124)
    white=$(tput setaf 15)
    yellow=$(tput setaf 136)
    lime_yellow=$(tput setaf 190)
    power_blue=$(tput setaf 153)
    blink=$(tput blink)
    reverse=$(tput smso)
    underline=$(tput smul)
else
    echo "tput color is not supported. Use old school colors."
fi

echo ${red}RED${green}GREEN${yellow}YELLOW${blue}BLUE${purple}PURPLE${cyan}CYAN${white}WHITE${reset}

Basically there are two types of colors, tput generated or the old-fashioned escape characters like \e[1;32m. Since the tput type is more interesting, for example, it supports blinking and underline, the code uses tput type color if possible. Here is an image to prove it works as expected in Oracle Linux 7.6 (kinda like RedHat or CentOS) GUI environment.

When I run it from other terminals, it doesn't work. For example, below is the snapshot when running in MobaXterm.

I also tried putty and it doesn't work either. Is there anything wrong with my code?

Update
I executed echo $TERM in each of the terminals and below is the result.

Oracle Linux with Desktop environment (color works)
Output: xterm-256color

MobaXterm on Windows (color doesn't work)
Output: xterm

putty on Windows (color doesn't work)
Output: xterm

A: You must configure your terminal type as putty, putty-256color, or putty-sco when using PuTTY, or things based upon it such as MobaXTerm.  They are the only terminal types whose entries in the terminfo database correctly describe PuTTY.
It is a widespread incorrect assumption that terminal emulators are all compatible with XTerm, and that the xterm and xterm-256color entries in the terminfo database correctly describe them.
This erroneous thinking is called out in Thomas Dickey's XTerm FAQ and it is worth observing that the xterm and xterm-256color entries do not even describe all versions of XTerm, let alone other terminal emulators.
The putty entry in the terminfo database describes a terminal that is only capable of 8 ECMA-48 colours.  As, indeed, does the xterm entry.  But merely switching from xterm to xterm-256colour is wrong.  PuTTY differs from XTerm.
In fact, PuTTY is quite capable of indexed colour (256 colours from a palette) using ISO/IEC 8613 control sequences.  Indeed, since 2017 it is quite capable of direct colour (24-bit RGB colour) using ISO/IEC 8613 control sequences.  The putty-256colour entry describes the former.  terminfo does not have a way to fully describe the latter.
Use the correct terminal type, and tput will look up the correct control sequences.
Further reading

*

*https://unix.stackexchange.com/a/419092/5132

A: These codes should work :
    magenta=$(tput setaf 5)
    blue=$(tput setaf 4)
    cyan=$(tput setaf 6)
    green="$(tput setaf 2)"
    purple=$(tput setaf 5)
    red=$(tput setaf 1)
    white=$(tput setaf 7)
    yellow=$(tput setaf 3)

A: It's the terminal's capability that doesn't support the colors besides the 8 basic ones. I found this piece of code to test all available color (source: tput setaf color table? How to determine color codes?):
# Connector fifos directory
read TMPDIR < <(mktemp -d /dev/shm/bc_shell_XXXXXXX)

fd=3
# find next free fd
nextFd() { while [ -e /dev/fd/$fd ];do ((fd++)) ;done;printf -v $1 %d $fd;}

tputConnector() {
    mkfifo $TMPDIR/tput
    nextFd TPUTIN
    eval "exec $TPUTIN> >(LANG=C exec stdbuf -o0 tput -S - >$TMPDIR/tput 2>&1)"
    nextFd TPUTOUT
    eval "exec $TPUTOUT<$TMPDIR/tput"
}
myTput() { echo -e "$1\ncr" 1>&$TPUTIN && IFS= read -r -d $'\r' -u $TPUTOUT $2
}
tputConnector

myTput op op
myTput "setaf 7" grey
myTput "setaf 16" black
fore=("$black" "$grey")
for ((i=0; i<256; i++)) ;do
    myTput "setab $i" bgr
    printf "  %s%s  %3d  %s" "$bgr" "${fore[ i>231 && i<244||(i<17)&& (i%8<2)||
        (i>16&&i<232)&&((i-16)%6*11+(i-16)/6%6*14+(i-16)/36*10)<58
        ? 1 : 0 ]}" $i "$op"
    (( ((i<16||i>231) && ((i+1)%8==0)) || ((i>16&&i<232)&& ((i-15)%6==0)) )) &&
        printf "\n" ''
done

Below is the output from all three terminal I've tested.

*

*Oracle Linux with Desktop environment

*MobaXterm on Windows

*putty on Windows

So it's the terminal doesn't support the colors besides the 8 basic ones. To be safe and portable, use just these 8 colors.


text:
Q: "No module named" error when attempting to importing c# dll using Python.NET I'm attempting to import a c# module into Python using python.NET under Anaconda
This has been installed using pip install pythonnet which reported "Successfully installed pythonnet-2.5.2"
From there with python it should be possible to do something like the following which isn't working properly.
Jetbrains dotPeek can see the module, and calls to standards Windows dlls work fine.
What am I doing wrong?
clr.AddReference(R'C:\Program Files (x86)\UVtools\UVtools.Core.dll')
from UVtools.Core import About
>>ModuleNotFoundError: No module named 'UVtools'
# never gets here:
print(About.Software)

This works fine:
import clr
clr.AddReference("System.Windows.Forms")
from System.Windows.Forms import Form
form = Form()
print(dir(form))
>> ['AcceptButton', ...

This also doesn't work (trying to access the same dll in a different way)
import System
uvTools = System.Reflection.Assembly.LoadFile(R'C:\Program Files (x86)\UVtools\UVtools.Core.dll')
print(uvTools.FullName)
print(uvTools.Location)
>>UVtools.Core, Version=2.8.4.0, Culture=neutral, PublicKeyToken=null
>>C:\Program Files (x86)\UVtools\UVtools.Core.dll
# But the following all fail with the same fundamental error:
print(uvTools.UVtools.Core.About)
print(uvTools.Core.About)
print(uvTools.About)
>>AttributeError: 'RuntimeAssembly' object has no attribute 'About'

JetBrains dotPeek can see the modules, which to me would have implied it's not an issue with the dll.

I did see elsewhere that if trying to use ctype then you need to include "[DllExport("add", CallingConvention = CallingConvention.Cdecl)]" in the c# basecode, but I don't think this applies to python.NET clr calls

A: I believe your issue is that you are using the file extension in the import statement.
This is what works for me:
#add the directory the assembly is located in to sys.path.
assembly_path1 = r"C:\DesktopGym\src\MouseSimulatorGui\bin\Debug"
import sys
sys.path.append(assembly_path1)

import clr
#add a reference to the assembly, by name without the .dll extension.
clr.AddReference("GymSharp")

#import the class. Here this is a public class, not static.
from GymSharp import TicTacToeSharpEnvironment

# instantiate a new instance
env = TicTacToeSharpEnvironment()

# call a method
result = env.HelloWorld()

print (result)

In C#, GymSharp is the name space and TicTacToeSharpEnvironment is the name of the public class:
namespace GymSharp
{
    public class TicTacToeSharpEnvironment
    {
        public string HelloWorld()
        {
            return "Hello World";
        }
    }
}

I also tested my a Static class with a static method, so that is not the issue.
namespace GymSharp
{

    public static class StaticFoo
    {
        public static string StaticHelloWorld => "Static hello World";
    }

From Python
from GymSharp import StaticFoo
print (StaticFoo.StaticHelloWorld)

A: The full-stop between UVtools and Core prevents you from accessing the object of core which contains the About Method. You must find a way to have just one name with a dot or full-stop inbetween the class and method in the class. Also note that if you import a dll file through the assembly path. the entire library in that assembly path is accessible.
The example on GymSharp below is a good example of how to implement  and use the pythonnet library and implementing an assembly import is given below:
#add the directory the assembly is located in to sys.path.
assembly_path1 = r"C:\DesktopGym\src\MouseSimulatorGui\bin\Debug"
import sys
sys.path.append(assembly_path1)

ModuleNotFoundError: No module named 'UVtools'

A: I also had the ModuleNotFoundError. After switching to .NET Framework 4.8 everything worked. My initial project was with .NET Core 3.1 which worked for this question, but not for me. I also tried .NET 5.0, but that gave the same error.
I used:

*

*pythonnet 2.5.2

*Python 3.8.13

*Class Library with .NET Framework 4.8


text:
Q: Mpeg-dash playback I've been trying to figure out how to playback an mpeg-dash xml file directly in chrome (Version 30.0.1599.69 m) with the html5 video element. Something like
the mpd file has been created with mp4box and the video codec is MP4.
But this is obviously not the correct method. I'm aware of the "dash.js" project - but why cant the browser handle all the details, when they've added support for mpeg-dash playback?
Is there any way to play an mpeg-dash without any use of javascript?
Is there an open source flash player for mpeg-dash? (with support for live streams, file streams, multiple audio tracks and sub titling)
We are planning a project for OTT streaming of live tv and VOD and would prefere to use MPEG-dash, but it looks like its not a complete design yet, and we are also thinking of using HLS with some kind of flash player for browsers without HLS support. Is HLS an better choise, even its not an ISO standard?

A: What you describe, just using plain html5 to play a video, only supports progressive download (not streaming).  With streaming/adaptive streaming  you will need some kind of player like the one suggested above.  Note that there is also a free mpeg-dash player, dash.js, which I had working in an hour.  But with mpeg-dash, only the latest browsers and devices support it.  It's gaining in popularity but as you say, support is still limited.  You are on the right track with HLS.  I had to implement a solution recently that targeted the largest audience (old and new browsers and devices) and I ended up with JWPlayer and HLS V3. HLS is only second to flash as far as the widest support and it has the advantage of working well with the latest tech as well.  MPEG-DASH is the future.  Flash is the past.  HLS V3 is the now.
One note, Android before 4.x didn't support HLS but Android devices tend to get push updates so my above answer assumes most Android users are running newer versions.

A: In case you are planning an App, you may use the open source library libdash:  http://www.bitmovin.net/libdash
As far as I know, they also have Flash and Java-based Versions of http://www.bitmovin.net/bitdash.html

A: Wowza now supports MPEG-DASH nDVR for live streaming and has a player. Users can play or pause the live stream, rewind it to a previously recorded point, or resume viewing at the current live point.
Docs to do this can be found here:
https://www.wowza.com/docs/wowza-ndvr-quick-start-guide
[I work for Wowza.]


text:
Q: Access CF service without running app Our CF hosted application (java) has crashed because of a database issue. The database service (mariaDB) is still running but I cannot connect to it using my service key and ssh because the app is down. Is there any way to access a service on cloud foundry directly without having a running app?
I cannot get the app running again, because I cannot access the DB, and I cannot access the DB because the app is down. You see the problem. We are using Swisscom's CF.

A: My findings coincide with @SandroMathys. We created an "empty" proxy-app borrowing from this guide: https://github.com/swisscom/docs-appcloud-service-offerings/blob/master/migrate-mariadb-to-mariadbent.html.md.erb
The gist of it is:
$ git clone https://github.com/swisscom/cf-default-app-staticfile.git
$ cd cf-default-app-staticfile
$ cf push proxy-app --no-route

Afterwards:

*

*bind "proxy-app" to your service (e.g. database)

*create a service key

*use cf ssh as usual to open up a tunnel and access the service

A: Unfortunately, there's no other way. However, you can bind several apps to the same service instance, so you could temporarily push a small dummy app.


text:
Q: How to fix if App rejected for using UIWebView in code? I have been trying to upload an iOS app to Appstore but its only appearing on "Activity" tab for 3-5 minutes and then disappears.
Then I got an email from Apple saying that my app is rejected because it is using UIWebView in one of the view controller. I deleted that particular screen and reuploaded the app and had the same error email.
Then I checked my third-party sdks like FacebookLoginSDK and GoogleSignInSDK and updated those and then checked that if the app has no UIWebView which it did not. Then i reuploaded the app but this time again I had the same error email. I have searched the whole storyboard source code and the whole app code to look that if there is any sign for UIWebView but there is nothing, but still I am getting this email.
I also tried deleting 'Derived Data' folder several times and cleaning the build folder also but nothing helps.
On the other hand I have uploaded a different app today which had UIWebView and it got approved but I also got the same email for not using UIWebView.
Does anybody had this kind of experience or can anybody tell me whats going on ?

A: I got the same issue before.
If you have uploaded the build and showing it in activity tab for few minutes then its not mean that issue is only about UIWebview but there can be some other issue as well.
I have uploaded my app n got the mail related to UIWebview, so I coverted the UIWebview to WKWebView and again I uploaded but that time same thing happend.
I failed to tackle the problem.
Then I mailed to Apple Developer Support and they replied like
Any of the third party library internally using some privacy data you should ask permission for the same.
Then I checked Info.plist, I have given each permission in list still how it comes that we don't understand.
Finally then after whole search the one third party library internally using motion related data without permission so this happened.
Then I have added that in plist and then again uploaded and its approved.
So please you can check your info.plist and also check whether your third party library using any privacy sensitive data without permission or not.
May it help you at some point.

A: Make sure you update all your plugins to the latest version!
Check this: https://ionicframework.com/blog/understanding-itms-90809-uiwebview-api-deprecation where you can find the plugins that have known issues concerning the old WebView usage.
But be aware that uninstalling and re-installing some plugins will NOT will not install the latest available version of the plugin!
So to be sure that you are re-installing the latest version of a plugin, go to the github repository of the cordova plugin and search for the plugin.xml file and open it. Then, copy the version string found in the root xml element.
Finally, install the plugin like that: ionic cordova plugin add plugin_name@copied_version
<?xml version='1.0' encoding='utf-8'?>
<plugin id="cordova-plugin-firebase" version="2.0.5"
xmlns="http://apache.org/cordova/ns/plugins/1.0"
xmlns:android="http://schemas.android.com/apk/res/android">
    <name>Google Firebase Plugin</name>
...
...
...
</plugin>

A: Are you using the AdMob plugin?
It is not enough to check for the absence of "UIWebView" strings!
You have to make sure that all third party plugins are up to date.
One of the trickiest situations I had went to is when I had tried to update an app (using AdMob) on the AppStore after Apple started rejecting apps using the UIWebView.
The generated iOS source code has no UIWebView references, but still rejected!
After a long headache, I realized that the Google AdMob SDK version I'm using is out of date, knowing that I had updated the AdMob plugin from the CLI, but it seems that the SDK is not updated when updating from the npm.
Finally, I had downloaded the latest AdMob SDK from this link https://developers.google.com/admob/ios/download and replaced it in the source code of the AdMob SDK plugin. Then I had followed the instructions found in this link https://developers.google.com/admob/ios/quick-start to update the code in the xCode.


text:
Q: Detect correct resolution dual monitor VGA 9800gt Ubuntu 12.10 I connected a second monitor to my 9800gt on the VGA port. The first monitor is on DVI. Both monitors have a native resolution of 1920x1080 but the second monitor doesn't get past 1360x768 and appears as "Unknown" in the display settings.
I tried this guide on how to add undetected resolutions but it didn't work.
First I create the new mode with xrand --newmode "1920x1080_60.00"  173.00  1920 2048 2248 2576  1080 1083 1088 1120 -hsync +vsync and then when I try to add the new mode to my second monitor like randr --addmode VGA-0 1920x1080 I get this error:
X Error of failed request:  BadMatch (invalid parameter attributes)
  Major opcode of failed request:  140 (RANDR)
  Minor opcode of failed request:  18 (RRAddOutputMode)
  Serial number of failed request:  31
  Current serial number in output stream:  32

I tried using the nvidia-settings panel to generate a xorg.conf:
Section "ServerLayout"
    Identifier     "Layout0"
    Screen      0  "Screen0" 0 0
    InputDevice    "Keyboard0" "CoreKeyboard"
    InputDevice    "Mouse0" "CorePointer"
    Option         "Xinerama" "0"
EndSection

Section "Files"
EndSection

Section "InputDevice"
    # generated from default
    Identifier     "Mouse0"
    Driver         "mouse"
    Option         "Protocol" "auto"
    Option         "Device" "/dev/psaux"
    Option         "Emulate3Buttons" "no"
    Option         "ZAxisMapping" "4 5"
EndSection

Section "InputDevice"
    # generated from default
    Identifier     "Keyboard0"
    Driver         "kbd"
EndSection

Section "Monitor"
    # HorizSync source: builtin, VertRefresh source: builtin
    Identifier     "Monitor0"
    VendorName     "Unknown"
    ModelName      "CRT-1"
    HorizSync       28.0 - 55.0
    VertRefresh     43.0 - 72.0
    Option         "DPMS"
EndSection

Section "Device"
    Identifier     "Device0"
    Driver         "nvidia"
    VendorName     "NVIDIA Corporation"
    BoardName      "GeForce 9800 GT"
EndSection

Section "Screen"
    Identifier     "Screen0"
    Device         "Device0"
    Monitor        "Monitor0"
    DefaultDepth    24
    Option         "Stereo" "0"
    Option         "nvidiaXineramaInfoOrder" "DFP-0"
    Option         "metamodes" "CRT: 1360x768 +0+0, DFP: nvidia-auto-select +1360+0; CRT: nvidia-auto-select @1920x1080 +0+0, DFP: nvidia-auto-select +1360+0"
                                    ____^____ I tried changing this to 1920x1080 but no luck
    SubSection     "Display"
        Depth       24
    EndSubSection
EndSection

Here's my xrandr output in case it helps:
Screen 0: minimum 8 x 8, current 3280 x 1080, maximum 8192 x 8192
DVI-I-0 disconnected (normal left inverted right x axis y axis)
VGA-0 connected 1360x768+0+0 (normal left inverted right x axis y axis) 0mm x 0mm
   1024x768       60.0 +
   1360x768       60.0*    59.8
   1152x864       60.0
   800x600        72.2     60.3     56.2
   680x384       119.9    119.6
   640x480        59.9
   512x384       120.0
   400x300       144.4
   320x240       120.1
DVI-I-1 connected 1920x1080+1360+0 (normal left inverted right x axis y axis) 510mm x 290mm
   1920x1080      60.0*+   50.0
   1680x1050      60.0
   1600x1200      60.0
   1440x900       59.9
   1280x1024      60.0
   1280x960       60.0
   1280x800       59.8
   1280x720       60.0     50.0
   1024x768       60.0
   800x600        60.3     56.2
   720x576        50.0
   720x480        59.9
   640x480        59.9
HDMI-0 disconnected (normal left inverted right x axis y axis)

Any ideas on what to do next? I've been trying for hours with no luck, it works fine in Windows so it can't be the cable or monitor...

A: I think what you need to do is disable EDID probing. Methods vary depending on graphics chipset/driver. For example, with nvidia's binary blob driver, you use "Option "IgnoreEDID" "false"". This goes in your monitor configuration section. YMMV.


text:
Q: How to read PDFs in Android without using third-party apps, or a webview? I want to write an Android application to read and display PDFs. I don't want to use any third-party applications to do this, because I don't want to force my users to download those applications.  And I don't want to use a webview, because then users won't be able to use my app when they're offline.
How might I approach this?

A: Here's a link I used to create one that mostly works.
It outlines how to write (and hence read) all the common PDF parts that are in a .pdf file. It's far more readable than the ISO spec, especially if you haven't done PDF formats before.
http://www.adobe.com/technology/pdfs/presentations/KingPDFTutorial.pdf
Good Luck.

A: Unless you fancy building a PDF rendering engine from scratch (or including one in your project), you probably are better with using some kind of intent to ask some other application on the phone to view the PDF. I know you do not really want the requirement of having an application installed to handle it, but I suggest that you are probably adding unnecessary complexity to your application by trying to do it some other way.
It's worth mentioning that quite a lot of Android handsets already have PDF viewers preinstalled, and incidentally, I think even WebView requires that the phone has a PDF viewer installed!


text:
Q: Solving a tricky PDE We are required to solve the PDE $$p^2 + q^2 = z^2(x+y)$$
Where $p \equiv z_{x}, q \equiv z_{y}$.
I tried using the charpit equations, although couldn't think of anything that would produce a solution..
Next, I tried using the transformations $X=x+y, Y=x-y, P=z_{X}= p+q, Q=z_{Y}=p-q$, which gave the equation:
$$(P^2+Q^2)= z^2X/2$$
The charpit equations read:
$$ \dfrac{dX}{2P}=\dfrac{dY}{2Q}=\dfrac{dZ}{2(P^2+Q^2)}(\equiv \dfrac{dz}{z^2X})=\dfrac{dP}{z^2/2+zPX}=\dfrac{dQ}{zQX}$$
Using the 3rd and the 5th terms, we can see that $$dQ/Q=dz/z$$
S0, $Q=az$.
But apart from this, I dont see any other terms giving something useful.. So how exactly do we approach this question?

A: $$(z_x)^2+(z_y)^2=(x+y)z^2$$
Without boundary condition the solution is undefinite (they are an infinity of solutions).
For example one can look for solutions on the form $z(X)$ with $X=x+y$ :
$z_x=z_y=z'(X)\quad\implies\quad 2(z')^2=X\:z^2\quad\implies\quad\frac{z'}{z}=\pm\sqrt{\frac12 X}\quad\implies\quad z=c\:e^{\frac{\sqrt{2}}{3} X^{3/2}} $
$$\boxed{z(x,y)=c\:e^{\frac{\sqrt{2}}{3} (x+y)^{3/2}}} $$
$c$ is an arbitrary constant.
The Charpit equations leads to the same result.


text:
Q: .load() does not work in browsers I use Coda 2 which has a built-in browser. Here's a code:
$('#mtbLink').click(function() {
    $("#loadHere").load("file:///Volumes/Macintosh%20HD/Applications/XAMPP/xamppfiles/htdocs/another/test.html #loadThis")
});

It works in Coda browser, but doesn't work in Safari, Mozilla and Yandex.Browser (chromium-based browser). How can I fix it?

A: You cannot make AJAX requests to the local file system. To test this in FF/Chrome etc. you need to place your test.html file on an accessible webserver.


text:
Q: ControllerAdvice not catching exceptions as expected Given an exception thrown while processing a request handled by the Spring DispatcherServlet
Shouldn't this global handler be able to "catch" it ?
@ControllerAdvice
public class ExceptionControllerAdvice {

    @ExceptionHandler(Exception.class)
    public ResponseEntity<ErrorResponse> exceptionHandler(Exception ex) {
        ErrorResponse error = new ErrorResponse();
        error.setErrorCode(HttpStatus.INTERNAL_SERVER_ERROR.value());
        error.setMessage("Please contact your administrator");
        return new ResponseEntity<ErrorResponse>(error, HttpStatus.OK);
    }
}

Some tests I've carried out show that an handler like this is not able to catch exceptions thrown by formatters or even by the DispatcherServlet itself for example in the case it cannot find a suitable target handler.
Is this the expected behaviour ?
Am I missing something here ?


text:
Q: Looking for a suffix to denote paraphernalia associated with a person Can someone help me identify the below-described suffix.  I feel I've seen it before, but I can't bring it to mind or locate it through my usual methods (i.e., search queries).
The suffix is added to the end of a person's name and denotes paraphernalia, collectibles, memorabilia or other items associated with that person.  For example, if someone is obsessed with Richard Nixon, and owns a bunch of Nixon's old letters, belongings, who knows, clothes, tape recordings, etc., you might refer to this collection as Nixon + a suffix.  Like -ica, or -ia.  Nixonica.  But that's not right, I don't think.
In any event, the effect might be facetious (or not).  The suffix might also apply to items associated with a non-person, but I can't remember.  It may also only work with certain names - for example, those that end in a consonant.

A: A possible alternative to "ana" is "-alia", although it doesn't seem to be widely listed in dictionaries:

-alia
Suffix
(forming plural nouns) denoting items associated with a particular area of activity or interest.
Example kitchenalia [Lexico]

and on affixes.org

-alia A collection or group ... sometimes with implications of triviality...  [Affixes]

However, neither "kitchenalia" nor "-alia" as a suffix is listed in my 1975 copy of the Concise Oxford Dictionary (Edition 6).
To my ear I would use "Nixonalia" as a portmanteau for items collected because of an association with Nixon (but not "Nixonana"), but would collectively describe items typical of the Victorian era as "Victoriana".

A: You have got to be looking for the suffix "-ana".

(SOED) -ana Forming plural nouns with the sense 'publications or other items concerning or associated with a person, place, or topic' as Americana, cricketana, railwayana, Shakespeariana, Victoriana.


text:
Q: Why Apache Ignite sys-thread consumes so much memory? Environmental information:
There are two Linux-machine(8U 16G 64bits) nodes in my cluster. And I enable the Ignite native persistence. The memory for offHeap is 3.2G. Ignite version is 2.6.0.
Usage information:
There are three caches, and only one backup in the cluster. About 100,000 records in total.
The number of re-balance thread is 1.
My question:
When I execute the sql "select *" repeatly, error "out of memory" occurs. I anaylyse the dump file with MAT and find that one thread consumes so much memory. Then I anaylyse the stack of thread and find that in the ignite method org.apache.ignite.internal.processors.cache.IgniteCacheOffheapManagerImpl.rebalanceIterator, a treeMap was created and cost near 7G memory!
Can somebody help me to solve the out of memory problem?

JVM options:
-server
-XX:MaxDirectMemorySize=512m
-Xms10g -Xmx10g
-XX:+AlwaysPreTouch
-XX:+UseG1GC
-XX:+AggressiveOpts
-XX:+ScavengeBeforeFullGC
-XX:+DisableExplicitGC
-XX:+UseNUMA
-XX:+PrintGCDetails
-XX:+PrintGCTimeStamps
-XX:+PrintGCDateStamps
-XX:+PrintAdaptiveSizePolicy
-XX:+UnlockDiagnosticVMOptions
-XX:+G1PrintRegionLivenessInfo
-XX:+PrintGCApplicationStoppedTime
-XX:+PrintGCApplicationConcurrentTime
-XX:G1ReservePercent=15
-XX:InitiatingHeapOccupancyPercent=45
-XX:+UseGCLogFileRotation
-XX:NumberOfGCLogFiles=10
-XX:GCLogFileSize=10M
-XX:+HeapDumpOnOutOfMemoryError
-XX:+ExitOnOutOfMemoryError

|Name                                       | Shallow Heap | Retained Heap |Context Class Loader                                                |Is Daemon
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
org.apache.ignite.thread.IgniteThread @ 0x5a0d32f20                                                                                |sys-#86%paloma2[172.17.0.1#192.154.163.17]%|          136 | 7,234,644,440 |org.springframework.boot.loader.LaunchedURLClassLoader @ 0x5a0ba53b8|false
|- at java.lang.OutOfMemoryError.<init>()V (OutOfMemoryError.java:48)                                                                                |                                           |              |               |                                                                    |
|- at org.apache.ignite.internal.processors.cache.persistence.file.IgniteNativeIoLib.pread(ILcom/sun/jna/Pointer;Lcom/sun/jna/NativeLong;Lcom/sun/jna/NativeLong;)Lcom/sun/jna/NativeLong; (Native Method)                                                                                |                                           |              |               |                                                                    |
|- at org.apache.ignite.internal.processors.cache.persistence.file.AlignedBuffersDirectFileIO.readIntoAlignedBuffer(Ljava/nio/ByteBuffer;J)I (AlignedBuffersDirectFileIO.java:347)                                                                                |                                           |              |               |                                                                    |
|- at org.apache.ignite.internal.processors.cache.persistence.file.AlignedBuffersDirectFileIO.read(Ljava/nio/ByteBuffer;J)I (AlignedBuffersDirectFileIO.java:215)                                                                                |                                           |              |               |                                                                    |
|- at org.apache.ignite.internal.processors.cache.persistence.file.FilePageStore.read(JLjava/nio/ByteBuffer;Z)V (FilePageStore.java:351)                                                                                |                                           |              |               |                                                                    |
|- at org.apache.ignite.internal.processors.cache.persistence.file.FilePageStoreManager.read(IJLjava/nio/ByteBuffer;Z)V (FilePageStoreManager.java:328)                                                                                |                                           |              |               |                                                                    |
|- at org.apache.ignite.internal.processors.cache.persistence.file.FilePageStoreManager.read(IJLjava/nio/ByteBuffer;)V (FilePageStoreManager.java:312)                                                                                |                                           |              |               |                                                                    |
|- at org.apache.ignite.internal.processors.cache.persistence.pagemem.PageMemoryImpl.acquirePage(IJZ)J (PageMemoryImpl.java:779)                                                                                |                                           |              |               |                                                                    |
|- at org.apache.ignite.internal.processors.cache.persistence.pagemem.PageMemoryImpl.acquirePage(IJ)J (PageMemoryImpl.java:624)                                                                                |                                           |              |               |                                                                    |
|- at org.apache.ignite.internal.processors.cache.persistence.CacheDataRowAdapter.initFromLink(Lorg/apache/ignite/internal/processors/cache/CacheGroupContext;Lorg/apache/ignite/internal/processors/cache/GridCacheSharedContext;Lorg/apache/ignite/internal/pagemem/PageMemory;Lorg/apache/ignite/internal/processors/cache/persistence/CacheDataRowAdapter$RowData;)V (CacheDataRowAdapter.java:140)|                                           |              |               |                                                                    |
|- at org.apache.ignite.internal.processors.cache.persistence.CacheDataRowAdapter.initFromLink(Lorg/apache/ignite/internal/processors/cache/CacheGroupContext;Lorg/apache/ignite/internal/processors/cache/persistence/CacheDataRowAdapter$RowData;)V (CacheDataRowAdapter.java:102)                                                                                |                                           |              |               |                                                                    |
|- at org.apache.ignite.internal.processors.cache.tree.DataRow.<init>(Lorg/apache/ignite/internal/processors/cache/CacheGroupContext;IJILorg/apache/ignite/internal/processors/cache/persistence/CacheDataRowAdapter$RowData;)V (DataRow.java:54)                                                                                |                                           |              |               |                                                                    |
|- at org.apache.ignite.internal.processors.cache.tree.CacheDataRowStore.dataRow(IIJLorg/apache/ignite/internal/processors/cache/persistence/CacheDataRowAdapter$RowData;)Lorg/apache/ignite/internal/processors/cache/persistence/CacheDataRow; (CacheDataRowStore.java:73)                                                                                |                                           |              |               |                                                                    |
|- at org.apache.ignite.internal.processors.cache.tree.CacheDataTree.getRow(Lorg/apache/ignite/internal/processors/cache/persistence/tree/io/BPlusIO;JILjava/lang/Object;)Lorg/apache/ignite/internal/processors/cache/persistence/CacheDataRow; (CacheDataTree.java:146)                                                                                |                                           |              |               |                                                                    |
|- at org.apache.ignite.internal.processors.cache.tree.CacheDataTree.getRow(Lorg/apache/ignite/internal/processors/cache/persistence/tree/io/BPlusIO;JILjava/lang/Object;)Ljava/lang/Object; (CacheDataTree.java:41)                                                                                |                                           |              |               |                                                                    |
|- at org.apache.ignite.internal.processors.cache.persistence.tree.BPlusTree$ForwardCursor.fillFromBuffer(JLorg/apache/ignite/internal/processors/cache/persistence/tree/io/BPlusIO;II)Z (BPlusTree.java:4660)                                                                                |                                           |              |               |                                                                    |
|- at org.apache.ignite.internal.processors.cache.persistence.tree.BPlusTree$ForwardCursor.init(JLorg/apache/ignite/internal/processors/cache/persistence/tree/io/BPlusIO;I)V (BPlusTree.java:4562)                                                                                |                                           |              |               |                                                                    |
|- at org.apache.ignite.internal.processors.cache.persistence.tree.BPlusTree$ForwardCursor.access$5300(Lorg/apache/ignite/internal/processors/cache/persistence/tree/BPlusTree$ForwardCursor;JLorg/apache/ignite/internal/processors/cache/persistence/tree/io/BPlusIO;I)V (BPlusTree.java:4501)                                                                                |                                           |              |               |                                                                    |
|- at org.apache.ignite.internal.processors.cache.persistence.tree.BPlusTree.findLowerUnbounded(Ljava/lang/Object;Ljava/lang/Object;)Lorg/apache/ignite/internal/util/lang/GridCursor; (BPlusTree.java:927)                                                                                |                                           |              |               |                                                                    |
|- at org.apache.ignite.internal.processors.cache.persistence.tree.BPlusTree.find(Ljava/lang/Object;Ljava/lang/Object;Ljava/lang/Object;)Lorg/apache/ignite/internal/util/lang/GridCursor; (BPlusTree.java:959)                                                                                |                                           |              |               |                                                                    |
|- at org.apache.ignite.internal.processors.cache.persistence.tree.BPlusTree.find(Ljava/lang/Object;Ljava/lang/Object;)Lorg/apache/ignite/internal/util/lang/GridCursor; (BPlusTree.java:950)                                                                                |                                           |              |               |                                                                    |
|- at org.apache.ignite.internal.processors.cache.IgniteCacheOffheapManagerImpl$CacheDataStoreImpl.cursor()Lorg/apache/ignite/internal/util/lang/GridCursor; (IgniteCacheOffheapManagerImpl.java:1483)                                                                                |                                           |              |               |                                                                    |
|- at org.apache.ignite.internal.processors.cache.persistence.GridCacheOffheapManager$GridCacheDataStore.cursor()Lorg/apache/ignite/internal/util/lang/GridCursor; (GridCacheOffheapManager.java:1555)                                                                                |                                           |              |               |                                                                    |
|- at org.apache.ignite.internal.processors.cache.IgniteCacheOffheapManagerImpl.reservedIterator(ILorg/apache/ignite/internal/processors/affinity/AffinityTopologyVersion;)Lorg/apache/ignite/internal/util/lang/GridCloseableIterator; (IgniteCacheOffheapManagerImpl.java:839)                                                                                |                                           |              |               |                                                                    |
|- at org.apache.ignite.internal.processors.cache.IgniteCacheOffheapManagerImpl.rebalanceIterator(Lorg/apache/ignite/internal/processors/cache/distributed/dht/preloader/IgniteDhtDemandedPartitionsMap;Lorg/apache/ignite/internal/processors/affinity/AffinityTopologyVersion;)Lorg/apache/ignite/internal/processors/cache/IgniteRebalanceIterator; (IgniteCacheOffheapManagerImpl.java:882)        |                                           |              |               |                                                                    |
|  |- <local> org.apache.ignite.internal.processors.cache.persistence.GridCacheOffheapManager @ 0x5a0d33368                                                                                |                                           |           64 |         1,648 |                                                                    |
|  |- <local> org.apache.ignite.internal.processors.cache.distributed.dht.preloader.IgniteDhtDemandedPartitionsMap @ 0x5a0d33408                                                                                |                                           |           24 |            24 |                                                                    |
|  |- <local> org.apache.ignite.internal.processors.affinity.AffinityTopologyVersion @ 0x5a0d33420                                                                                |                                           |           24 |            24 |                                                                    |
|  |- <local>java.util.TreeMap @ 0x5a0d33438                                                                                |                                           |           48 | 7,227,513,912 |                                                                    |
|  |- <local> java.util.HashSet @ 0x5a0d33468                                                                                |                                           |           16 |            64 |                                                                    |
|  |- <local> java.util.Collections$UnmodifiableCollection$1 @ 0x5a0d33478                                                                                |                                           |           24 |            80 |                                                                    |
|  |- <local> java.lang.Integer @ 0x5ad5cd658  354                                                                                |                                           |           16 |            16 |                                                                    |
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

Clues: the treeMap is created in the following code

    /** {@inheritDoc} */
    @Override public IgniteRebalanceIterator rebalanceIterator(IgniteDhtDemandedPartitionsMap parts,
        final AffinityTopologyVersion topVer)
        throws IgniteCheckedException {

        final TreeMap<Integer, GridCloseableIterator<CacheDataRow>> iterators = new TreeMap<>();

        Set<Integer> missing = new HashSet<>();

        for (Integer p : parts.fullSet()) {
            GridCloseableIterator<CacheDataRow> partIter = reservedIterator(p, topVer);

            if (partIter == null) {
                missing.add(p);

                continue;
            }

            iterators.put(p, partIter);
        }

        IgniteHistoricalIterator historicalIterator = historicalIterator(parts.historicalMap(), missing);

        IgniteRebalanceIterator iter = new IgniteRebalanceIteratorImpl(iterators, historicalIterator);

        for (Integer p : missing)
            iter.setPartitionMissing(p);

        return iter;
    }

A: Looks like there were rebalancing and select * queries running concurrently in the cluster.
Rebalancing is a process, that moves partitions between nodes to achieve the configured backup factor. All rebalanced data passes through the heap, so it may be polluted during this process. You can read about it here: https://apacheignite.readme.io/docs/rebalancing
Rebalancing may be tracked by corresponding messages in log or by waiting on a future, returned from IgniteCache#rebalance() method.
select * is also a pretty consuming operation, since it requires all data to be loaded to a single node.
Using lazy queries may help in this situation. You can enable this flag either in the JDBC connection string, or as SqlFieldQuery#lazy property.