text:
Q: Invert Angular 2 *ngFor

    {{ user.name }} is {{ user.age }} years old.

Is it possible to invert the ngFor that the items are added bottom up?

A: Update
@Pipe({
  name: 'reverse',
  pure: false
})
export class ReversePipe implements PipeTransform {
  constructor(private differs: IterableDiffers) {
    this.differ = this.differs.find([]).create();
  }

  transform(value) {
    const changes = this.differ.diff(value);
    if (changes) {
      this.cached = value.slice().reverse();
    }
    return this.cached;
  }
}

By default, Angular only calls the pipe's transform() method when the array reference has been changed, so it won't be called when items are added or removed from/to the array, meaning that changes to the array won't be reflected in the UI.
For the pipe to get called every time change detection is called, I made the pipe impure.
An impure pipe will be called very often, therefore it's important for it to work efficient.
Creating a copy of an array (perhaps even a large array) and then reversing its order is quite expensive.
Therefore a differ is to only do the actual work if some changes were recognized and otherwise return the cached result from the previous call.
Original
You can create a custom pipe that returns the array in the reverse order or just provide the data in the reverse order in the first place.
See also

*

*angular 2 sort and filter

*https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/Array/reverse

A: Surprisingly, after so many years there is still no solution posted here that does not have serious flaws. That is why in my answer, I am going to explain what drawbacks all current solutions have and present two new approaches to this problem which I consider to be better.

Drawbacks of current solutions
Live demos are available for each solution. Please check out the links under the explanations.
1. Pure pipe with slice().reverse() (currently accepted)
— by @Thierry Templier and @rey_coder (since ngx-pipes uses this method)
@Pipe({ name: 'reverse' })
export class ReversePipe implements PipeTransform {
  transform(value) {
    return value.slice().reverse();
  }
}

Pipes are pure by default, so Angular expects them to produce the same output given the same input. That is why the transform() method will not be called again when you make changes to the array unless you create a new array every time you want to update the old one, for example by writing
this.users = this.users.concat([{ name, age }]);

instead of
this.users.push({ name, age });

but doing so just because your pipe requires it is a bad idea.
So this solution only works if you are not going to modify the array.
In the live demo, you will see that only the Reset button works because it creates a new (empty) array when clicked, whereas the Add button only mutates the existing array.
Live demo
2. slice().reverse() without a pipe
— by @André Góis, @Trilok Singh and @WapShivam

   {{ user.name }} is {{ user.age }} years old.

Here, we use the same array methods but without a pipe, which means that Angular will call them on each change detection cycle. Changes to the array will now be reflected in the UI, but the problem here is that slice() and reverse() might get called too often because array changes are not the only thing that can cause change detection to run.
Note that we get the same behavior if we modify the code of the previous solution to make the pipe impure. We can do so by setting pure: false in the object passed to the Pipe decorator. I did it in the live demo in order to be able to log something in the console whenever slice() and reverse() are going to get called. I also added a button that lets you trigger change detection without changing the array. After clicking it, you will see in the console that slice() and reverse() were called although the array had not been modified, and that is something we would not want in an ideal solution. Nevertheless, this solution is the best of all current solutions.
Live demo
3. Trying to improve performance by caching the reversed array
— by @Günter Zöchbauer
@Pipe({ name: 'reverse', pure: false })
export class ReversePipe implements PipeTransform {
  constructor(private differs: IterableDiffers) {
    this.differ = this.differs.find([]).create();
  }

  transform(value) {
    if (this.differ.diff(value)) {
      this.cached = value.slice().reverse();
    }
    return this.cached;
  }
}

This is a clever attempt to solve the problem I described in the previous section. Here, slice() and reverse() are only called if the array's contents have actually changed. If they have not changed, the cached result of the last operation is returned.
To check for array changes, an Angular's IterableDiffer object is used. Such objects are also used by Angular internally during change detection. Again, you can check the console in the live demo to see that it actually works.
However, I do not think there is any performance improvement. On the contrary, I think this solution makes it even worse. The reason is that it takes the differ linear time to find out that the array has not changed, which is just as bad as calling slice() and reverse(). And if it has changed, the time complexity is still linear in the worst case because in some cases, the entire array has to be traversed before the differ detects a change. As an example, this happens when the last element of the array has been modified. In that case, the entire array will have to be traversed twice: when calling the differ and when calling slice() and reverse(), which is just terrible.
Live demo
4. Only using reverse()
— by @Prank100 and @Dan

   {{ user.name }} is {{ user.age }} years old.

This solution is an absolute no go.
The reason is that reverse() mutates the array instead of creating a new one, which is most probably undesired because you might need the original one in a different place. If you don't, you should just reverse the array as soon as it arrives in your application and never have to worry about it again.
There is an even more significant problem, which is especially dangerous because you cannot see it in development mode. In production mode, your array will be reversed during each change detection cycle, meaning that an array like [1,2,3] will keep switching between [1,2,3] and [3,2,1]. You definitely don't want that.
You don't see it in development mode because in that mode, Angular performs additional checks after each change detection run, which cause the reversed array to be reversed one more time bringing it back in its original order. The side effects of the second check are not reflected in the UI, and that is why everything seems to work fine, although in reality, it does not.
Live demo (production mode)

Alternative solutions
1. Only using array indices
// In the component:
userIdentity = i => this.users[this.users.length - 1 - i];

  {{ users[users.length - 1 - i].name }} is {{ users[users.length - 1 - i].age }} years old.

Instead of grabbing the user, we only grab the index i and use it to get the ith last element of the array. (Technically, we grab the user too, but we use _ as the variable name to indicate that we are not going to use that variable. That is a pretty common convention.)
Having to write users[users.length - 1 - i] multiple times is annoying. We could simplify the code by using this trick:

  <ng-container *ngIf="users[users.length - 1 - i] as user">
    {{ user.name }} is {{ user.age }} years old.
  </ng-container>

This way, we create a local variable which can be used inside the <ng-container>. Note that it will only work properly if your array elements are not falsy values because what we save in that variable is actually the condition for the *ngIf directive.
Also note that we have to use a custom TrackByFunction, and it is absolutely necessary if you don't want to spend a lot of time debugging afterwards, even though our simple example seems to work fine without it.
Live demo
2. Pure pipe that returns an iterable object
@Pipe({ name: 'reverseIterable' })
export class ReverseIterablePipe implements PipeTransform {
  transform<T>(value: T[]): Iterable<T> {
    return {
      *[Symbol.iterator]() {
        for (let i = value.length - 1; i >= 0; i--) {
          yield value[i];
        }
      }
    };
  }
}

*ngFor loops work with iterable objects internally, so we just construct one that fulfills our needs using a pipe. The [Symbol.iterator] method of our object is a generator function which returns iterators that let us traverse the array in reverse order. Please read this guide if it is the first time you hear about iterables, or if the asterisk syntax and the yield keyword are unfamiliar to you.
The beautiful thing about this approach is that it is enough to just create one iterable object for our array. The app will still work properly if we make changes to the array because the generator function returns a new iterator each time it is called. That means that we only have to create a new iterable when we create a new array, and that is why a pure pipe is enough here, which makes this solution better than the one with slice() and reverse().
I consider this to be the more elegant solution than the previous one because we do not have to resort to using array indices in our *ngFor loop. In fact, we do not need to change anything in our component other than adding the pipe because the entire functionality is wrapped within it.

  {{ user.name }} is {{ user.age }} years old.

Also, don't forget to import and declare the pipe in your module.
Note that I named the pipe differently this time in order to indicate that it only works in contexts where an iterable is enough. You cannot apply other pipes to its output if they expect arrays as their input, and you cannot use it to print the reversed array by writing {{ users | reverseIterable }} in your template like you can with normal arrays because the iterable object does not implement the toString() method (although nothing stops you from implementing it if it makes sense in your use case). That is the disadvantage this pipe has compared to the one with slice() and reverse(), but it is definitely better if all you want to do is to use it in *ngFor loops.
Live demo
Possible optimization with a stateful pure pipe
"Stateful pure pipes" may sound like an oxymoron, but they are actually something Angular lets us create if we use its relatively new compilation and rendering engine called Ivy.
Before Ivy was introduced, Angular would only create one instance of a pure pipe, even if we used it more than once in our template. That means that the transform() method would always be called on the same object. As a consequence, we could not rely on any state stored in that object because it was shared between all occurences of the pipe in our template.
Ivy, however, takes a different approach by creating a separate pipe instance for each of its occurrences, which means that we can now make pure pipes stateful. Why would we want to do that? Well, the problem with our current solution is that, although we do not have to create a new iterable object when we modfiy the array, we still have to do it when we create a new one. We could fix that by stroing the array in a property of our pipe instance and making the iterable depend on that property instead of the array passed to the transform() method. We then only need to assign the new array to our existing property whenever transform() is called, and just return the existing iterable object afterwards.
@Pipe({ name: 'reverseIterable' })
export class ReverseIterablePipe implements PipeTransform {
  private array: any[] = [];
  private reverseIterable: Iterable<any>;

  constructor() {
    this.reverseIterable = {
      [Symbol.iterator]: function*(this: ReverseIterablePipe) {
        for (let i = this.array.length - 1; i >= 0; i--) {
          yield this.array[i];
        }
      }.bind(this)
    };
  }

  transform<T>(value: T[]): Iterable<T> {
    this.array = value;
    return this.reverseIterable;
  }
}

Note that we have to bind the generator function to this because this might have a different meaning in other contexts if we don't. We would normally fix that by using an arrow function, but there is no such syntax for generator functions, so we have to bind them explicitly.
Ivy is enabled by default starting with Angular version 9, but I disabled it in the live demo in order to show you why we cannot make pure pipes stateful without it. In order for the app to work correctly, you will have to set angularCompilerOptions.enableIvy to true in the tsconfig.json file.
Live demo

A: One could use ngx-pipes
npm install ngx-pipes --save
module
import {NgPipesModule} from 'ngx-pipes';

@NgModule({
 // ...
 imports: [
   // ...
   NgPipesModule
 ]
})

component
@Component({
  // ..
  providers: [ReversePipe]
})
export class AppComponent {
  constructor(private reversePipe: ReversePipe) {
  }
}

then using in template

A: try this:

{{item}}

A: you can do it using javascript function.

    {{ user.name }} is {{ user.age }} years old.

A: The solution of using .slice().reverse() in the template is simple and effective. However, you should be careful when using the iteration index.
This is because .slice() method returns a new array for the view, so that our initial array does not change. The problem is that the reversed array has also reversed index.
Therefore, you should also reverse the index, if you want to use it as a variable.  Example:

{{item}}

In the above, instead of i we use the reversed items.length - 1 - i so that a clicked item corresponds to the same item of our initial array.
Check this stackblitz:
https://stackblitz.com/edit/angular-vxasr6?file=src%2Fapp%2Fapp.component.html

A: This should do the trick

  {{ user.name }} is {{ user.age }} years old.

A: There are two problems with the selected answer:
First, the pipe won't notice source array modification, unless you add pure: false to the pipe's properties.
Second, the pipe does not support two-directional binding, because the copy of the array is reversed, not the array itself.
The final code looks like:
    import {Pipe} from 'angular2/core';

    @Pipe({
      name: 'reverse',
      pure: false
    })
    export class ReversePipe {
      transform (values) {
        if (values) {
          return values.reverse();
        }
      }
    }

Plunker
http://plnkr.co/edit/8aYdcv9QZJk6ZB8LZePC?p=preview

A: You can simply use JavaScript's .reverse() on the array. Don't need an angular specific solution.

   {{ user.name }} is {{ user.age }} years old.

See more here:
https://www.w3schools.com/jsref/jsref_reverse.asp

A: You need to implement a custom pipe that leverage the reverse method of JavaScript array:
import { Pipe, PipeTransform } from '@angular/core';

@Pipe({ name: 'reverse' })

export class ReversePipe implements PipeTransform {
  transform(value) {
    return value.slice().reverse();
  }
}

You can use it like that:

    {{ user.name }} is {{ user.age }} years old.

Don't forget to add the pipe in the pipes attribute of your component.

A: Using transform requires PipeTransform:
    import { Pipe, PipeTransform } from '@angular/core';

    @Pipe({
      name: 'reverse',
      pure: false
    })

    export class ReversePipe implements PipeTransform {
      transform (values: any) {
        if (values) {
          return values.reverse();
        }
      }
    }

Call it with

A: You can simply add slice() and reverse() like this:

   {{ user.name }} is {{ user.age }} years old.

A: If anyone is using typescript here is how I managed to get it to work, using @Günter Zöchbauer's answer.
@Pipe({
  name: 'reverse',
  pure: false
})
export class ReversePipe implements PipeTransform {

  differs: any
  cashed: any
  constructor(private _differs: IterableDiffers) {
    this.differs = this._differs.find([]).create(null);
  }
  /**
   * Takes a value and makes it lowercase.
   */
  transform(value, ...args) {
    const changes = this.differs.diff(value)
    if (changes) {
      this.cashed = value.slice().reverse();;
    };
    return this.cashed
  }
}


text:
Q: Power BI Desktop - Storing credentials I am fetching POWER BI admin and workspace information using the Power BI Rest API from the power BI Desktop which I plan to publish as a report later. I have written a function in Power Bi query editor to generate an access token which I am calling in my REST API call. All this works fine. But, how can I secure my function to generate access token. Currently, the username and password are being hardcoded in the function.
What is the best practice and how to make this more secure.

A: I solved a similar problem a while ago and found the best solution to be using this Power BI REST API Connector:
Article describing the connector: https://www.thepoweruser.com/2021/02/21/power-bi-rest-api-connector/
Github: https://github.com/migueesc123/PowerBIRESTAPI

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to execute a loop only once I'm creating a program that provides the user with job offers. For example they're given 10 offers and they decide to reject the first 3 right off the bat. From there I'm taking the maximum number out of the three and I want to accept the next best offer. Although my program is accepting the best offer instead of the next best.
To explain a little further, let's say offer 4 was higher than the max number out of the first 3, I want that offer to be considered 'accepted' even if offer number 5 is higher. Here is my code at the moment, the problem lies that the last 'if' statement keeps repeating causing it to give me the best offer instead of next best.
    offerRejList = []
    offerList = []
    counter = 1
    counterRej = 1
    while counter <= jobOff:
        offer = random.gauss(65, 5)
        offerList.append(offer)
        if counterRej <= jobRej:
            offerRejList.append(offer)
        print('Offer #' ,counter, ': $',offer,'-',)

        counterRej += 1
        counter += 1
        if offer > max(offerRejList):
            acceptedOffer = offer

A: http://www.tutorialspoint.com/python/python_loop_control.htm
That's all you need. Immediately after you have "acceptedOffer"


text:
Q: What should the attribute value be for a custom attribute in an array passed to getProductByAttributes? The question I propose actually has several parts so I will explain with examples and end with two questions who's answers should answer the topic question.
The file / method in question and instructions to repeat the tests.
app\code\core\Mage\Catalog\Model\Product\Type\Configurable.php (Line 494)

    public function getProductByAttributes($attributesInfo, $product = null)

*

*Create a custom attribute such as "Water Type" with the possible values of, "Clear Water, Opaque Water".

*Create a configurable product that uses the previously created attribute.

*Create two associated simple products, each having one of the possible values.

*Get the product id that you create for simplicity purposes and setup a test environment/extension however you please.

Now let's get some information for this product. I'm going to make some assumptions for testing purposes, such as the product being configurable.
//load up our created product.
$product = Mage::getModel('catalog/product')->load($ourProductId);

//get the attributes for the configurable product and dump them in the magento log.
$attributes = Mage::getModel('catalog/product_type_configurable')->getConfigurableAttributesAsArray($product);

//log the attributes for the product to the log so we can see what's available.
Mage::log(print_r($attributes,true));

//you should get a result similar to this
2014-02-25T21:21:25+00:00 DEBUG (7): Array
(
    [0] => Array
        (
            [id] => 204
            [label] => Water Type
            [use_default] => 0
            [position] => 0
            [values] => Array
                (
                    [0] => Array
                        (
                            [product_super_attribute_id] => 204
                            [value_index] => 165
                            [label] => Clear Water
                            [default_label] => Clear Water
                            [store_label] => Clear Water
                            [is_percent] => 0
                            [pricing_value] =>
                            [use_default_value] => 1
                        )
                    [1] => Array
                        (
                            [product_super_attribute_id] => 204
                            [value_index] => 166
                            [label] => Opaque Water
                            [default_label] => Opaque Water
                            [store_label] => Opaque Water
                            [is_percent] => 0
                            [pricing_value] =>
                            [use_default_value] => 1
                        )
                )
            [attribute_id] => 226
            [attribute_code] => water_type
            [frontend_label] => Water Type
            [store_label] => Water Type
        )
)

Now, the end result is that we want to get the associated product model by an array of attributes. Looking at the attributes that are available let's manually create an array for the sake of testing and pass it to getProductByAttributes() and see if we can do that.
We want to get the associated product that has the 'Opaque Water' attribute set, so we'll put that into our array and pass it on. According to the comments above the getProductByAttributes() method it requires an array with $attributeId => $attributeValue. This is what I will put into my first array to pass through based on the information I dumped into my log.
$filterAttributes = array(
    '226' => 'Opaque Water'
);

$associatedProduct = Mage::getModel('catalog/product_type_configurable')->getProductByAttributes($filterAttributes,$product);

//let's see if it worked
if ($associatedProduct !== NULL)
{
    Mage::log('We found the ' . $associatedProduct->getTypeId() . ' associated product, yay');
} else {
    Mage::log('No product found, its null, boo');
}

The result you should/will receive is sadly null. Let's do some logging on the method and try to figure out why it's null! Let's count the collection within the getProductByAttributes before it returns anything so that we're sure it's grabbing the associated products, it should return 2 products before the filtering is done.
Add this line of code inside of the getProductByAttributes method in this file, app\code\core\Mage\Catalog\Model\Product\Type\Configurable.php.
//add this directly after the 'getUsedProductCollection' call and before the attributes are added to filter by. This will give us the count of that collection before it filters it.
Mage::log('Product collection count: ' . $productCollection->count());

If done correctly, your log will show some magic just happened. Your product was found and the result from the previous code is no longer null. This brings me to the first question.
Question #1 Why does the count change the fact that the filter previously didn't work?
Now let's remove the $productCollection->count() and test again to verify you still get null. This should definitely be the case. Let's now change the $filterAttributes array to use the value_index instead of the name of the value.
//change from 'Opaque Water' to '165', the value_index from the attributes array we dumped.
$filterAttributes = array(
    '226' => '165'
);

Run it all again and get the outcome. It works fine, without needing to add in the $productCollection->count().
Question #2 Why does using value_index work without needing to force the collection to load prior to adding the filters?
Possible Answer / Guess
I have some theories of why, but I don't know if they are correct or not. I will provide them either way.
Theory #1 The attribute value name isn't available until the collection is loaded, which is why loading it with the count makes it work with the filter is applied. This doesn't make sense to me though because wouldn't the filter use those attributes during the select statements in the database and get the same result without needing for the collection to be force loaded?
Theory #2 Bad variable naming and comments. Whether or not it works after force loading the collection with count, the $attributeValue should be something other than what it implies such as value_index that works. This implies that what I passed first 'Opaque Water' is an actual value. I've also considered that it's not technically a value and that because we're dealing with a select, value_index is actually the value regardless of what it's called when you dump the attributes.

A: We've been going back and forth on this for the better part of the afternoon on IRC and I think it just comes down to your calling the getProductByAttributes method incorrectly.  It expects the following:
// 92 = EAV attribute_id from the eav_attribute table
// 17 = EAV value_id from the eav_attribute_option_value table
$attributes = [92 => 17];

/* @var $product Mage_Catalog_Model_Product */
$product = Mage::getModel('catalog/product')->load(3);

/* @var $simpleProduct Mage_Catalog_Model_Product_Type_Configurable */
$simpleProduct = Mage::getModel('catalog/product_type_configurable');

$result = $simpleProduct->getProductByAttributes($attributes, $product);
var_dump($result);

Doing this generates a query (regardless of weather you insert a ->load() statement inside the getProductByAttributes method to debug it) that looks like this...
SELECT `e`.*, `link_table`.`parent_id`, `at_color`.`value` AS `color`
FROM `catalog_product_entity` AS `e`
INNER JOIN `catalog_product_super_link` AS `link_table`
    ON link_table.product_id = e.entity_id
INNER JOIN `catalog_product_entity_int` AS `at_color`
    ON (`at_color`.`entity_id` = `e`.`entity_id`)
    AND (`at_color`.`attribute_id` = '92')
    AND (`at_color`.`store_id` = 0)
WHERE (link_table.parent_id = 3)
AND (at_color.value = '17')

When you structure your $filterAttributes array as you do, the query comes out like this (notice the last line)...
SELECT `e`.*, `link_table`.`parent_id`, `at_color`.`value` AS `color`
FROM `catalog_product_entity` AS `e`
INNER JOIN `catalog_product_super_link` AS `link_table`
    ON link_table.product_id = e.entity_id
INNER JOIN `catalog_product_entity_int` AS `at_color`
    ON (`at_color`.`entity_id` = `e`.`entity_id`)
    AND (`at_color`.`attribute_id` = '92')
    AND (`at_color`.`store_id` = 0)
WHERE (link_table.parent_id = 3)
AND (at_color.value = 'Opaque Water')

So, that's why it doesn't work initially.  The question I think you (and I for a bit) is why it seems to work when you go into the getProductByAttributes method and do this...
if (is_array($attributesInfo) && !empty($attributesInfo)) {
    $productCollection = $this->getUsedProductCollection($product)->addAttributeToSelect('name');
    $productCollection->load(); // This here...
    foreach ($attributesInfo as $attributeId => $attributeValue) {
        $productCollection->addAttributeToFilter($attributeId, $attributeValue);
    }
    // ... more code follows
}

The reason is, I'm seeing is that by loading the collection before it has a chance to add those malformed attributes, it actually fully loads the child products associated with the parent configurable product... all of them... see, this is the query that gets executed when you call ->load() without any attribute filtering...
SELECT `e`.*, `link_table`.`parent_id`
FROM `catalog_product_entity` AS `e`
INNER JOIN `catalog_product_super_link` AS `link_table`
    ON link_table.product_id = e.entity_id
WHERE (link_table.parent_id = 3)

It's not returning to you a collection filtered by your $filterAttributes array... it's returning ALL constituent products of that configurable product.
Bottom line, reformat that $filterAttributes array!


text:
Q: Asymptotic complexity of building a binary tree What is the complexity of building a balanced binary tree of size n from scratch?
Node insertion is O(log n).
However, as you go along, the cumulative time is
O( (log 1) + (log 2) + ... + (log (n-1)) + (log n) ).
What does this "add up" to?
It is o(n log(n)), small 'o', i don't know how far small.

A: log(1) + log(2) + ... + log(n) = log(1*2*..*n) = log(n!) which is in Theta(nlogn)
So, building a (balanced) tree from scratch has a tight asymptotic bound of Theta(nlogn)

EDIT:
I also wanted to show you a proof that you cannot build a BST better than O(nlogn) with any algorithm. Basically - this is because it will allow sorting better than O(nlogn) by simply building your tree with the 'better' algorithm, and then - doing in-order traversal on the tree and outputting elements. The result will be a sorted array.
Complexity in-order traversal is O(n), and since assuming the tree is built faster then O(nlogn) - we get contradiction to the fact that sorting is Omega(nlogn) problen.


text:
Q: How do I avoid Enum + Trait pattern when a struct is not object safe? I get the implications of object safety, but I'm trying to find an idiomatic way to solve for this situation.
Say I have two structs that share common behavior and also need to derive PartialEq for comparison in another part of the program:
trait Growl:PartialEq {
    fn growl(&self);
}

#[derive(PartialEq)]
struct Pikachu;

#[derive(PartialEq)]
struct Porygon;

impl Growl for Pikachu {
    fn growl(&self) {
        println!("pika");
    }
}

impl Growl for Porygon {
    fn growl(&self) {
        println!("umm.. rawr?");
    }
}

In another struct, I want to hold a Vec of these objects. Since I can't use a trait object with Vec<Box<Growl>>...
struct Region{
    pokemon: Vec<Box<dyn Growl>>,
}

// ERROR: `Growl` cannot be made into an object

... I need to get more creative. I read this article, which suggests using an enum or changing the trait. I haven't yet explored type erasure, but it seems heavy-handed for my use case. Using an enum like this is what I've ended up doing but it feels unnecessarily complex
enum Pokemon {
    Pika(Pikachu),
    Pory(Porygon),
}

Someone coming through this code in the future now needs to understand the individual structs, the trait (which provides all functionality for the structs), and the wrapper enum type to make changes.
Is there a better solution for this pattern?

A:
I read this article, which suggests using an enum or changing the trait. I haven't yet explored type erasure, but it seems heavy-handed for my use case.

Type erasure is just a synonym term for dynamic dispatch - even your original Box<dyn Growl> "erases the type" of the Pokemon. What you want here is to continue in the same vein, by creating a new trait better taylored to your use case and providing a blanket implementation of that trait for any type that implements the original trait.
It sounds complex, but it's actually very simple, much simpler than erased-serde, which has to deal with serde's behemoth traits. Let's go through it step by step. First, you create a trait that won't cause issues with dynamic dispatch:
/// Like Growl, but without PartialEq
trait Gnarl {
    // here you'd have only the methods which are actually needed by Region::pokemon.
    // Let's assume it needs growl().
    fn growl(&self);
}

Then, provide a blanket implementation of your new Gnarl trait for all types that implement the original Growl:
impl<T> Gnarl for T
where
    T: Growl,
{
    fn growl(&self) {
        // Here in the implementation `self` is known to implement `Growl`,
        // so you can make use of the full `Growl` functionality, *including*
        // things not exposed to `Gnarl` like PartialEq
        <T as Growl>::growl(self);
    }
}

Finally, use the new trait to create type-erased pokemon:
struct Region {
    pokemon: Vec<Box<dyn Gnarl>>,
}

fn main() {
    let _region = Region {
        pokemon: vec![Box::new(Pikachu), Box::new(Porygon)],
    };
}

Playground


text:
Q: Running .sql file within a SQL query I have a SQL script I need to run on about 20 different databases.
I basically just need to be able to run some SQL, then have it load and run a file from the disk, do more SQL, run that same script again, etc.
I was hoping to make a SQL script that would basically look something like this:
use database1
go
exec c:\release.sql
go

use database2
go
exec c:\release.sql
go

use database3
go
exec c:\release.sql
go

--etc....
I've looked online a bunch and found a way to do something similar in a batch file with sqlcmd but it isn't working and I don't see how to switch databases that way, either.
Thanks a ton!
Ben

A: You can switch management studio to sqlcmd mode (query menu) and then run a script with :r script.sql
To do this on a dynamically generated list of databases you have to do some sqlcmd trickery:

*

*set output to file

*generate the command to execute

*set output to stdout

*execute the file

*delete the temp file

I assume in this example that the file script.sql exists in c:\temp. Note that the GO statements are important in the script or the sqlcmd parser will get confused.
:OUT $(TEMP)\db.sql
declare @script nvarchar(max)
select @script = isnull(@script, '')
               + 'use ' + name + char(13) + char(10)
               + ':r c:\temp\script.sql' + char(13) + char(10)
  from sys.databases
 where name like N'%[_]db'
print @script

GO

:OUT stdout
:r $(TEMP)\db.sql

GO

!!del $(TEMP)\db.sql /s /q

A: You don't need to do this in SSMS. You just need to create a CMD script.
IF you have a static set of databases to run on, then use the following:
@ECHO OFF

SET MyServer="(local)"
SET MyScript="c:\release.sql"

SQLCMD -S %MyServer% -E -i %MyScript% -d database1
SQLCMD -S %MyServer% -E -i %MyScript% -d database2
...
SQLCMD -S %MyServer% -E -i %MyScript% -d database20

IF you have a dynamic set of databases that can be queried for, then use the following:
@ECHO OFF

SET MyServer="(local)"
SET MyScript="c:\release.sql"
SET MyQuery="SET NOCOUNT ON; SELECT [Name] FROM [sys].[databases] sd WHERE sd.[name] LIKE N'%%[_]db' ORDER BY sd.[name];"

FOR /F %%B IN ('SQLCMD -h -1 -S %MyServer% -E -Q %MyQuery%') DO (
    REM remove the "echo" from the next line to run the scripts
    echo SQLCMD -S %MyServer% -E -i %MyScript% -d %%B -o results-%%B.txt
)

Using the %%B in the output filename will give you a different output file per database, as in:

results-database1_db.txt
  results-database2_db.txt
  ...

Other notes:

*

*Use (local) instead of localhost when connecting to the local, default instance as it uses shared memory while localhost forces a TCP connection.

*If you are searching for an underscore in a LIKE statement, enclose it in square brackets else it is a single-character wild card (which still technically works sometimes, but could also match other characters): [_]

A: Thanks everyone who pitched in! The following seems like it might work (based on @srutzky's answer)

sqlcmd -S "localhost" -E -i "c:\release.sql" -d database1 -o results.txt

The thing I am missing by using a cmd prompt instead of SSMS is that I don't think I can write  cursor to loop through each database that ends with "_db" and then execute against that...  Here's the SQL I have but I just need to be able to put the link to the SQL file to execute.
link
If I put the release script SQL into this file into the @text variable it doesn't work because it blows up on each GO statement I have in my release.sql file.
declare @text as nvarchar(max)
set @text = N'
-- GET AND RUN SCRIPT FROM DISK!
'

declare C_CURSOR CURSOR FOR
    select  [Name] from sys.databases
    where   name like '%_db'
    order by name

declare @runtext as nvarchar(max)
declare @DB_Name as nvarchar(200)

OPEN C_CURSOR
fetch next from C_CURSOR INTO @DB_Name
WHILE(@@FETCH_STATUS = 0)
BEGIN

    print @DB_Name
    set @runtext = 'select ''' + @DB_Name + ''' as DatabaseName
        use ' + @DB_Name + N'
    ' + @text

    exec sp_executesql  @runtext

    fetch next from C_CURSOR INTO @DB_Name
END

CLOSE C_CURSOR
DEALLOCATE C_CURSOR

Thanks again!

A: I ended up combining 2 things. I made a SQL script that creates a cursor to find the databases and then prints a list of commands for a CMD prompt. I then run that in the command prompt. Below is what we output with our sql script and then save as a .bat file that we run. It's working great!
That script is essentially created with the following SQL script:
/*** GET DATABASES IN THE CURSOR QUERY BELOW! */
declare C_CURSOR CURSOR FOR
        select  [Name] from sys.databases
        where   name like '%_db'
        order by name

/* THIS IS WHERE THE CURSOR STARTS*/
declare @DB_Name as nvarchar(200)

OPEN C_CURSOR
fetch next from C_CURSOR INTO @DB_Name
WHILE(@@FETCH_STATUS = 0)
BEGIN

    print 'SQLCMD -S "localhost" -E -i "C:\release.sql" -d ' +  @DB_Name + ' -o ' +  @DB_Name + '_results.txt'

    fetch next from C_CURSOR INTO @DB_Name
END

CLOSE C_CURSOR
DEALLOCATE C_CURSOR

That outputs the following which we then run in a .bat file
SQLCMD -S "localhost" -E -i "C:\release.sql" -d database1 -o database1_results.txt
SQLCMD -S "localhost" -E -i "C:\release.sql" -d database2 -o database2_results.txt
SQLCMD -S "localhost" -E -i "C:\release.sql" -d database3 -o database3_results.txt

Thanks everyone!


text: Q: Faulty keyboard key_m So my laptops keyboard key_m is faulty and is constantly pressing on itself, so i wanted to switch m to a key I don't use and doesn't affect linux, or code am writing . Was thinking switching m with numlock. Is this possible with linux?


text:
Q: Why did defragmenting C drive increase my free disk space by 10 GB? I used Defraggler to defragment free space on my 100 GB C:\ drive which was 85 GB full. After defragmentation, the drive showed only 75 GB full. How did 10 GB  of free space magically appear? Did I lose any data?
I did a disk cleanup before defragmenting and my trash was only about 11 MB, so it can't be because of cleaning the temporary files. Note that I defragmented "free space" which means that it should have rearranged the empty blocks to be contiguous.

A: Each fragment has to be tracked somewhere. That takes storage space (within the File system's plumbing, not stuff you're meant to directly access).
An example: Suppose you have a single file with 1000 fragments. Thus your file is stored through a collection of random blocks.. Rather than in a single continuous block. This means the fragmented file requires 1000x more storage space within the file system's plumbing, if only for storing addresses for each fragment. The file system plumbing keeps little dictionaries/databases/maps/tables/list to the location of each fragment of the file. So, for the file system plumbing, storing a list of a single fragment pointer doesn't need much space, compared to a list of 1000 fragment pointers..
But hey, maybe I'm wrong...
Edit: Supporting information from here:

When a non-resident data stream is too
  much fragmented, so that its effective
  allocation map cannot fit entirely
  within the MFT record, the allocation
  map may be also stored as an
  non-resident stream, with just a small
  resident stream containing the
  indirect allocation map to the
  effective non-resident allocation map
  of the non-resident data stream.

Translation: If you have heavy fragmentation, the general case assumptions of the file system plumbing won't apply. As such, the FS must take steps to accommodate the fragmentation and end up costing extra storage space, just to manage the fragments. Exactly my guess from the first place.

Edit: Given the above, it still seems like 10GB being lost just to file fragmentation is crazy. I'm betting that while defragging, you had some common file system corruption that was corrected automatically. I'm thinking not only did you have massive fragmentation, but also partially deleted files taking up storage space. It would have been nice to see a scandisk log from that defrag (or a run of scandisk prior to defrag)

A: What probably happened is that the defrag operation forced Windows to throw out some system restore snapshots. It'd be a pathological case of fragmentation to cause metadata overhead to be a full 10% of your drive space on top of what Windows normally uses.  even then, I'm not sure it's possible.
I don't see anything in Defraggler's version history or documentation that indicates that it's able to correctly defragment files to prevent the purging of shadow copies.  In fact, this thread from Defraggler's support forum indicates that they know that it's happening (there's a post from a board admin labeled "Official Piriform Bug Fixer" in thread) but don't indicate whether or not they're going to fix it.
Shadow copies may be lost when you defragment a volume: The reason this happens is that by default, VSS operates with 16 KB clusters by default, while most NTFS volumes are formatted with 4 KB clusters.  So if a defrag operation is moving data that isn't a multiple of a 16 KB cluster (or the "distance" it's moved isn't a multiple of 16 KB), then VSS will track it as a change and might purge all your snapshots.
MSDN: Defragmenting Files:

When possible, move data in blocks aligned relative to each other in 16-kilobyte (KB) increments. This reduces copy-on-write overhead when shadow copies are enabled, because shadow copy space is increased and performance is reduced when the following conditions occur:

*

*The move request block size is less than or equal to 16 KB.

*The move delta is not in increments of 16 KB.

Vista's built in defrag doesn't do this:

One change that's not obvious to users is our shadow copy optimization during defragmentation. Defrag has special heuristics to move file blocks in a way that will minimize the copy-on-write activity and shadow copy storage area consumption. Without this optimization, the defragmentation process would accelerate the deletion of older shadow copies.


text:
Q: Exception with Spring @Validated and @InitBinder When I use Spring @Validated for validating I get a strange problem.
Here is the core code.
Java model:
@Getter
@Setter
public class User {

    private String userName;
    private String password;
    private String email;

}

Custom UserValidate:
    public class UserValidate implements Validator {

    @Override
    public boolean supports(Class<?> arg0) {
        System.out.println("ee:"+arg0+","+User.class.isAssignableFrom(arg0));
        return User.class.isAssignableFrom(arg0);
    }

    @Override
    public void validate(Object target, Errors errors) {
        //ValidationUtils.rejectIfEmpty(errors, "userName", "user.userName.required", "username can not be empty");
        //ValidationUtils.rejectIfEmpty(errors, "password", "user.password.required", "password can not be empty");
        //ValidationUtils.rejectIfEmpty(errors, "email", "user.email.required", "email can not be empty");
        User user = (User) target;
        int length = user.getUserName().length();
        if (length > 20) {
            errors.rejectValue("userName", "user.userName.too_long", "Username cannot exceed {20} characters");
        }
        length = user.getPassword().length();
        if (length < 6) {
            errors.rejectValue("password", "user.password.too_short", "Password is too short to be less than {6} characters");
        } else if (length > 20) {
            errors.rejectValue("password", "user.password.too_long", "Password is too long to be longer than {20} characters");
        }
        int index = user.getEmail().indexOf("@");
        if (index == -1) {
            errors.rejectValue("email", "user.email.invalid_email", "Bad mailbox format");
        }
    }
}

Thymeleaf form:

    <form action="#" th:action="@{/addUser}"  method="POST">
        userName :<input type="text" name="userName"  />

        password :<input type="text" name="password" />

        email :<input type="text" name="email" />

        result:

        <input type="submit" />
    </form>

Controller:
import java.util.List;
import java.util.function.Consumer;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.servlet.ModelAndView;

import com.example.demo.app.model.User;
import com.example.demo.app.validate.UserValidate;
import com.google.common.collect.ImmutableListMultimap;
import com.google.common.collect.ImmutableListMultimap.Builder;

@Controller
public class UserController {

    @GetMapping("/userInfo")
    public ModelAndView userInfo() {
        ModelAndView userView = new ModelAndView("user");
        return userView;
    }

    @PostMapping("/addUser")
    public String addBook(@Validated User user,BindingResult result, Model model) {

        if(result.hasErrors()){
            List<ObjectError> allErrors = result.getAllErrors();
            Builder<String, String> builder = ImmutableListMultimap.builder();
            allErrors.stream().forEach(new Consumer<ObjectError>() {

                @Override
                public void accept(ObjectError t) {
                    builder.put(t.getObjectName(), t.getDefaultMessage());
                }
            });

            ImmutableListMultimap<String, String> build = builder.build();
            model.addAttribute("result",build);
        }else {
            model.addAttribute("result","success");
        }
        return "user";
    }

    @InitBinder
    public void initBinder(WebDataBinder binder) {
        binder.addValidators(new UserValidate());
    }

}

After submitting, the exception is abnormal. The result of the exception is that the ImmutableListMultimap class also performs the validation process of UserValidate. Why does this happen?
exception stack:
ee:class com.example.demo.app.model.User,true
ee:class com.google.common.collect.ImmutableListMultimap,false
2018-06-06 18:07:40.172 ERROR 10696 --- [nio-8088-exec-1] o.a.c.c.C.[.[.[.[dispatcherServlet]      : Servlet.service() for servlet [dispatcherServlet] in context with path [/spring-demo] threw exception [Request processing failed; nested exception is java.lang.IllegalStateException: Invalid target for Validator [com.example.demo.app.validate.UserValidate@2a8b1054]: {user=[Password is too short to be less than {6} characters, Bad mailbox format]}] with root cause

java.lang.IllegalStateException: Invalid target for Validator [com.example.demo.app.validate.UserValidate@2a8b1054]: {user=[Password is too short to be less than {6} characters, Bad mailbox format]}
    at org.springframework.validation.DataBinder.assertValidators(DataBinder.java:568) ~[spring-context-4.3.17.RELEASE.jar:4.3.17.RELEASE]
    at org.springframework.validation.DataBinder.setValidator(DataBinder.java:558) ~[spring-context-4.3.17.RELEASE.jar:4.3.17.RELEASE]
    at com.example.demo.app.controller.UserController.initBinder(UserController.java:56) ~[classes/:na]
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_144]
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_144]
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_144]
    at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_144]
    at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:205) ~[spring-web-4.3.17.RELEASE.jar:4.3.17.RELEASE]
    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:133) ~[spring-web-4.3.17.RELEASE.jar:4.3.17.RELEASE]
    at org.springframework.web.method.annotation.InitBinderDataBinderFactory.initBinder(InitBinderDataBinderFactory.java:64) ~[spring-web-4.3.17.RELEASE.jar:4.3.17.RELEASE]
    at org.springframework.web.bind.support.DefaultDataBinderFactory.createBinder(DefaultDataBinderFactory.java:57) ~[spring-web-4.3.17.RELEASE.jar:4.3.17.RELEASE]
    at org.springframework.web.method.annotation.ModelFactory.updateBindingResult(ModelFactory.java:218) ~[spring-web-4.3.17.RELEASE.jar:4.3.17.RELEASE]
    at org.springframework.web.method.annotation.ModelFactory.updateModel(ModelFactory.java:204) ~[spring-web-4.3.17.RELEASE.jar:4.3.17.RELEASE]
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.getModelAndView(RequestMappingHandlerAdapter.java:931) ~[spring-webmvc-4.3.17.RELEASE.jar:4.3.17.RELEASE]
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:832) ~[spring-webmvc-4.3.17.RELEASE.jar:4.3.17.RELEASE]
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:738) ~[spring-webmvc-4.3.17.RELEASE.jar:4.3.17.RELEASE]
    at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85) ~[spring-webmvc-4.3.17.RELEASE.jar:4.3.17.RELEASE]
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:967) ~[spring-webmvc-4.3.17.RELEASE.jar:4.3.17.RELEASE]
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:901) ~[spring-webmvc-4.3.17.RELEASE.jar:4.3.17.RELEASE]
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970) ~[spring-webmvc-4.3.17.RELEASE.jar:4.3.17.RELEASE]
    at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:872) ~[spring-webmvc-4.3.17.RELEASE.jar:4.3.17.RELEASE]
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:661) ~[tomcat-embed-core-8.5.31.jar:8.5.31]
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846) ~[spring-webmvc-4.3.17.RELEASE.jar:4.3.17.RELEASE]
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:742) ~[tomcat-embed-core-8.5.31.jar:8.5.31]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231) ~[tomcat-embed-core-8.5.31.jar:8.5.31]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.31.jar:8.5.31]
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52) ~[tomcat-embed-websocket-8.5.31.jar:8.5.31]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-8.5.31.jar:8.5.31]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.31.jar:8.5.31]
    at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:99) ~[spring-web-4.3.17.RELEASE.jar:4.3.17.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-4.3.17.RELEASE.jar:4.3.17.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-8.5.31.jar:8.5.31]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.31.jar:8.5.31]
    at org.springframework.web.filter.HttpPutFormContentFilter.doFilterInternal(HttpPutFormContentFilter.java:109) ~[spring-web-4.3.17.RELEASE.jar:4.3.17.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-4.3.17.RELEASE.jar:4.3.17.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-8.5.31.jar:8.5.31]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.31.jar:8.5.31]
    at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:81) ~[spring-web-4.3.17.RELEASE.jar:4.3.17.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-4.3.17.RELEASE.jar:4.3.17.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-8.5.31.jar:8.5.31]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.31.jar:8.5.31]
    at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:197) ~[spring-web-4.3.17.RELEASE.jar:4.3.17.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-4.3.17.RELEASE.jar:4.3.17.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-8.5.31.jar:8.5.31]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.31.jar:8.5.31]
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:198) ~[tomcat-embed-core-8.5.31.jar:8.5.31]
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96) [tomcat-embed-core-8.5.31.jar:8.5.31]
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:496) [tomcat-embed-core-8.5.31.jar:8.5.31]
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140) [tomcat-embed-core-8.5.31.jar:8.5.31]
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:81) [tomcat-embed-core-8.5.31.jar:8.5.31]
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87) [tomcat-embed-core-8.5.31.jar:8.5.31]
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:342) [tomcat-embed-core-8.5.31.jar:8.5.31]
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:803) [tomcat-embed-core-8.5.31.jar:8.5.31]
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66) [tomcat-embed-core-8.5.31.jar:8.5.31]
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:790) [tomcat-embed-core-8.5.31.jar:8.5.31]
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1468) [tomcat-embed-core-8.5.31.jar:8.5.31]
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) [tomcat-embed-core-8.5.31.jar:8.5.31]
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) [na:1.8.0_144]
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) [na:1.8.0_144]
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) [tomcat-embed-core-8.5.31.jar:8.5.31]
    at java.lang.Thread.run(Thread.java:748) [na:1.8.0_144]


text:
Q: Android: How to logout user after 24 hours? One way I thought was to check the timestamp from the last time it was run to the current timestamp and determine if the user needs to be logged out (from the app's member section). Another developer suggested creating Android services. Would like to know a good approach to automatically forcefully logout user after 24 hours since last time they ran it.

A: To automatically forcefully log out user after 24 hrs you need to save the logout time on server, check every time the app starts and log him/her out. This is because the app may be uninstalled and then all the saved time stamp data will be lost.
Note that it is quite OK to save the time stamp and restart the login process when the app get uninstalled and re-installed. Many apps do this. But if this is a financial app then it is a good idea to control logout from server, it gives you more flexibility and control.


text:
Q: Probability distribution in data mining In many data mining/machine learning books and articles, nobody is mentioning probability distribution of input data and relation between data mining models and distributions.
Does it mean, that it is not important, when applying, for example, a random forest classifier?
When building data mining models, should one consider probability distribution? If yes, how?
EDIT
By data mining models i mean more like Machine Learning algorithms, as certain data mining models can make assumption about distributioun as Underminer mentioned

A: In general, machine learning classifiers (e.g. random forest) are nonparametric models; that is, they do not make underlying assumptions about the probability distributions of variables being assessed.
Instead, most machine learning classifiers (e.g. random forest, neural nets, SVM, k-nearest neighbor) have algorithmic parameters that are tuned in the training phase, but they don't rely on underlying probability distribution assumptions of the data.
That being said, the term 'data mining models' is very vague, so the above answer is directed at models like you specifically mention in your question, namely the random forest model.  There are many parametric statistical models that can be used for classification or other aspects of data mining as well (e.g. logistic regression), but it seems you are referring more towards the algorithmic machine learning approaches.


text:
Q: Item height relative to actual row height with * WPF XAML I have the following XAML
<Window x:Class="WpfApplication3.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:wpfApplication3="clr-namespace:WpfApplication3"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="60*"/>
            <RowDefinition Height="147*"/>
            <RowDefinition Height="112*"/>
        </Grid.RowDefinitions>
        <TabControl Grid.Row="1">
            <TabItem Header="Match Bets" >

                <StackPanel Margin="15" Orientation="Vertical" Height="Auto" Width="Auto" >
                    <Label Content="My Header"/>
                    <DataGrid
                        Height="Auto" VerticalAlignment="Stretch" HorizontalAlignment="Stretch" Width="Auto">
                        <DataGrid.Columns>
                            <DataGridTextColumn  IsReadOnly="False" Binding="{Binding Subject}" Header="Original A"  Width="Auto" />
                            <DataGridTextColumn  IsReadOnly="False" Binding="{Binding PriceOriginalSelectionB}" Header="Original B"  Width="Auto" />
                            <DataGridTextColumn  IsReadOnly="False" Binding="{Binding PriceDerivedSelectionA}" Header="Derived A"  Width="Auto" />
                            <DataGridTextColumn  IsReadOnly="False" Binding="{Binding PriceDerivedSelectionB}" Header="Derived B"  Width="Auto" />
                        </DataGrid.Columns>

                        <wpfApplication3:Dummy Subject="Subject 1" Body="Body 1" />
                        <wpfApplication3:Dummy Subject="Subject 2" Body="Body 2" />
                        <wpfApplication3:Dummy Subject="Subject 2" Body="Body 2" />
                        <wpfApplication3:Dummy Subject="Subject 2" Body="Body 2" />
                        <wpfApplication3:Dummy Subject="Subject 2" Body="Body 2" />
                        <wpfApplication3:Dummy Subject="Subject 2" Body="Body 2" />

                    </DataGrid>

                </StackPanel>

            </TabItem>

        </TabControl>
        <DataGrid HorizontalAlignment="Stretch" Margin="5" Grid.Row="2" VerticalAlignment="Stretch" Height="Auto" Width="Auto" />

    </Grid>
</Window>

I want my datagrid (which is inside a stackpanel) only to grow to below the size of the row it is inside, but the stack panel seems to allow it to grow to any size it wants. Is there anyway without explicitly setting the height of the stack panel that I can do this. Or can I set the height of the stackpanel to be slightly smaller that the star * height of the row.
If I remove the stackpanel that the datagrid is inside this works fine, but I need the stackpanel to add other things above and below the datagrid.

A: Do not set the Height of the DataGrid, but instead set the VerticalAlign to Stretch, and use a 5px top/bottom margin.

A: Use a grid.  StackPanel behaves differently and Grid should allow "growing" as you want it.


text:
Q: Google Apps, SPF, softfail problem (validates with validation tools, but still softfails otherwise) I guess this is probably a commonly asked and boring question but I'm really at a loss and I don't know what else to do. This might be a duplicate of other questions, but none of the solutions worked for me. I've Googled around and read just about anything I could find but I'm still puzzled as to why it doesn't work.
The gist of my problem is that I have set-up Google Apps for a client of mine with the domain fintan.dk. Everthing works just excellent, except emails sent from *@fintan.dk (either with the Gmail web-interface or desktop client) to a non-Google Apps email gets a softfail (I have sent to my University email, an email hosted at MediaTemple and even Hotmail). The emails gets a pass when sent to a Google Apps or Gmail address though... (All emails from that domain are sent via email clients.)
So this is what I have done so far:

*

*I've added the SPF record Google recommended (v=spf1 include:_spf.google.com ~all), waited several days hoping it would a DNS update delay problem. Now, three days later there is no change.

*I have verified the settings in the desktop clients several times.

*I have validated the records with validation tools like the SPF Query Tool, spf-test@openspf.org and check-auth@verifier.port25.com. All of them validate and gives a pass, saying there shouldn't be a problem, but strangely there still is.

So, I really don't know what else to do. Any help is very much appreciated.
Thank you in advance!
--
Here are som headers for an email I sent from a *@fintan.dk address to a non-Google Apps/-Gmail address with email hosted at MediaTemple, **@newzoo.no.
Delivered-To: ***@***
Received: by 10.204.113.141 with SMTP id a13cs215458bkq;
        Mon, 7 Jun 2010 14:27:23 -0700 (PDT)
Received: by 10.204.83.228 with SMTP id g36mr347934bkl.133.1275946041770;
        Mon, 07 Jun 2010 14:27:21 -0700 (PDT)
Received-SPF: softfail (google.com: best guess record for domain of transitioning **@fintan.dk does not designate **.**.***.*** as permitted sender) client-ip=**.**.***.***;
Received: by 10.188.26.13 with POP3 id 13mf159579bwz.53;
        Mon, 07 Jun 2010 14:27:21 -0700 (PDT)
X-Gmail-Fetch-Info: **@newzoo.no 3 mail.newzoo.no 110 **@newzoo.no
Return-path: <**@fintan.dk>
Envelope-to: **@newzoo.no
Delivery-date: Mon, 07 Jun 2010 14:27:17 -0700
Received: from mail-ew0-f224.google.com ([209.85.219.224]:44843)
    by cl29.gs01.gridserver.com with esmtp (Exim 4.63)
    (envelope-from <**@fintan.dk>)
    id 1OLjqk-0007P1-RP
    for mc@newzoo.no; Mon, 07 Jun 2010 14:27:17 -0700
Received: by ewy24 with SMTP id 24so1953534ewy.34
        for <**@newzoo.no>; Mon, 07 Jun 2010 14:27:13 -0700 (PDT)
Received: by 10.213.22.14 with SMTP id l14mr11377870ebb.55.1275946032661;
        Mon, 07 Jun 2010 14:27:12 -0700 (PDT)
Received: from [192.168.1.4] (cm-84.215.178.166.getinternet.no [84.215.178.166])
        by mx.google.com with ESMTPS id 13sm2910690ewy.5.2010.06.07.14.27.11
        (version=TLSv1/SSLv3 cipher=RC4-MD5);
        Mon, 07 Jun 2010 14:27:11 -0700 (PDT)
From: Moquan Chen <**@fintan.dk>
Content-Type: multipart/alternative; boundary=Apple-Mail-16--861396158
Date: Mon, 7 Jun 2010 23:27:10 +0200
References: <****5c90912060401w1a16edc8x88706159cb35caa0@mail.gmail.com>
To: **@newzoo.no
Message-Id: <F0B66FDB-42A1-4114-80A8-A5AAD6FD7C3A@fintan.dk>
Mime-Version: 1.0 (Apple Message framework v1075.2)
X-Mailer: Apple Mail (2.1075.2)
X-Spam-Status: "score=1.0 tests=HTML_MESSAGE version=3.1.7"
X-Spam-Level: *

A: Try changing your record from v=spf1 include:_spf.google.com ~all to v=spf1 mx include:_spf.google.com ~all
Thats what my SPF record has (note the mx addition) it should work since google's servers are the MX servers for the domain.
Also if you need the server that hosts the fintan.dk website to send emails change the record to v=spf1 a mx include:_spf.google.com ~all

A: ~all means soft fail. If you want to specify a hard fail you need to use -all.
http://www.openspf.org/SPF_Record_Syntax


text:
Q: How to change the color of the Text and a SVG on hover in React? So I have the following React component which acts as a Navbar in my case. Whenever the user hovers over the navbar item it must change its color to whatever is specified. Currently, the Navbar item consists of 2 items: The Icon(SVG) and a text describing what it is.
So hovering over the component must change the color of both the text and the icon.
Here is the current code:
import { ReactComponent as DashboardIcon } from "../assets/ico_dashboard.svg";

          <DashboardIcon className="navLinkHolder" height={50} />
          Dashboard

The CSS:
a:hover {
  color: yellow;
}

Using this code is working on the Text inside the  which is the Dashboard but the SVG is not changing its color. How do I change the color of the SVG? I tried fill: yellow too but it did not work

A: EDIT : this solution works only on in-line svg, because the browser is able to add the fill property also on svg's childs. It's not a basic text so the a is not able to fill them.
(you can just open the svg file with a text editor and copy its content)
You should apply the :hover pseudo-class on the svg class also!
navLinkHolder:hover {
  fill: yellow;
}

EXAMPLE:

.mylink:hover {
  fill: orange;
  color: orange;
 }

    my link
    <svg width="24" height="24" class="mysvg">
      <path d="M4,11V13H16L10.5,18.5L11.92,19.92L19.84,12L11.92,4.08L10.5,5.5L16,11H4Z"></path>
    </svg>

You can separate the style too, but like this the svg and the text will behave the same way in the same time.

A: you can add to 'path' in the SVG the 'className', so use it in parent CSS hover:
<svg width="24" height="24">
      <path className="myIcon" d="M4,11V13H16L10.5,18.5L11.92,19.92L19.84,12L11.92,4.08L10.5,5.5L16,11H4Z"></path>
</svg>

import { ReactComponent as DashboardIcon } from "../assets/ico_dashboard.svg";

          <DashboardIcon height={50} />
          Dashboard

CSS:
a:hover .myIcon{
  fill: red;
}

or:
.divHover:hover .myIcon{
   fill: red;
}


text:
Q: Query on Jython with Web Start I am looking at creating a jython application and deploying it as a java web start.
My query is related to a concern that for web start deployment, we have to distribute the jython standard jar package also along with our application jar.
From all the web resources , this is what I hear. And the concern is that this will make the download time of the application significantly large as jython jar file is nearly 9 Mb.
If anyone of you has deployed a jython app through web start, can you clarify if we need to bundle the jython jar package along with our application files or only the application files in a standalone jar file ( this solves my problem)
Regards
Shyam

A: OK , as I figured out...I have to package the jython jar also along with the application jar to make it work.
The reason is that, the application jar consists of python code which the client JVM has no way to understand unless it uses the jython jar package.
As I hear jython has no support currently to convert python code to java classes. Unless this is possible , the jython jar package has to be included.


text:
Q: show that the eigenspace corresponding to every $\lambda_n$ is one dimensional Theorem(*): Let $p\in C^1(\bar I)$ with $I=(0,1)$ and $p\ge\alpha>0$ on $I$;let $q\in C(\bar I).$ Then there exits a sequence $(\lambda_n)$ of real numbers and a Hilbert basis $(e_n)$ of $L^2(I)$ such that $e_n\in C^2(\bar I)$ for any n and $$-(pe'_n)'+qe_n=\lambda_ne_n\\e_n(0)=e_n(0)=0$$ on I. Furthermore, we have $\lambda_n\to \infty$ as $n\to \infty$. (we say that $\lambda_n$ are the eigenvalues of the differential operator $Au=-(pu')'+qu$ with Dirichlet boundary condition and that $(e_n)$ are the associated eigenfunctions. ) This theorem is from therem 8.22 in the book called functional analysis,Sobolev Spaces and Partial Differential equations written by Haim Brezis
Question:
Assume we have the regular Sturm-Liouville eigenvalue problem$$L\phi:=(p(x)\phi'(x))'+q(x)\phi(x)=\lambda\phi(x) on [a,b],\\\phi(a)=0,\phi(b)=0,$$where we have $p\in C^1[a,b],p>=\alpha>0,q\in C^0[a,b].$ Look at the theorem(*),Show that as for eigenvalue $\lambda_n$,its corresponding engienspace is one-dimensional.
This problem has a hint:if $\phi_1 $and $\phi_2$ are two eigenfunctions for the same eignevalue then ${d\over dx}(p(\phi_1' \phi_2-\phi_1 \phi_2'))=0$
My thought: actually, I already proved ${d\over dx}(p(\phi_1' \phi_2-\phi_1 \phi_2'))=0$(just based on definitions above). however, how can I prove $\lambda_n$'s eigenspace only has one dimension? This is where I am confused about.

A: Suppose you have two solutions $\phi_1,\phi_2$ of the eigenvalue problem. Then $\phi_1(a)=0=\phi_2(a)$ and $\phi_1(b)=0=\phi_2(b)$. The Wronksian result gives
\begin{align}
         &p(x)\{\phi_1(x)\phi_2'(x)-\phi_1'(x)\phi_2(x)\}\\
      = &p(a)\{\phi_1(a)\phi_2'(a)-\phi_1'(a)\phi_2(a)\}=0,\;\; x\in[a,b].
\end{align}
So,
$$
      \frac{d}{dx}\left(\frac{\phi_2}{\phi_1}\right)=0.
$$
You have to deal with the special cases where $\phi_1$ vanishes in the interior of $(a,b)$, but you can see that the left-most zero of $\phi_1$ inside $(a,b)$ must also be a zero of $\phi_2$ because $\phi_2/\phi_1$ is constant between $a$ and that first $0$, if any.


text:
Q: After reinstalling windows Outlook is not syncing folders other than inbox Background
On my outlook panel I had the following folders:

*

*The default Folders: Inbox, Sent, Draft etc

*Personal / Custom created folders: Ex. "Sustenance", "Reference", "Too Long Read Later" etc.

I had a lot of rules setup to sort mails into these folders.. Until I had to reinstall Windows > Reinstall Office 2013.
The Problem
After reinstall Outlook is syncing emails. But it is not creating these folders automatically. I'm guessing that these folders must have been created in my Profile on the server.
Question
How can I get Outlook to create these folders again? When I try to sync it only syncs my Inbox folder.

A: I'm assuming this is an exchange account as you refer to a server? It should recreate the folders automatically - check Mail in control panel, select Email accounts and then double click the account in question. There is a slider that sets what mail to keep offline - slide it all the way to the right and click Next and finish. Reopen Outlook and see. If still not, go back there and off tick the Use Cached Exchange box, finish it and reopen Outlook again. If the latter shows the folders, then you need to go delete your OST and SRS files in your profile folder, re-enable Cached mode and reopen Outlook.

A: You have IMAP folder. There should be an option to view/edit Subscribed Folders.

*

*In Mail, in the Navigation Pane, right-click the top folder for your IMAP account.

*Click IMAP Folders.

*Click Query.

*Click a folder, and then click
Subscribe or Unsubscribe.

Source: Choose which IMAP folders appear


text:
Q: Repeater html values always taking last item's value Hi I am using asp repeater for list item's speciality textboxes and a div for giving alert textbox type (numeric or string etc)  Here is html;
      <asp:Repeater ID="rptProperties" runat="server" DataSourceID="dsProperties" OnItemDataBound="rptProperties_ItemDataBound">
                <ItemTemplate>

<%# Eval("ad_en")%>

                        <div class="form_content" id="fk_<%# Eval("id")%>">

                            <asp:HiddenField runat="server" ID="hdnPropertyID" Value='<%# Eval("id") %>' />
                            <asp:TextBox runat="server" ID="txtProperty"></asp:TextBox>

                        <%= labelType %>

                                <asp:DropDownList runat="server" ID="ddlProperty" CssClass="data_select">
                                    <asp:ListItem>Select</asp:ListItem>
                                </asp:DropDownList>

                </ItemTemplate>
            </asp:Repeater>

And here is code behind ;
                if (id!=130)
                {
                    txtProperty.Attributes.Add("Class", "data_input");
                    labelType = GetLocalResourceObject("stringType").ToString();

                }

                else
                {
                    labelType = GetLocalResourceObject("intType").ToString();

                }

Even tho code trigger if and else both, all repeater textboxes take "intType" value which is last item's  value. But ;
   txtProperty.Attributes.Add("Class", "data_input");

line works fine as I want. Only "labelType" variable problem for me. Thank You

A: Sorry, but this wouldn't work.
<% %> code blocks are compiled run time after c# code run through. So you change labelType and after that asp code blocks runs and label type is the last thing it changed to.
For it to work you can change the way you implement it, maybe writing that code-behind block to asp block.

   <%=   Convert.ToInt32(Eval("id")) != 130 ? GetLocalResourceObject("stringType").ToString() : GetLocalResourceObject("intType").ToString() %>

and changing code-behind to just
if (id!=130)
{
    txtProperty.Attributes.Add("Class", "data_input");
}


text:
Q: How to get the stack trace when installing an app with adb install? Is it possible to view the stacktrace (as you get when you install via the marketplace) when you install an app via adb install command?

A: You have to set the environment variable ADB_TRACE to the value 'all'.
For Linux it is this command:
export ADB_TRACE=all

The traces from the ADB front-end will be shown on the screen, and the traces from the server will be saved in /tmp/adb.log.


text:
Q: No export options for Modeling Project on Visual Studio 2012 We have created a new Modeling Project on Visual Studio 2012 to have all of the class and sequence diagrams, however there is no option to export the diagrams to images like the diagrams created via "View class diagram" option in a Class Library.
Why? How can I export the diagrams from this project template?

A: I've been trying to find a way to export the diagrams and now I realized that selecting the elements of the diagram, copying and pasting to another application (like MSPaint or Word) does work.
However, the header of the diagram (with the name of the class diagram) is ignored.


text:
Q: Python 3 built-in functions and classes When I am creating a list using below statement
a = list('jane')
Am I calling Python's built-in list function or instantiating list class.
My understanding is we are instantiating list class by passing 'jane' as argument.
However, the Python's documentation https://docs.python.org/3/library/functions.html says list() is built-in function.

A: Your question is answered by the very documentation page you mention:

class list([iterable])
  Rather than being a function, list is actually a mutable sequence type, as documented in Lists and Sequence Types — list, tuple, range.

In Python, both classes and functions are callable, so in practice, you can treat them alike.

A: The docs explicitly say:

class list([iterable])
Rather than being a function, list is actually a mutable sequence type

You can easily check that:
>>> type(list)
type

if it was a function, function would be the output provided by using type.
You're instantiating a list object the same way you'd do if you created your own class and called it. type's __call__ is essentially getting invoked and sets up your instance so, though they aren't a function per se, they are callable.

The fact that they are listed in that specific section is probably for convenience, it might be confusing but reading the description of it is supposed to disambiguate this.

A: You are instantiating a list.

class list([iterable])
  Rather than being a function, list is actually a mutable sequence type, as documented in Lists and Sequence Types — list, tuple, range.


text:
Q: Auto Serial no in my lost and found sheet I have a sheet in which serial format is like this 24/08/2017 basically serial no is 24 , is it possible to get next serial no which is 25/08/2017 by using formula

A: As mentioned in comment, if the serial number is irrespective of date,
you can do the following,
with s as the serial number,
and / differentiates the number to increment and the rest of the serial number, you can use string replace!
>>> s
'100/08/2017'
>>> s.replace(s.split('/')[0],str(int(s.split('/')[0])+1),1)
'101/08/2017'

If the serial number is in date format, you can use datetime module of python,
>>> from datetime import datetime,timedelta
>>> #serial_no = datetime.now().strftime('%d/%m/%Y')
>>> serial_no = "16/08/2017"
>>> print serial_no
16/08/2017
>>> print (datetime.strptime(serial_no, "%d/%m/%Y").date()+timedelta(days=1)).strftime('%d/%m/%Y')
17/08/2017


text:
Q: Issue with the output objects In one script, i use var_dump() to output the objects:
foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS'][$this->extKey.'/'.$this->scriptRelPath] as $classRef) {
                $hookObj = t3lib_div::getUserObj($classRef);
                var_dump($hookObj);

The result is:
object(tx_job_dagoupost)#73 (3) { ["extKey"]=> string(3) "job" ["prefixId"]=> string(10) "tx_job_pi1" ["scriptRelPath"]=> string(32) "hooks/class.tx_job_dagoupost.php" }
object(tx_christianvolunteer_dagoupost)#79 (2) { ["extKey"]=> string(19) "christian_volunteer" ["scriptRelPath"]=> string(47) "hooks/class.tx_christianvolunteer_dagoupost.php" }
object(tx_watermark_dagoupost)#73 (2) { ["extKey"]=> string(9) "watermark" ["scriptRelPath"]=> string(38) "hooks/class.tx_watermark_dagoupost.php" }

Question:

*

*what does #73 and #79 mean?

*object(tx_job_dagoupost)#73 and object(tx_watermark_dagoupost)#73 are different objects, but they have same id #73, why?

A: *

*As explained here sign # is PHP internal identifier for object.

*Same identifiers for different objects means that your first object (tx_job_dagoupost) was transient (not assigned to any variable or variable was unset) and PHP used same identifier for next object.


text:
Q: Programatically check if object parameter is default(object.GetType()) in C# I'm writing an ObjectHasValueConverter : IValueConverter for WPF.
The relevant function is Convert(object value, ...).  I want essentially want to do
return value != default(value.GetType())

Unfortunately, it seems default is a compile-time keyword and IValueConverter doesn't have a generic equivalent, so I can't just do default(T).
Obviously if value is an instance of a class or an array I can just check for null.
if (value.GetType().IsValueType | value.GetType().IsArray)
{
    return value != null;
}

I have a special case for strings, returning !string.IsNullOrWhitespace(value).  For structs and other primitives, I'm hoping there's something cleaner than
if (value is int | value is short | value is long | ...)
{
    return (int)value != 0;
}

if (value is float | value is double)
{
    return (double)value != 0;
}

if (value is bool)
{
    return !(bool)value;
}
...

I've scoured SO before writing this, but all the answers I found had to do with reflection and getting the members of a value type.  I didn't find anything relating to types that are put on the stack.


text:
Q: Handle command-not-found without PackageKit I have uninstall PackageKit on Fedora, because I didn't need the bloat & race-conditions with the command-line.
Since then, command-not-found fails with the following:
❯ foo
bash: foo: command not found...
Failed to search for file: GDBus.Error:org.freedesktop.DBus.Error.NameHasNoOwner: Could not activate remote peer.
# because...
❯ dbus-send --system --print-reply  --dest=org.freedesktop.PackageKit  \
    /org/freedesktop/PackageKit org.freedesktop.DBus.Properties.Get  \
    string:'org.freedesktop.PackageKit' string:'BackendName'

Error org.freedesktop.DBus.Error.NameHasNoOwner: Could not activate remote peer.

How can I retain command-not-found functionality without PackageKit? It seems dnf should be able to handle that on its own?
Versions:

*

*Fedora 31 beta + gnome-shell 3.34.0 + zsh 5.7.1

*PackageKit-command-not-found-1.1.12-11.fc31.x86_64.rpm

A: Ugh, this has bugged me for years.   Like a number of other people, I HATE PackageKit and have gone out of my way to shut it down. I've also found you can't just uninstall it without significant ramifications. The best you can do is disable and mask it's systemctl service which keeps it from suddenly downloading copious amounts of packages onto your already full hard-drive.  Rather I rely solely on command-line DNF to take care of any package and system upgrades.
So, I've generally just lived with this "annoying feature" each time I fat-finger a command such as 'mkae' (that's "make" for those that can type correctly).
Not being one to usually just give up and live with an annoyance like this, I finally took the time today to dig into it...  I had realized that this has to be a feature coming from bash. But, I couldn't fathom that Fedora would tweak bash that much for PackageKit.  But, I also couldn't really find any results searching on this topic (though I did find lots of other people who also seem annoyed with PackageKit, so apparently I am not alone).  I was momentarily excited when I found this post, but only to quickly become disappointed by the lack of any answer!
So, I dug into it.   I do know bash fairly well and decided to start by just searching the man page.  And that ultimately led to this simple answer...
It turns out bash (and some other shells like zsh) have a command_not_found_handle function that can be called when an arbitrary command is not found.   Well, it turns out that PackageKit installs a file under /etc/profile.d which defines this function.  It's /etc/profile.d/PackageKit.sh
Looking at the version of the function in there yields a couple of different ways it could be disabled:

*

*You could just remove the /etc/profile.d/PackageKit.sh  (though it likely would show back up on a package update).

*Remove executable permission from /usr/libexec/pk-command-not-found (again, probably get reverted on a package update).

*Remove (or rename) the directory /usr/libexec/packagekitd (and again, probably get re-installed on a package update).

*Add unset -f command_not_found_handle to your local .bashrc file

*Lastly, define your own super awesome, "custom" function for command_not_found_handle in your local .bashrc file (like mentioned in the comment above). I had started down that path, but then decided good old "command not found" was probably best...

Since, I've had so many issues when I tried to fully remove PackageKit, I've just had to leave it in place and keep it disabled & masked.  As a result, I took the simplest approach of just unsetting the function in my local .bashrc and have now been very pleased with no longer seeing the stupid and obnoxious GDBus.Error:org.freedesktop.DBus.Error.NameHasNoOwner error.
HTH!


text:
Q: lsblk doesn't show mmcblk0, mmcblk2 exists I am trying to install devsus on an ASUS C201 laptop. I have successfully installed on an external USB, but am trying to install to the internal laptop memory. The instructions direct me to dd the 16GB image onto mmcblk0, however lsblk shows only an mmcblk2, mmcblk2boot0, mmcblk2boot1, and mmcblk2rpmb. I have dd the image onto mmcblk2, which has definitely done something as it no longer boots into chromeOS when I boot from the internal media, however it doesn't boot devsus and instead puts me in a recovery mode which requires external media for recovery.

*

*Should I be looking for an mmcblk0, or is mmcblk2 the correct target?

*Given that the external USB does boot, is there a way to dd that onto the internal memory, and then perhaps re-partition it to use the full internal disk?


text:
Q: How to supply hiveconf variable from hive oozie action I want to supply variable as hiveconf namespace from my hive-oozie action, how to do that?

<action name="setupAct">
  <hive xmlns="uri:oozie:hive-action:0.2">
    <job-tracker>maprfs:///</job-tracker>
    <name-node>maprfs:///</name-node>
    <script>
      XYZ.hql
    </script>
    <!--how to add variable to hiveconf-->
    <param>DB_NAME=test</param>
  </hive>
  <ok to="ok" />
  <error to="error" />
</action>

The values inside param element are supplied as --hivevar namespace to hive.
Below is application log, the param element gets added as hivevar:

------------------------
  DB_NAME=test
------------------------
Hive command arguments :
      --hivevar
        DB_NAME=test
        -f
         test.hql

A: For hiveconf in Oozie, Use the configuration element.
<hive xmlns="uri:oozie:hive-action:0.2">
    <job-tracker>maprfs:///</job-tracker>
    <name-node>maprfs:///</name-node>
    <script>
      XYZ.hql
    </script>
    <!--how to add variable to hiveconf-->
    <configuration>
       <property>
          <name>hive.default.fileformat</name>
          <value>Parquet</value>
       </property>
    </configuration>
    <param>DB_NAME=test</param>
  </hive>


text:
Q: PHP: Get static method reference I want to get the reference of a static method from another static method in same class, but PHP interprets the two lines (see example code below) always as an access to a constant. Is it not possible to get a reference to static methods in PHP?
class foo
{
    public static function test()
    {
        self::bar();  // calling (not referencing) works
        $bar_reference = self::bar;  // Error: Undefined class constant 'bar'
    }

    public static function bar()
    {
        echo "hello";
    }
}

foo::test();
$bar_reference = foo::bar;  // Error: Undefined class constant

Just to clarify it again: I do NOT want to call the static method - I just want to get a reference to it.

A: You can create a callable like this:
class foo
{
    public static function test()
    {
        $bar_reference = array(__CLASS__, 'bar');
        // Call it
        $bar_reference();
    }

    public static function bar()
    {
        echo "hello";
    }
}

foo::test();
$bar_reference = foo::bar();


text:
Q: Do asp.net application variables pass by reference or value? I've discovered recently that when using the Session or Application objects within an ASP.net application, that it passes the values by reference.
This works great most of the time, but now I'm in a place where I truly need a copy of the data, and not a reference to it, since I will discard any changes to it when done processing.
I'm also aware of setting variables in the root of the application, effectively creating global application variables that have a bit better performance and eliminate all the casting craziness of the Session/Application objects.
Does anybody know if the application variables pass by reference or value? I can't seem to dig up any data on the topic and would like to eliminate the code I currently have to "copy" the data from the Application object into a new variable for processing.

A: This is not an ASP.NET phenomenon per se... it is inherent to the CLI in all of .NET framework. You should take a look at Jon Skeet's classic article on Parameter passing.
Assuming you are dealing with reference types, if you want to clone an object rather than simply copying a reference to the object, you will need to manually clone it. Here's a good article that explains how to deep copy an object and why the MemberwiseClone method creates only a shallow copy of the object.

A: Actually, what happens by default (assuming you have a reference type rather than a value type) is that it passes a copy of the reference.
So you have a different variable but it's pointing at the same object.

A: An "Application" variable is just a regular member variable. It works just like any other variable, it's only it's scope that is larger than most.
If the value of the variable is copied or not depends on whether the variable is a value type or not.
If it's a value type, for example int, the value is always copied.
If it's a reference type, for example a List<int> you get a copy of the reference to the object. The object itself is not copied.
So, if what you need to copy is a reference type, you have to explicitly create the copy.


text:
Q: What's wrong with my code that this error occurs?
Error: type'_InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'List<dynamic>' in type cast

I just want to show the data on the screen, very simple, but it is not working in any way. the API is returning me the necessary data correctly because show me on the console but do not know how to call in View.
My Model:
class ProdutosModel {
  int codigo;
  String codigoBarras;
  String descricao;
  double preco;

  ProdutosModel({
    this.codigo,
    this.codigoBarras,
    this.descricao,
    this.preco,
  });

  Map<String, dynamic> toMap() {
    return {
      'codigo': codigo,
      'codigoBarras': codigoBarras,
      'descricao': descricao,
      'preco': preco,
    };
  }

  factory ProdutosModel.fromMap(Map<String, dynamic> map) {
    return ProdutosModel(
      codigo: map['codigo'],
      codigoBarras: map['codigoBarras'],
      descricao: map['descricao'],
      preco: map['preco'],
    );
  }

  String toJson() => json.encode(toMap());

  factory ProdutosModel.fromJson(String source) =>
      ProdutosModel.fromMap(json.decode(source));
}

My controller:
Future getterProducts() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    final token = prefs.getString('token');

    try {
      final response = await Dio().get(
        'CONFIDENTIAL#CONFIDENTIAL#CONFIDENTIAL#',
        options: Options(
          headers: {'Token': token},
        ),
      );

      print(response.data);

      if (response.statusCode == 200 || response.statusCode == 201) {
        var getProducts = response.data as List;
        var listProducts =
            getProducts.map((i) => ProdutosModel.fromJson(i)).toList();
        return listProducts;
      }
    } on DioError catch (e) {
      print(e);
    }
  }

And my view:
class HomeView extends GetView<HomeController> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: PreferredSize(
        preferredSize: Size.fromHeight(150.0),
        child: AppBar(
          elevation: 10,
          flexibleSpace: Container(
            decoration: BoxDecoration(
              gradient: LinearGradient(
                colors: [
                  Color(0xff38EF7D),
                  Color(0xff11998E),
                ],
              ),
            ),
          ),
          title: Text(''),
          centerTitle: true,
        ),
      ),
      body: FutureBuilder(
        future: controller.listProducts,
        builder: (context, snapshot) {
          if (snapshot.hasData) {
            return ListView.builder(
                itemCount: snapshot.data.length,
                itemBuilder: (context, index) {

                  var prod = (snapshot.data as List<ProdutosModel>)[index];
                  return ListTile(
                    title: Text('${prod.descricao}'),
                  );
                },
                /* itemCount: (snapshot.data as List<ProdutosModel>).length */);
          } else if (snapshot.hasError) {
            return Center(child: Text('${snapshot.error}'));
          }
          return Center(
            child:
                CircularProgressIndicator(backgroundColor: Colors.cyanAccent),
          );
        },
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          //
        },
        child: Icon(
          Icons.refresh,
          color: Colors.green[700],
        ),
        backgroundColor: Colors.greenAccent,
      ),
    );
  }
}

A: Change fromJson to fromMap in MyController
var listProducts =
            getProducts.map((i) => ProdutosModel.fromMap(i)).toList();

A: You might want to check if response.data is indeed a list that you are receiving from the Api, and not a json object with a list inside. If not a list, then
var getProducts = response.data as List;
This type cast wont work and will throw an error.
You can go to https://app.quicktype.io/ and just copy paste the entire response. Choose dart as the language and you'll get the proper serialization.
Let me know if that helped. Otherwise provide the Api json response here.

A: The error occurs from this line:
var getProducts = response.data as List;
This is because the API is returning a Map instead of a list, hence the error

type'_InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'List' in type cast

Try accessing the data through the correct property of response.data, for example response.data['data']
Quick note: In your UI code block, it'd be better to define the type like this for the type-check to work at the bloc level:
//... other lines

// Define the type of data here
FutureBuilder<List<ProdutosModel>>(

        // Since I'm getting this method from your code, I'm using it here
        future: controller.getterProducts(),

        builder: (context, snapshot) {
          if (snapshot.hasData) {
            return ListView.builder(
                itemCount: snapshot.data.length,
                itemBuilder: (context, index) {

                  // We can use `snapshot.data` right away without type-cast here
                  var prod = snapshot.data[index];
                  return ListTile(
                    title: Text('${prod.descricao}'),
                  );
                },
                /* itemCount: (snapshot.data as List<ProdutosModel>).length */);
          }

//... other lines


text:
Q: MySQL subquery returning more than one result Does someone figures out a way to make this code works even when MySQL subquery returns more than one result? It is working fine when the user has no event related to him, or when the user has one event related to him, but when a user is related to more than one event, the subquery returns more than one result and than the code gets nothing to work with.
$stmt = $db->prepare("SELECT * FROM events WHERE
                  id_events = ( SELECT id_events FROM relationship_events WHERE id_user = ?)");
$stmt->bindParam(1, $idUser);
$stmt->execute();

$rawTimeStamps = $stmt->fetchAll(PDO::FETCH_ASSOC);
$cleanDateArray = array();

foreach ($rawTimeStamps as $t) {
$rawDate = $t['start'];
$rawDate = getdate($rawDate);
$cleanDate = mktime(0,0,0,$rawDate['mon'],$rawDate['mday'],$rawDate['year']);
$cleanDateArray[] = $cleanDate;
}

for($list_day = 1; $list_day <= $days_in_month; $list_day++):

$calendar.= '';
    $timestamp = mktime(0,0,0,$month,$list_day,$year);
    if (!empty($cleanDateArray) && in_array($timestamp, $cleanDateArray)) {

    $date = getdate($timestamp);
    $time_start = mktime(0,0,0,$date['mon'],$date['mday'],$date['year']);
    $time_end = mktime(23,59,59,$date['mon'],$date['mday'],$date['year']);
    $stmt = $db->prepare('SELECT title FROM events WHERE start BETWEEN ? AND ?');
    $stmt->bindParam(1,$time_start,PDO::PARAM_INT);
    $stmt->bindParam(2,$time_end,PDO::PARAM_INT);
    $stmt->execute();
    $events = $stmt->fetch(PDO::FETCH_ASSOC);

    $calendar.= '
'.$list_day.'

'.$events["title"].'
';
    } else {
    $calendar.= '
'.$list_day.'

';
    }

A: Query should be SELECT * FROM events WHERE id_events IN ( SELECT id_events FROM relationship_events WHERE id_user = ?).

A: There are two possible answers, depending on how you want it to work.
If you only want a single event, regardless if the user has 1 or more events, you can add LIMIT 1 in your subquery:
SELECT * FROM events
WHERE id_events = (
    SELECT id_events FROM relationship_events WHERE id_user = ? LIMIT 1
)

On the other hand, if you want all events assigned to the user, you can use an IN clause:
SELECT * FROM events
WHERE id_events IN (
    SELECT id_events FROM relationship_events WHERE id_user = ?
)

Both of these should also work fine if the user is assigned to no events.


text:
Q: Issue with for each loop and arrays I am getting java.lang.ArrayIndexOutOfBoundsException: 5 when running this program.
public class TestArray {
    public static void main(String[] args) {
            int[] someArray = new int[5];

            someArray[0] = 5;
            someArray[1] = 10;
            someArray[2] = 15;
            someArray[3] = 20;
            someArray[4] = 25;

            System.out.println("Array length = " + someArray.length);
            for (int i : someArray) {
                    System.out.println("Element at index " + i + ": " + someArray[i]);
            }
    }

}
Shouldn't the loop exit when i is greater than or equal to the length of the array which would be 5 in this case?

A: You are iterating over array values itself not the indexes. Use just i not someArray[i]
Or change your loop to
for (int i=0; i<someArray.length; i++)

Changing loop is better in this case based upon what you are trying to achieve there


text:
Q: Fire an event automatically after barcode scanner input I have a textbox on an asp.net page. I use a barcode scanner to get the barcode number into that textbox. I need to then automaticaly fire an event directly after the text box recieves that input. the only event that is exposed is the TextChanged event which doesnt achieve what i need. I am using c# for the code behind.
Regards

A: Use TextChanged event with AutoPostBack=true.
Also ensure that your scanner sends a carriage return after scanning(normally with scanning a code from the manual).