text:
Q: Abstracting UIViewController like Cocoa ones EDIT: Is there someone that have some useful links about this topic? I mean good practices for writing reusable code and "abstraction"?
tl;dr - Read this comment Abstracting UIViewController like Cocoa ones
I have 3 UITableViewController:

*

*CategoriesViewController

*RecipesViewController

*IngredientsViewController
They're ordered hierarchically. Below an example of the hierarchy:

*

*Dessert (category)

*

*Brownie (recipe)

*

*Milk (ingredient)

*Chocolate (ingredient)

*Butter (ingredient)

Each one of these has similar functionalities with the others.
For example they all have sorting (moving rows), deleting, adding (presenting a modal view) etc.
Currently I've repeated all the code for every view controller customizing the parts that are related to each one. For example they all have an instance variable like this:
CategoriesViewController.m:
@implementation CategoriesViewController {
    NSMutableArray *categories;
}

RecipesViewController.m:
@implementation RecipesViewController {
    NSMutableArray *recipes;
}

IngredientsViewController.m:
@implementation IngredientsViewController {
    NSMutableArray *ingredients;
}

Because I think there's a better way to organize this view controller I've tried to create a skeleton of MyListViewController.h:
@interface MyListViewController : UITableViewController

@property (nonatomic, strong) NSMutableArray *list;

@end

MyListViewController.m:
@implementation MyListViewController

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [_list count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"ListCell"];

    id currentObject = [_list objectAtIndex:indexPath.row];
    cell.textLabel.text = [currentObject valueForKey:@"name"];

    return cell;
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // get item to delete
        id object = [_list objectAtIndex:indexPath.row];

        // remove it from list
        [_list removeObjectAtIndex:indexPath.row];

        // call callback
        [self didFinishDeletingItem:object];

        // delete row from tableview
        [self.tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
    }
}

- (void)didFinishDeletingItem:(id)item
{
}

In this way, once I've subclassed it I have only to assign list ivar to my data structure. And I can even override methods like didFinishDeletingItem: for customizing the behavior of each controller.
Because it's the first time that I would use best practices of writing and organizing code in this way I would love to know your opinions AND which are the best ways to abstract classes for reusing them following correctly the DRY principle.

A: From what I understand, you can do it in one of the following ways:

*

*Since you said your screens and behaviors are the same, you can use the same class MyListViewController and while creating the instance you can assign/populate the "list" array. That is the conventional approach

*Alternatively, if your classes (Categories, Recipes, Ingredients) vary slightly in behaviour, you can  sub-class them to MyListViewContrller.  You can do this in .h file like this:
@interface CategoriesViewController : MyListViewController{
In Xcode, you can select the super-class while you create new class file too.
Hope this helps in some way

A: (This should be comment, but I can't comment yet).
Don't do
    [_list count];
Use the property:
    [self.list count]
Only access the ivar in the accessors, or you will get bitten somewhere along the line. This also goes for the other places you are using _list instead of self.list.
Your skeleton class looks OK and this is good coding. Extending on this: if the only thing later in that is different in the actual data for the items, you can create different subclasses of UITableViewCell. The the MyListViewController can see what type of objects are contained in the NSArray (or you can set a flag on MyListViewCOntroller) and use the appropriate UITableViewCell based on that (and hence display the data correctly.)


text:
Q: What makes this deconstruct never be called I am trying to understand the memory leak.
I don't understand why below MyInt deconstruct in main is never called and a memory leak happens.
  class MyInt
    {
        int *_p;
    public:
        MyInt(int *p = NULL) { _p = p; }
        ~MyInt()
        {
            delete _p;
        }
        int &operator*() { return *_p; }
    };

int main()
{
    double t[] = {1.0, 2.0, 3.0, 4.0, 5.0};
    for (size_t i = 0; i < 5; ++i)
    {
        MyInt *en = new MyInt(new int(i));
        std::cout << **en << "/" << t[i] << " = " << **en / t[i] << std::endl;

    return 0;
}

A: Replace MyInt* en (a pointer to an object of type MyInt named en) with MyInt en (an object of type MyInt named en).
Or, explicitly call delete on your MyInt* pointer (albeit that would defeat the purpose of what you are trying to accomplish, I guess).

A:
I don't understand why below MyInt deconstruct in main is never called and a memory leak happens.

Because you use an allocated pointer to MyInt.
You have to call
delete en;

to de-allocate it.
Deleting en, the destructor of MyInt is called and the memory associated to _p is de-allocated.
Suggestion: you tagged C++11, so you can use smart pointers.
So, inside MyInt, use a smart pointer
#include <memory>

class MyInt
{
    std::unique_ptr<int> my_p;
public:
    MyInt (int *p = NULL) : my_p{p}
        { }

    // no explicit destructor required anymore

    int &operator*() { return *my_p; }
};

In main(), use a smart pointer as well:
#include <memory>

for (std::size_t i = 0; i < 5; ++i)
{
    std::unique_ptr<MyInt> en { new MyInt(new int(i)) };

    // use en and the content pointer

    // no more delete en required
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: UWP C# How to change Xaml UI rectangle fill outside of MainPage in async method? (Windows 10, UWP, C#, XAML)
I'm trying to change a rectangle's Fill from a class that is not the main method. I've sent my rectangle to the other class and from there I can set it's Fill. However, I need the Fill to change during an ongoing asynchronous method (rather, during a method that is being called by an on-going asynchronous method) but when I try that, I get an exception about threading:

The application called an interface that was marshalled for a
  different thread. (Exception from HRESULT: 0x8001010E
  (RPC_E_WRONG_THREAD))

So, I've read about using Dispatcher to solve this sort of problem. It works for me ONLY when I don't leave the MainPage:
    public async void printer()
    {
        await this.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
        {
            Debug.WriteLine("I'm inside the printer before");
           this.staffImageBorder.Fill = new SolidColorBrush(Colors.Blue);
            Debug.WriteLine("I'm inside the printer after");
        });
}

However, when I call this printer() method from my other class, it just skips right over the Fill change. Both Debug statements print.
I tried to move the Dispatcher code over to my other class but that class doesn't know what "Dispatcher" is (and neither do I ...).
Sorry I couldn't provide more code, I'm having difficulty replicating it on a simpler example. Any help would be greatly appreciated!

A: Dispatcher essentially manages dispatching events on the UI thread (and any updates to the UI need to be done on the UI thread!).
If you want to access it from outside a page you can access it via Window.Current.Dispatcher (or assign it as a static variable somewhere if you can't access Window - there's only ONE dispatcher per UI thread / Window that everything in that Window shares)
If it's printing both Debug statements however it's more than likely NOT skipping over your code, but you've got some issue elsewhere.
BTW, you probably want to re-write as a Task and NOT as an async void.
public Task SetPrintFillAsync()
{
    return this.Dispatcher.RunAsync(CoreDispatcherPriority.High, () =>
    {
        Debug.WriteLine("I'm inside the printer before");
        this.staffImageBorder.Fill = new SolidColorBrush(Colors.Blue);
        Debug.WriteLine("I'm inside the printer after");
    });
}

And call like
await SetPrintFillAsync()


text:
Q: Ionic angularjs Android App I am developing an android app using the Ionic framework. I am trying to build the basic fileupload system.
<form action="" enctype="multipart/form-data" method="post">
      <fieldset>
        <input type="file" name="image">
        <input type="submit" value="Upload">
      </fieldset>
    </form>

After selecting the image, it doesnot show original filename. It shows some random filename without extension.
Here is the screenshots. I have selected the images-2.jpeg

Thanks to all


text:
Q: Does htmlunit creates browser instances on the machine where it is running? I am using htmlunit for web scraping - logging to a website on behalf of the users, settings something in their profile and then come back.
Just using pure Htmlunit and no selenium framework.
Now my question:
WebClient webClient = new WebClient(BrowserVersion.INTERNET_EXPLORER_11);
Does this statement - creates a browser instance on the machine where i am executing the code or what it does?
I am using BrowserVersion.INTERNET_EXPLORER_11 as this is an accepted browser at that website.
How Selenium is different than htmlunit - i know we can use htmlunit as a webdriver in Selenium. Does Selenium needs a native browser instance on the machine where the code is getting executed? Does Selenium creates browser instances?
My use case is - I will be having multiple users accessing this application. I know WebClient in htmlunit is not thread safe(so have to code it as Spring proto type bean).
Is there any suggestions regarding this?
Any help is greatly appreciated.

A: HTMLUnit is a headless browser. So no window will be created if used with Selenium either. Setting the BrowserVersion will just tell HTMLUnit to present itself to the server as if it were a given browser (AFAIK, it will just change the User-Agent but might perform additional internal processing depending on the version). I guess this answers most of the questions but the last one.
Regarding asking for suggestions on how to implement this I would try to avoid logging in to a website that way. If the website does not provide an API for this then it is likely that it is agains the Terms Of Service. Assuming it is not, you will have to create new WebClient instances for each user each time the data needs to be extracted from the other site.


text:
Q: Transformation of model I have the following model

$y_i=\beta_1+\beta_2x_i+\epsilon_i$ with $E(\epsilon^2)=\sigma^2\exp(x_i)$

And I have to use the proper transformation to obtain a model where the variance of the error is $\sigma^2$.
My guess:
I do not have any guesses because I do not know how to proceed.

A: You should probably replace "I have no idea" in the question with at least some outline of the way that you understand now how to proceed, since it shows (presumably) some form of research along the lines we'd expect to give guidance.
Since you show in comments that you already have the right idea (but you make it harder than it needs to be for this case -- you don't need matrices for this simple version of the problem), let me discuss a slightly more general case (generalizing the form of $\epsilon$) in a simpler way -- but without quite giving all the details of showing it does what's needed. It essentially proceeds as you were doing with the matrix-formulation.
Let $y_i = \beta_0+\beta_1 x_i + \epsilon_i$ where the $\epsilon$'s are all mutually independent with mean $0$, and $\text{Var}(\epsilon_i) = \sigma^2 v(x_i)$ for $v$ some specified function where $v(x)\geq 0$ for all possible $x$.
(This can be fitted by weighted regression as it stands. Simply supply $w_i = 1/v(x_i)$ as weights to a regression routine, though note that you'll need $v$ strictly greater than $0$ to do this -- as you will for the approach below; observations where $v$ is exactly $0$ can still be done if there's no more than $2$ of them; and if there's more than $1$ of them the rest of the data can have no impact.)
However, it can be converted to an unweighted regression --
Define $s(x)=v(x)^\frac12$.
Then divide both sides through by $s(x_i)$ (which has the same effect as pre-multiplying $y$ and $X$ by $K^{-1}$ where the diagonal of $K$ is $v(x_i)^\frac12$ in your approach) -- i.e. let $y^*_i = y_i/s(x_i)$, let $x^*_i= x_i/s(x_i)$ and let $\eta_i = \epsilon_i/s(x_i)$. Further, let $j^*_i = 1/s(x_i)$.
Then we have a new equation: $y^*_i = \beta_0 j^*_i + \beta_1 x^*_i + \eta_i$. The mutual independence of $\eta$ follows from the mutual independence of $\epsilon$ and the remaining properties of $\eta$ relating to mean and variance are readily established (the required variance follows from basic properties of variance). Showing these results is, as they say in the books, left as an exercise for the reader.
This can be fitted using ordinary unweighted multiple linear regression by supplying $j^*$ and $x^*$ as predictors and $y^*$ as the response, but note carefully that there's no intercept term here.
The more general case of multiple regression $y=X\beta+\epsilon$ can be done in similar fashion, and here ii is convenient to proceed with matrices as you were doing, with similar effect -- you define $y^*$ as before and $X^*=W^\frac12 X$ for a diagonal weight-matrix $W$ where $w_i=\text{diag}(W)_i=1/v(x_i)$, noting that the corresponding column to the column of $1$'s in $X$ is not a constant in $X^*$ but of the same form as $j^*$ above.


text:
Q: django-select2 class-based or function based views I'm thinking of using django-select2 project on my forms, but I'm mostly concerned about views do they have to be class-based views or I can use regular function views ?
In the documentation they only mention class-based views but didn't say a word about function based views (like in snippet below) so I don't know if it will work with my regular function views?
Thanks in advance.
https://django-select2.readthedocs.io/en/latest/
A simple class based view will do, to render your form:
# views.py
from django.views import generic

from . import forms, models

class BookCreateView(generic.CreateView):
    model = models.Book
    form_class = forms.BookForm
    success_url = "/"

And I want to use it with the view like one below is:
def prilog_tacka_poziv_dodaj(request,poziv_id,tackapoziv_id):
    poziv=Poziv.objects.get(id=poziv_id)
    tackapoziv=TackaPoziv.objects.get(id=tackapoziv_id)
    if request.method=='POST':
        forma=PrilogTackaPozivDodaj(request.POST)
        if forma.is_valid():
            forma.save()
            return redirect('poziv',poziv_id=poziv.id)
    else:
        forma=PrilogTackaPozivDodaj(initial={'tacka_poziv':tackapoziv})
    return render(request,'prilog_tacka_poziv_dodaj.html',{'forma':forma,'poziv':poziv,'tackapoziv':tackapoziv})

A: I have tried it and it works with function based views also!


text:
Q: css print friendly version - disabling links I have a page with many links. and Have a button to print, clicking on that will be print.css included. In print preview version of the page remain all the links intact.
Is there a way to disable all the link in print preview? i.e. they are no more clickable.

A: I know this isn't disabling the links, but this is along the lines of print preview and links. Here's an option that you can add to your css so links will print much nicer: http://davidwalsh.name/optimize-your-links-for-print-using-css-show-url

A: I wouldn't disable the links as much as style them the same way as regular text, since the intent of clicking on Print Preview is to prepare to print the page, where the links won't work anyway.
If you're still set on disabling links, you can try this query code. Assume that your body has a class called print on it:
$("body.print a").each(function(a) { $(a).html(a.innertext); });

The above is pseduocode and was off the top of my head at 8:30 AM. I would just save yourself the trouble and make links look like surrounding text.


text:
Q: How to check efficiently if numpy array a contains b How to check if one numpy array a contains fully another numpy array b efficiently?
Somewhat like b is subset of a....
Thanks!
EDIT:
a and b are one dimentional numpy arrays

A: If you're asking about b being a consecutive sub-array of a
If either of the arrays can contain repeated values, algorithmically speaking, your problem is equivalent to a single-pattern string-searching problem. There are several known algorithms for this problem.  Unfortunately, neither is too simple.
Else, it is simple to implement, by first looking for the first element in b, then comparing all the following elements:
import numpy as np

def is_subarray_no_repeatition(a, b):
  try:
    i = np.where(a == b[0])[0][0]
  except IndexError:
    # either b is empty, or b[0] not in a
    return b.size == 0
  a = a[i : i+b.size]
  if a.size < b.size:
    return False
  return (a == b).all()

If you're asking about b being a subset of a (i.e. that each element of b exists in a)
def is_subset(a, b):
  b = np.unique1d(b)
  c = np.intersect1d(a,b)
  return c.size == b.size


text:
Q: How to create hoverover popups in Rails 3.1 I have been searching for a way to implement a hover-over popup with no luck.  Because it is used on so many sites I thought it would be easy to find instructions, but I am wondering if I am missing something basic.  I have looked at qTips2 and a few others, but these seem like way more than I need.
I have a Rails 3.1 app and want to display more details when a user hovers over a line in a table.  Is this something built into Rails that I am missing, or do I need an add-on?
I sure would appreciate someone pointing me in the right direction.

A: Just set the title on your link like this
My link

A: Use some CSS and Javascript!
Here's an example you can play with: http://jsfiddle.net/cdpZg/
Copying it here, just in case.
HTML:

I am a user. Move your mouse over me

Extended info about a user

I a piece of useless information. No use hovering over me.

CSS:
#popup {
    height: 50px;
    width: 200px;
    text-align: center;
    vertical-align:middle;
    background-color: cornflowerblue;
    color: white;
    display: none;
    padding-top: 8px;
    position: absolute;
}

Javascript:
$(document).ready(function() {
    $('#user').hover(function() {
        $('#popup').show();
    }, function() {
        $('#popup').hide();
    });
});


text:
Q: Silent Redirect uri not being called using oidc-client We tried to renew token silently (refresh token) using Oidc-Client library. We were able to login successfully.
But once user's token expired silent callback page not being called even it is configured like below. Kindly help if anything missing or re-correct.
Also silent redirect uri configured in identity server as one of redirect_uri.
Login.ts
Office.initialize = function () {
     var settings = {
      authority: "https://xxxx.xxxxx.com/xxxx/v1",
      client_id: "https://xxx.xxx.com/",
      redirect_uri: "https://localhost:3000/taskpane.html",
      post_logout_redirect_uri: "https://localhost:3000/logout.html",
      revokeAccessTokenOnSignout: true,
      response_type: "id_token token",
      scope: "openid read:xxxx read:xxxx",
      state: true,
      filterProtocolClaims: true,
      loadUserInfo: true,
      nonce:true,
      clearHashAfterLogin: true,
      automaticSilentRenew: true,
      silent_redirect_uri: 'https://localhost:3000/silent-refresh.html',
      monitorsession:true,
      metadata: {
        issuer: 'https://xxx.xxx.com/xxx/v1',
        authorization_endpoint:  "https://xxx.xxx.com/xxxxx/v1/connect/authorize"

    }
    };

    var mgr = new Oidc.UserManager(settings);
    mgr.signinRedirect();

mgr.events.addAccessTokenExpiring(function(){
    console.log("token expiring...");
});

}

silent-refresh.html
<head>
    <title>RefreshToken</title>
    <meta http-equiv="Content-Security-Policy" content="upgrade-insecure-requests">
</head>
<body>
    <script type="text/javascript" src=https://cdnjs.cloudflare.com/ajax/libs/oidc-client/1.10.0/oidc-client.js></script>
<script>
    new Oidc.UserManager().signinSilentCallback().then((user)=>
    { consolse.log("silentrenewed");}
    )
        .catch((err) => {
            console.log(err);
        });

</script>
</body>

Auth.ts
import { UserManager, WebStorageStateStore } from "oidc-client";

export default class AuthSigninService {
  private userManager: UserManager;

  constructor() {

      const settings: any = {
        ..................
        automaticSilentRenew: true,
      accessTokenExpiringNotificationTime: 4,
        silent_redirect_uri: "https://localhost:3000/taskpane.html",
        monitorsession:false,
             };

      this.userManager = new UserManager(settings);
    }

    public signin()
    {
        return this.userManager.signinRedirect();
    }

  public async silentRenew() {
    try {
      const user = await this.userManager.signinSilentCallback().then((success) => {
        console.log("silentrenewed");
        console.log(success);
      }
      )
        .catch((err) => {
          console.log(err);
        });

    }
    catch (err) {
      console.log(err);
    }
    }
}

taskpane.ts
document.getElementById('btnSilent').onclick = SilentRenew;

async function SilentRenew() {

  const auth = new AuthSigninService();
  auth.silentRenew();

}

A: Possible causes:

*

*Something to do with the inline script

*Maybe the second instance of UserManager also needs to be initialised with settings

WHAT I WOULD TRY

*

*On the main window, call await mgr.signInSilent(); to do an 'on demand' silent renewal and see if you get any console.log output.

*Make the iframe code part of your main app rather than running it inline in an HTML page
SOMETHING TO COMPARE AGAINST
My code sample does iframe silent renewal and the spa code may give you some ideas.
I tend to set the silent renewal URI to the main index.html page, which I find simpler. Then write code like this:
if (window.top === window.self) {

    // If index.html is running on the main window, run the app
    const app = new App();
    app.execute();

} else {

    // If index.html is running on an iframe, handle token renewal responses
    const app = new IFrameApp();
    app.execute();

}

Here is my OAuth code by the way.


text:
Q: How remove html entity values from ajax paramater I was working ajax with my php code. I just want to retrieve some values from the database. So what i am doing is, when i click on the edit button i am getting its id using that i am passing through ajax and retrieve the value from mysql.
my Html code:
   <a class="edit_address_book" style='float:right;' id="<?= $list['address_key'] ?>">Edit

jquery:
 $(document).on("click", ".edit_address_book", function(){
  $(".address_book").hide();
  $key = $(this).attr("id");
  alert($key); //printing agagaga
  $param = {address_key: $(this).attr("id")};
  $.ajax({
      url: "<?= BASE_URL ?>/users/get_address_book.html",
      type: "POST",
      data: ($param),
      success: function(data){
        alert(data);
        //window.reload();
      },
      error: function(xhr){
        alert("error " + xhr.status);
      }
  });

PHP
 $key = $_POST['address_key'];
        $query = Yii::$app->DB->createCommand("SELECT address_key, flat_no, apartment, address, company, delivery_instruction, alternate_contact WHERE address_key =". mysql_real_escape_string(mysql_real_escape_string($key)));
        //$query->bindValue(":key", mysql_real_escape_string($key));
        $result = $query->queryOne();

when i am seeing the in my console i got this error

Exception (Database Exception) 'yii\db\Exception' with message 'SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'WHERE address_key =sfdsewrffdsfds' at line 1
  The SQL being executed was: SELECT address_key, flat_no, apartment, address, company, delivery_instruction, alternate_contact WHERE address_key =sfdsewrffdsfds&#039//it showing this single quote as html entity;

please someone help me

A: You need to wrap your SQL data in single quotes. You're also double escaping the data
$query = Yii::$app->DB->createCommand("SELECT address_key, flat_no, apartment, address, company, delivery_instruction, alternate_contact WHERE address_key ='". mysql_real_escape_string($key) . "'");

And last but not least, stop using mysql_ functions


text:
Q: undefined component in Vue.js I'm following the Laracasts Tutorials on Vue.js and i've hit a bit of a roadblock, i have a vueify component called app-footer.vue that contains all of my styles scripts and template.
<style>
    .red {
        background-color: #000;
    }
</style>

<template>
    <p class="footer-text">Copyright {{ currentYear }} </p>
</template>

<script>
    export default {
        data () {
            return {
                currentYear: new Date().getFullYear()
            }
        }
    }
</script>

Then in my view i define the component as
<app-footer></app-footer>

And finally in my app.js file i import the template file and add it to my Vue instance's components list as follows
window.Vue = require('Vue');

import AppFooter from './components/app-footer.vue';

new Vue({
    el: 'body',
    components: { AppFooter }
});

I just keep getting Component errors asking me if i've
defined it correctly what exactly am i doing wrong?

A: The issue was simple, i forgot to name the component when setting it in my Vue declaration.
WRONG
 new Vue({
    el: 'body',
    components: { AppFooter }
});

RIGHT
 new Vue({
    el: 'body',
    components: { 'app-footer': AppFooter }
});


text:
Q: OSGi bundle doesn't start when using declarative service annotations I'm working with OSGi and Equinox for the first time and I'm trying to build a simple project. It has two bundles:

*

*A service bundle with a simple MyService interface and an implementing MyServiceImpl class.

*A consumer bundle with consisting only a MyConsumer class.

The service interface looks like this:
package test.service.osgi.service;

public interface MyService {

    public String getMessage();
}

The implementing class like this:
package test.service.osgi.impl;

import org.osgi.service.component.annotations.Activate;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.Deactivate;

import test.service.osgi.service.MyService;

@Component (immediate = true, service = MyService.class)
public class MyServiceImpl implements MyService {

    @Activate
    public void activate() {
        System.out.println("MyService is active!");
    }

    @Override
    public String getMessage() {

        return "Hello world!";
    }

    @Deactivate
    public void deactivate() {
        System.out.println("MyService is no longer active.");
    }
}

The consumer Class of the other bundle looks like this:
package org.osgi.service.consumer;

import org.osgi.service.component.annotations.Activate;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.Reference;

import test.service.osgi.service.MyService;

@Component(immediate = true, service = MyConsumer.class)
public class MyConsumer {

    @Reference
    MyService myService;

    @Activate
    public void activate() {
        System.out.println("Activate executed");
        printMessage();
    }

    public void printMessage() {
        if(myService != null ) {
            System.out.println(myService.getMessage());
        } else {
            System.out.println("MyService Reference is null!!!");
        }
    }
}

I configured both MANIFEST.MF and the Run configurations according to this tutorial: https://www.datainmotion.de/osgi-in-a-nutshell-launch-a-simple-service/
But when I run the project there is no output on the console. it only says "osgi>".
I can use the commands like "ss" and get "Framework is launched" with the list of the bundles, which are all in ACTIVE state. However, none of the strings from the printing commands appear.
The same applies to when I stop and restart the consumer bundle via console command.
Does anyone know what the problem is?
I've been trying to get this running for hours but whatever I do, nothing changes.


text:
Q: What is keys which do not require encryption in KeyStore Provider? I want to store my secret keys using Android KeyStore Provider (on Android 6 and above). But I can't understand one thing: is the keys will be deleted when user change settings of lock screen?
In changes list to Android 6 described:

Keys which do not require encryption at rest will no longer be deleted
  when secure lock screen is disabled or reset (for example, by the user
  or a Device Administrator). Keys which require encryption at rest will
  be deleted during these events.

But what is the keys which do not require encryption? Is it mean that I should choose between store keys unsafely (without encryption) or it will be erased when user changes settings?

A: Keys that require user authentication are generated using setAuthenticationRequired on the KeyGenParameterSpec on API 23+:
KeyGenParameterSpec
  .Builder(...)
  .setUserAuthenticationRequired(requiresAuth)
  ...
  .build()

and using setEncryptionRequired on the KeyPairGeneratorSpec on API 19-22:
specBuilder = KeyPairGeneratorSpec.Builder(context)
if (requiresAuth) {
  specBuilder.setEncryptionRequired()
}


text:
Q: How to filter out results from PostgreSQL query based on combination of criteria across multiple columns I am trying to find unfinished tasks within a PostgreSQL table of tasks based on criteria.
The table contains information on the task number, step within a task, type, workplace, time and operator. The task is considered finished when all operators finished. What I specifically need to achieve is a query result that would show all relevant rows for a task and within it the rows that only exist with a "start" code. Example follows:
Task number Step    Code    Type    Workplace   Operator    Time
5006302212  10      Start   PPBG    M7UF-110    18003461    05:55:14
5006302212  10      Start   PPBG    M7UF-110    18002838    05:59:56
5006302212  10      Stop    PPBG    M7UF-110    18002838    13:59:23
5006302212  10      Start   PPBG    M7UF-110    18003460    05:55:04

From this example I see that task 5006302212 and its step 10 was started (code Start) by 3 operators. One of them already finished (code Stop). What I need is to get this table:
Task number Step    Code    Type    Workplace   Operator    Time
5006302212  10      Start   PPBG    M7UF-110    18003461    05:55:14
5006302212  10      Start   PPBG    M7UF-110    18003460    05:55:04

I tried using EXCEPT for a query of Stop code but that won't help as it returns the row with Start code for operator that already finished.
Any help will be appreciated.

A: You can use the NOT EXISTS clause to find rows that don't have a matching Stop step:
SELECT * FROM task
WHERE code = 'Start'
  AND NOT EXISTS
  (
    SELECT FROM task t2
    WHERE (task.task_number, task.step, task.type, task.workplace, task.operator) =
         (t2.task_number, t2.step, t2.type, t2.workplace, t2.operator)
      AND t2.code = 'Stop'
);

Here's a fiddle
Edit:
In response to the comment, it gets a bit trickier if the task can be restarted by the same operator, but you should be able to just check for Stop times > Start times in the AND NOT EXISTS clause:
SELECT * FROM task
WHERE code = 'Start'
  AND NOT EXISTS
  (
    SELECT FROM task t2
    WHERE (task.task_number, task.step, task.type, task.workplace, task.operator) =
         (t2.task_number, t2.step, t2.type, t2.workplace, t2.operator)
      AND t2.code = 'Stop'
      AND t2.task_time > task.task_time
);

Fiddle2


text:
Q: Docker filling up storage on macOS (Post created on Oct 05 '16)
I noticed that every time I run an image and delete it, my system doesn't return to the original amount of available space.
The lifecycle I'm applying to my containers is:
> docker build ...
> docker run CONTAINER_TAG
> docker stop CONTAINER_TAG
> rm docker CONTAINER_ID
> rmi docker image_id

[ running on a default mac terminal ]
The containers in fact were created from custom images, running from node and a standard redis. My OS is OSX 10.11.6.
At the end of the day I see I keep losing Mbs. How can I face this problem?
EDITED POST
2020 and the problem persists, leaving this update for the community:
Today running:

*

*macOS 10.13.6

*Docker Engine 18.9.2

*Docker Desktop Cli 2.0.0.3

The easiest way to workaround the problem is to prune the system with the Docker utilties.
docker system prune -a --volumes

A: There are three areas of Docker storage that can mount up, because Docker is cautious - it doesn't automatically remove any of them: exited containers, unused container volumes, unused image layers. In a dev environment with lots of building and running, that can be a lot of disk space.
These three commands clear down anything not being used:

*

*docker rm $(docker ps -f status=exited -aq) - remove stopped containers

*docker rmi $(docker images -f "dangling=true" -q) - remove image layers that are not used in any images

*docker volume rm $(docker volume ls -qf dangling=true) - remove volumes that are not used by any containers.

These are safe to run, they won't delete image layers that are referenced by images, or data volumes that are used by containers. You can alias them, and/or put them in a CRON job to regularly clean up the local disk.

A: Since nothing here was working for me, here's what I did. Check file size:
ls -lhks ~/Library/Containers/com.docker.docker//Data/vms/0/data/Docker.raw

Then in the docker desktop simply reduce the disk image size (I was using raw format). It will say it will delete everything, but by the time you are reading this post, you probably already have. So that creates a fresh new empty file.

A: i'm not sure if it is related to the current topic , but this been a solution for me personally
open docker settings -> resources -> disk image size - 16gb

A: It is also worth mentioning that file size of docker.qcow2 (or Docker.raw on High Sierra with Apple Filesystem) can seem very large (~64GiB), larger than it actually is, when using the following command:

*

*ls -klsh Docker.raw
This can be somehow misleading because it will output the logical size of the file rather than its physical size.
To see the physical size of the file you can use this command:

*

*du -h Docker.raw
Source: https://docs.docker.com/docker-for-mac/faqs/#disk-usage

A: Why does the file keep growing?
If Docker is used regularly, the size of the  Docker.raw  (or  Docker.qcow2) can keep growing, even when files are deleted.
To demonstrate the effect, first check the  current  size of the file on the host:
$ cd ~/Library/Containers/com.docker.docker/Data/com.docker.driver.amd64-linux/
$ ls -s Docker.raw
9964528 Docker.raw

Note the use of  -s  which displays the number of filesystem blocks actually used by the file. The number of blocks used is not necessarily the same as the file "size", as the file can be  sparse.
Next start a container in a separate terminal and create a 1GiB file in it:
$ docker run -it alpine sh
# and then inside the container:
/ # dd if=/dev/zero of=1GiB bs=1048576 count=1024
1024+0 records in
1024+0 records out
/ # sync

Back on the host check the file size again:
$ ls -s Docker.raw
12061704 Docker.raw

Note the increase in size from  9964528  to  12061704, where the increase of  2097176 512-byte sectors is approximately 1GiB, as expected. If you switch back to the  alpine  container terminal and delete the file:
/ # rm -f 1GiB
/ # sync

then check the file on the host:
$ ls -s Docker.raw
12059672 Docker.raw

The file has not got any smaller! Whatever has happened to the file inside the VM, the host doesn't seem to know about it.
Next if you re-create the "same"  1GiB  file in the container again and then check the size again you will see:
$ ls -s Docker.raw
14109456 Docker.raw

It's got even bigger! It seems that if you create and destroy files in a loop, the size of the  Docker.raw  (or  Docker.qcow2) will increase up to the upper limit (currently set to 64 GiB), even if the filesystem inside the VM is relatively empty.
The explanation for this odd behaviour lies with how filesystems typically manage blocks. When a file is to be created or extended, the filesystem will find a free block and add it to the file. When a file is removed, the blocks become "free" from the filesystem's point of view, but no-one tells the disk device. Making matters worse, the newly-freed blocks might not be re-used straight away – it's completely up to the filesystem's block allocation algorithm. For example, the algorithm might be designed to favour allocating blocks contiguously for a file: recently-freed blocks are unlikely to be in the ideal place for the file being extended.
Since the block allocator in practice tends to favour unused blocks, the result is that the  Docker.raw  (or  Docker.qcow2) will constantly accumulate new blocks, many of which contain stale data. The file on the host gets larger and larger, even though the filesystem inside the VM still reports plenty of free space.
TRIM
A  TRIM  command (or a  DISCARD  or  UNMAP) allows a filesystem to signal to a disk that a range of sectors contain stale data and they can be forgotten. This allows:

*

*an SSD drive to erase and reuse the space, rather than spend time shuffling it around; and

*Docker for Mac to deallocate the blocks in the host filesystem, shrinking the file.

So how do we make this work?
Automatic TRIM in Docker for Mac
In Docker for Mac 17.11 there is a  containerd  "task" called  trim-after-delete  listening for Docker image deletion events. It can be seen via the  ctr  command:
$ docker run --rm -it --privileged --pid=host walkerlee/nsenter -t 1 -m -u -i -n ctr t ls
TASK                    PID     STATUS
vsudd                   1741    RUNNING
acpid                   871     RUNNING
diagnose                913     RUNNING
docker-ce               958     RUNNING
host-timesync-daemon    1046    RUNNING
ntpd                    1109    RUNNING
trim-after-delete       1339    RUNNING
vpnkit-forwarder        1550    RUNNING

When an image deletion event is received, the process waits for a few seconds (in case other images are being deleted, for example as part of a  docker system prune  ) and then runs  fstrim  on the filesystem.
Returning to the example in the previous section, if you delete the 1 GiB file inside the  alpine  container
/ # rm -f 1GiB

then run  fstrim  manually from a terminal in the host:
$ docker run --rm -it --privileged --pid=host walkerlee/nsenter -t 1 -m -u -i -n fstrim /var/lib/docker

then check the file size:
$ ls -s Docker.raw
9965016 Docker.raw

The file is back to (approximately) it's original size – the space has finally been freed!
Hopefully this blog will be helpful, also checkout the following macos docker utility scripts for this problem:
https://github.com/wanliqun/macos_docker_toolkit

A: WARNING:

By default, volumes are not removed to prevent important data from being deleted if there is currently no container using the volume. Use the --volumes flag when running the command to prune volumes as well:

Docker now has a single command to do that:
docker system prune -a --volumes

See the Docker system prune docs

A: Docker on Mac has an additional problem that is hurting a lot of people: the docker.qcow2 file can grow out of proportions (up to 64gb) and won't ever shrink back down on its own.
https://github.com/docker/for-mac/issues/371
As stated in one of the replies by djs55 this is in the planning to be fixed, but its not a quick fix. Quote:

The .qcow2 is exposed to the VM as a block device with a maximum size
  of 64GiB. As new files are created in the filesystem by containers,
  new sectors are written to the block device. These new sectors are
  appended to the .qcow2 file causing it to grow in size, until it
  eventually becomes fully allocated. It stops growing when it hits this
  maximum size.
...
We're hoping to fix this in several stages: (note this is still at the
  planning / design stage, but I hope it gives you an idea)
1) we'll switch to a connection protocol which supports TRIM, and
  implement free-block tracking in a metadata file next to the qcow2.
  We'll create a compaction tool which can be run offline to shrink the
  disk (a bit like the qemu-img convert but without the dd if=/dev/zero
  and it should be fast because it will already know where the empty
  space is)
2) we'll automate running of the compaction tool over VM reboots,
  assuming it's quick enough
3) we'll switch to an online compactor (which is a bit like a GC in a
  programming language)
We're also looking at making the maximum size of the .qcow2
  configurable. Perhaps 64GiB is too large for some environments and a
  smaller cap would help?

Update 2019: many updates have been done to Docker for Mac since this answer was posted to help mitigate problems (notably: supporting a different filesystem).
Cleanup is still not fully automatic though, you may need to prune from time to time. For a single command that can help to cleanup disk space, see zhongjiajie's answer.

A: docker container prune
docker system prune
docker image prune
docker volume prune

A: There are several options on how to limit docker diskspace, I'd start by limiting/rotating the logs: Docker container logs taking all my disk space
E.g. if you have a recent docker version, you can start it with an --log-opt max-size=50m option per container.
Also - if you've got old, unused containers, you can consider having a look at the docker logs which are located at /var/lib/docker/containers/*/*-json.log

A: $ sudo docker system prune

WARNING! This will remove:

*

*all stopped containers

*all networks not used by at least one container

*all dangling images

*all dangling build cache


text:
Q: Blaze does not understand a SQLAlchemy type I am getting errors trying to use blaze
import pandas as pd
import numpy as np
from sqlalchemy import create_engine
from blaze import *

database_con = create_engine("mssql+pyodbc://server/database?driver=SQL Server Native Client 11.0", echo=False)

bzdata = data(database_con)

Blaze does not understand a SQLAlchemy type. Blaze provided the
  following error:  No SQL-datashape match for type TIMESTAMP Skipping.

is there a way to fix this?


text:
Q: Adding a Form to Visual Studio 2015 Load Test I am writing a Load test for a web service in Visual Studio 2015 Enterprise.
One of the required web request headers is a token that provides web service authentication information.
I get this token from a Login form that I am trying to pull up before my test executes.
Something like this:
    public override IEnumerator<WebTestRequest> GetRequestEnumerator ()
        {
            MyForm f = new MyForm();
            string auth = f.Login(); //also shows form

            //Then all the web request stuff, including:
            ResourceWebTest.Headers.Add(new WebTestRequestHeader("Authorization", "Token " + TokenAuthenticate));

            yield return ResourceWebTest;
        }

But when I run this, I don't see a form.  I simply get 'Unauthorized', probably because 'auth' is going through as an empty string.
Why isn't my form showing up? Can I get it to appear?
(Edit: I should note that hardcoding the authentication token directly works.)

A: The answer to my issue was to learn how to properly record a Web Test.  Logging in while recording replaced the need to manually show a login form while running the test.


text:
Q: Reading unformatted text data with Fortran (differences with gfortran and intel fortran) I am trying to read data from a very large text file within a FORTRAN program.  The program works fine when compiled with the Intel Fortran compiler, but segfaults when compiled with gfortran.
The data file is formatted such that there is typically six singles on each line.  But every ~10k lines there is a line with less than six values.  For example:
0.1466E+01  0.1459E+01  0.1203E+01  0.1362E+01  0.1281E+01  0.1544E+01
0.1480E+01  0.1517E+01  0.1238E+01  0.1056E+01  0.1204E+01  0.1269E+01
                                 :
0.3555E+00  0.3253E+00  0.6127E+00  0.6702E+00  0.1848E+01  0.2122E+01
0.2039E+01  0.6350E+00  0.6725E+00

I have written a program in FORTRAN to read this file.  A minimal version looks like this:
PROGRAM bigdataread

REAL,ALLOCATABLE :: VAR(:)
INTEGER :: NP, NVAR, NPER
CHARACTER(len=80) :: MOPFILE

       MOPFILE = 'bigdata.OUT'
       NP = 9945            ! Number of grid points
       NVAR = 7             ! Number of Variables
       NPER = 2920      ! Number of times-steps

    ALLOCATE(VAR(NP*NVAR*NPER))
    WRITE(LUNCO,*)'Alocated size ',SIZE(VAR)
    OPEN(UNIT=8,FILE=MOPFILE)
    READ(8,*,END=104,ERR=101)VAR
    WRITE(*,*)'Bigdata sucsessfully read'

    STOP

104    WRITE(*,*)'Reached end of file'
101    WRITE(*,*)'Problem reading in the .OUT file'

STOP
END

If 'NPER' is more 1300, the program (when compiled with gfortran) will segfault.  I have confirmed that the data file has the correct number of values using '$ wc bigdata.OUT'.  Given the dependence on variable size it seems to be a memory issue, but I can't figure out how.  My understanding is that gfortan puts arrays on the heap rather than the stack by default.  Anyone know what is going on here?  Maybe you have some helpful advice for further debugging this problem?
Here are the specifics of my platform:
gcc version 4.6.3 (Ubuntu/Linaro 4.6.3-1ubuntu5)
ifort version 12.1.3
Processor: 12x Intel(R) Core(TM) i7-3930K CPU @ 3.20GHz
Memory: 16412MB (8865MB used)
Operating System:  Linux Mint 13 Maya


text:
Q: Can Looper.loop create multiple loopers I would like to know whether Looper.loop() called multiple times creates multiple loopers??Please find my code below and let me know whether multiple loopers will be created because of this code.If yes then please give me advice to resolve this.

Thanks in advance


text:
Q: Create ArrayList from Postgresql query I have following class:
public class Person {

 private String firstName;
 private String lastName;
 private List<String> habits;
}

I have Postgres query which returns me following result using inner join from 2 tables
name | lastname|      habits
--------------------------------------
John | Smith   | ["walking", "eating"]

I am trying to write RowMapper as following:
private final RowMapper<Person> rowMapper = (rs, rowNum) -> {

 String firstName = rs.getString("name");
 String lastName =  rs.getString("lastName");
}

I am not sure how to create List habits from "habits column in my result table"
Please advise
Thanks

A: I have tried it and working fine. You can try the below code what I have understand from your description.
String firstName = rs.getString("name");
String lastName =  rs.getString("lastName");
List<String> list  =  rs.getObject("habits");

if you get compilation error, it will work definitly
List stringList = new ArrayList;
List objectList = stringList;// this does compile only if List where subtypes of List
objectList.add(new Object());
String s = stringList.get(0);
it should work.
Let me know if you facing still issue

A: Found an answer
The code below is working fine
String[] habits;
        try {
            habits = objectMapper.readValue(rs.getString("habits"), String[].class);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
        List<String> habitsList = Arrays.stream(habits).toList();


text:
Q: POWERSHELL For Each - Multi-Dimension Array Returns String NOT Array I am new to Powershell and I am still discovering -
[string[][]] $adusers = (
     ( "John", "Smith", "jsmith", "jsmith@smitty.com" ),
     ( "James", "Johnson", "jjohnson", "jjohnson@smitty.com" )
)

The second dimension can be returned as 1 dimension array.
 $adusers.GetType();
 $adusers[0].GetType();
 $adusers[1][2].GetType();

 IsPublic IsSerial Name                                     BaseType
 -------- -------- ----                                     --------
 True     True     String[][]                               System.Array
 True     True     String[]                                 System.Array
 True     True     String                                   System.Object

For Each with a 2 Dimensional Array concatenates the array elements of the 2nd dimension with a space delimiter and returns a string object.
Is there a syntax I am missing to CAST the $user variable to a dimension?  Should I have to?
Why does powershell concatenate them all together as a String?
$ForEach($user in $adusers){

    $adusers.GetType();
    $user.GetType();

    $user[0]
    $user[1]
    $user[2]
    $user[3]

}

Output
IsPublic IsSerial Name                                     BaseType
-------- -------- ----                                     --------
True     True     String[][]                               System.Array
True     True     String                                   System.Object
J
o
h
n
True     True     String[][]                               System.Array
True     True     String                                   System.Object
J
a
m
e

**************************** UPDATE ******************************
The problem ends up being that I had initialized the $user variable earlier in a different fragment of code in the same script (using run selection).
[String]$user = "testUser"

The ForEach was casting the 1 dimension array to a string - assuming that is what I wanted.
I tried the solution of declaring $user as a 1 dimension array but incorrectly:
[string]$user = ""
[string[]]$user
$user.GetType();

IsPublic IsSerial Name                                     BaseType
-------- -------- ----                                     --------
True     True     String                                   System.Object

What I needed to do is declare $user as a 1 dimension array and initialize it with a 1 dimension array:
[string]$user = ""
[string[]]$user = ("")
$user.GetType();

IsPublic IsSerial Name                                     BaseType
-------- -------- ----                                     --------
True     True     String[]                                 System.Array

Or start a new Powershell Session where $user has not been previously declared and instantiated.  That also worked.
Like I said I'm new to Powershell and still learning.
I also spent some time in this Question and Answers to get some insight regarding how to clear variables in the shell - interesting.
powershell - Remove all variables

A: I am sorry, that I cannot reproduce your error, as my Output is without any splits.
[string[][]] $adusers = (
     ( "John", "Smith", "jsmith", "jsmith@smitty.com" ),
     ( "James", "Johnson", "jjohnson", "jjohnson@smitty.com" )
)

ForEach ($user in $adusers){

    $adusers.GetType();
    $user.GetType();

    $user[0]
    $user[1]
    $user[2]
    $user[3]

}

IsPublic IsSerial Name                                     BaseType
-------- -------- ----                                     --------
True     True     String[][]                               System.Array
True     True     String[]                                 System.Array
John
Smith
jsmith
jsmith@smitty.com
True     True     String[][]                               System.Array
True     True     String[]                                 System.Array
James
Johnson
jjohnson
jjohnson@smitty.com

PS C:\Users\username> Get-Host
Name             : Windows PowerShell ISE Host
Version          : 5.1.17134.858
InstanceId       : 4c82dfcb-cdf7-4eb5-8c0a-25d2ad359ba3
UI               :   System.Management.Automation.Internal.Host.InternalHostUserInterface
CurrentCulture   : de-DE
CurrentUICulture : de-DE
PrivateData      : Microsoft.PowerShell.Host.ISE.ISEOptions
DebuggerEnabled  : True
IsRunspacePushed : False
Runspace         : System.Management.Automation.Runspaces.LocalRunspace


text:
Q: Creating new Generic references I want to implement two stacks using one array. I also want the stack implementation to be generic. Here is what I have do far:
public class TwoStack<T>
{
    private T array[];

    public TwoStack(int size)
    {
        array = new T[size];
    }

    //additional push/pop implementation
}

But the compiler throws Exception in the line inside the constructor saying "cannot create generic array.
I know that I cannot create new objects of the type T because of type erasure. But why can't I create references to objects of type T?

A: A Java array actually knows its component type at runtime. As you know, a generic class, like your TwoStack<T> doesn't know anything about its generic parameter at runtime. That's why there's a conflict. T[] represents a class that knows its component type T (or subclass of T) at runtime. You therefore need to know T at runtime to create it. This is not what you want.
Some people mentioned using ArrayList<T> or such, instead of an array. Why is that? Because ArrayList<T>, like your TwoStack<T>, doesn't know or care about T at runtime, so it's a perfect match.
Can arrays still be used? Sure. (ArrayLists are implemented using arrays, so naturally anything that can be done with ArrayLists can be done with arrays.) But as we established before, T[] is not what you want.
We want something that doesn't care about T at runtime. This is Object[]. So we have to create a Object[] at runtime. Unfortunately, there is no Object[]<T> in Java, so you lose the compile-time benefits of generics. Plenty of people have created generic wrapper classes for arrays, something like Array<T>; you can easily create one too, as an exercise, but it is not present in the Java library.
If you want to use arrays, there are two options:

*

*Just use Object[], and cast to the element you want as you need it, just like it was with collections before generics. You lose all the niceties of generics, but you do it completely honestly and above-board.

*Lie, cheat, and cast that Object[] into a T[] (i.e. (T[])new Object[size]). Now, this immediately on the surface looks like an illegal cast. (If you, e.g. create an Object[] and cast it to a String[], you immediately get a ClassCastException, because Object[] is not a subclass of String[], though it is the other way around.) But remember that so long as you are inside your generic class, T is erased to the lowest bound, which is Object, so the Object[] to Object[] cast is okay. The danger is deferred until a later time: If you ever return this array as type T[], or allow an outside source to get a reference to this array, and you promised them that it was a T[], and those people are expecting it to be the actual type of T[] (e.g. String[]), the compiler inserts a cast, and you will get a ClassCastException. However, if you take care to never expose this array to the outside world, nobody will know about this lie of T[], and you will be able to use type-safe operations on it without casting to T.

A: How to create a generic array in Java?

A: It's because at runtime, there is no information about the generic types you used at compile time. Therefore the runtime cannot know whether you wanted an Object[] or a String[]. You just have to create an Object[] and cast it to T[] later.

A: Java does not permit the construction of generic array without reflection or weak casting.

A: Use ArrayList instead of an [] array. It is only a tiny bit slower, and it works for this purpose, whereas Java forbids what you are trying to do.

A: Array was poor man's generics.
Java could get by just fine if it only allows Object[]. You can get by just fine if you limit yourself to Object[] only. But just like the non-generic List, using it is kind of painful. Programmer needs some other ways to remind himself what type of objects an array stores.
So Java allows you to specify the type of the elements in an array, like Number[], similar to generified List<Number>. Now javac can make sure you don't insert wrong type of elements; and you don't have to downcast an element retrieved from an array; and there's a simple covariances (for example, Interger[] is subtype of Number[])
Therefore, before the introduction of real generics, array is superior to List in APIs. It's better to return a Number[] than a raw List; the latter is hard to use for callers.
Now, with real generics, these benefits of arary are no longer relavant. Almost anywhere in implementation you needed an X[], you can use an ArrayList<X> instead; anywhere in AP you needed an X[], you can use a List<X> instead.
When you do need to use array, like when programming ArrayList<T> itself, or some other basic data structures, It is ok to use Object[] only. A generic array won't help you much, while being quite confusing itself.


text:
Q: Data validation with external javascript in html I am trying to get a basic data validation working on a form for a uni project. However, the javascript function I am trying to call does not seem to be getting accessed at all, and I haven't been able to figure out why.
Here is my HTML:
<!DOCTYPE HTML>

<meta http-equiv="Content-type" content="text/html;charset=UTF-8">

<TITLE>Make an Order</TITLE>

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

    <form id="guestbook" method="post" action="index.html" onsubmit="return Validator(this);">
        <fieldset>
            <legend>
                Personal information
            </legend>
            Name:
            <input id=name name=name type=text placeholder="Your name" required autofocus>

            Email:
            <input id=email name=email type=text placeholder="Your email address" required>

            Phone number:
            <input id=phnumber name=phnumber type=text placeholder="Your telephone number" required>

        </fieldset>

        <fieldset>
            <legend>
                Order details
            </legend>
            Choose whether you would like to order an image, video, or both:

            <input id=image name=order_type type=checkbox value="Image">$100 Image:

            <input id=video name=order_type type=checkbox value="Video">$95/frame Video:

            URL of image to modify:
            <input id=url name=url type=text placeholder="URL of image" required>

        </fieldset>

        <fieldset>
            <legend>
                Credit card details
            </legend>
            Credit card number:
            <input id=ccnumber name=ccnumber type=text placeholder="Your credit card number" required>

            BSB number:
            <input id=bsbnumber name=bsbnumber type=text placeholder="Your BSB number" required>

        </fieldset>

            <input type="submit" value="Submit" />
            <input type="reset" value="Reset" />

    </form>

website by etc

And here is my external javascript file, Validator.js:
function Validator(theForm)
{
    var errorinit = "Error(s) detected. Please amend before continuing:\n";
    var error = errorinit;

    //check that at least one checkbox (to choose either image or video) has been selected
    var boxChecked = false;
    if (theForm.image.checked == true && theForm.video.checked == true)
    {
        boxChecked = true;
    }
    if (boxChecked == false)
    {
        error += " - You must select at least a video or an image.\n"
        break;
    }

    //check that numerical-only inputs have numbers (but allowing for habitual spaces or dashes) only
    var digits = "0123456789- ";
    var temp = null;
    for (var i = 0; i < theForm.phnumber.value.length; i++)
    {
        temp = theForm.phnumber.value.substring(i, i+1)

        if (digits.indexOf(temp) == -1 && theForm.phnumber.value != "")
        {
            error += " - Your phone number must be numerical only.\n";
            break;
        }
    }
    for (var i = 0; i < theForm.ccnumber.value.length; i++)
    {
        temp = theForm.ccnumber.value.substring(i, i+1)

        if (digits.indexOf(temp) == -1 && theForm.ccnumber.value != "")
        {
            error += " - Your credit card number must be numerical only.\n";
            break;
        }
    }
    for (var i = 0; i < theForm.bsbnumber.value.length; i++)
    {
        temp = theForm.bsbnumber.value.substring(i, i+1)

        if (digits.indexOf(temp) == -1 && theForm.bsbnumber.value != "")
        {
            error += " - Your bsb number must be numerical only.\n";
            break;
        }
    }

    //check that the email address contains an @ symbol
    if ((theForm.email.value.indexOf ('@',0) == -1 || theForm.email.value.indexOf ('.',0) == -1) && theForm.email.value != "")
    {
        error += " - Your email address is invalid.";
    }

    //check if there has been any error
    if (error != errorinit)
    {
        alert(error);
        return (false);
    } else {
        alert("no problems");
        return (true);
    }
}

Now this is fairly simple code, so and after checking and re-checking I am stumped as to why it is not working. As you can see in the javascript, I have set it to throw an alert whether there has been an error or not, but no alert is given at all; I am simply returned to index.html without any validation (apart from the 'required' fields).
Can anybody point out the reason that this is not working?

A: This is the error that you have in your code:
SyntaxError: unlabeled break must be inside loop or switch

You are using break; at part below while you aren't in any switch or loop to break it:
if (boxChecked == false)
{
    error += " - You must select at least a video or an image.\n"
    break;
}

To solve this problem, replace break; with return false; ...


text:
Q: Select over 2 select queries I have two tables:
work:
id  w_date        other stuff
1   2017-05-10
1   2017-05-08
3   2017-05-17

home:
id  h_date       other stuff
1   2017-05-01
4   2017-05-06
1   2017-05-14

Now I need a query that I get all dates where id is 1.
Something like:
Select *
from (
    select w_date as date
    from work where id=1
),
  (select h_date as date from home where id=1)

Result should be:
id  date
1   2017-05-01
1   2017-05-08
1   2017-05-10
1   2017-05-14

Any ideas?

A: I would do something like this
select id,
       w_date as date
from work
where id=1
union all
select id,
       h_date as date
from home
where id=1

A: Select ID, date
from home where ID = 1
UNION all
Select ID, date
from work where ID = 1

For future posts, try to provide more info, some table and data definitions will go a long way.

A: This is a simple UNION query:
SELECT id, date
FROM work
WHERE id = 1
UNION ALL
SELECT id, date
FROM home
WHERE id = 1
ORDER BY date;

I've used the UNION ALL syntax which return all rows from both source tables.  Leaving the ALL keyword out ensures rows that are duplicated in both tables are only returned a single time.
I've added an ORDER BY clause at the end of the query to return the list in date ascending order, since your sample data seems to indicate that.
See the Wikipedia entry for further details.


text:
Q: Alternative to delayed job for simple cron task on heroku? In my Rails app on Heroku, I want to execute a simple block of code at 5 specific times in the future (each about a day apart), down to the second.
Is there a good way to do this without a background process?
I don't want to use Delayed Job because it'll require a Worker instance that costs ~$30/month. Seems unnecessary.
Is there a GOOD way to do this without Delayed Job / a Heroku Worker?
Resolved
Thanks for your answers- looks like there isn't a solid way to accomplish this. Going with Delayed Job.

A: use a rake task and heroku scheduler instead
https://devcenter.heroku.com/articles/scheduler

The scheduler add-on will run one-off processes that will count toward your dyno-hours for the month.

A: You could use a Rake task with the Heroku Scheduler, then add a bit of intelligent logic: sleep until job_is_available if job_is_available_in_less_than_twelve_minutes?
Then you're paying for the time to run the code, and the few seconds it takes your rake task to check if a job is available.  Something like 1-3 dollars, since Heroku pro-rates to the second.

A: You can do it with scheduler, you just need to check the day/hour etc when the task is running  - so you'd schedule an hourly job (if that will work for you) and then check the current day/hour to see if it's one that you want to run the job at and then run it inside the check. Not ideal but will work.

A: Old question, but...
Maybe it can solve your problems: Sucker Punch.
You don't need an extra dyno on Heroku. And it is possible to specify the time between the 5 blocks.


text:
Q: Compact operator from $H^1$ to $L^2$ Let $T : H^1(\mathbb{R}^d) \to L^2(\mathbb{R}^d)$ be the operator such that $Tu(x)=\frac{u(x)}{1+|x|^2}$. (here $H^1$ denotes the Sobolev space)

Question : show that $T$ is compact.

My attempt is this one : let $(u_n)$ be a bounded sequence in $H^1(\mathbb{R}^d)$ I want to show that there is a subsequence $(u_{\phi (n)})$ converging strongly in $L^2(\mathbb{R}^d)$. All I know (and want to use) is that $H^1(\mathbb{R}^d)$ continuously embbed in $L^2$ in every compact. But here the result has to be shown not only for compacts !
How can I do that ?
Thank you.

A: Since $C_0^\infty(R^d)$ is dense in $H^1(R^d)$, it suffices to show this for $C_0^\infty(R^d)$. Denote $B_i$ the centered ball in $R^d$ with center $0$ and radius $i$. Suppose $\{u_m\}$ is a bounded sequence in $C_0^\infty(R^d)$, say norm is less equal to $1$. Consider their restriction on $B_i$. Since $T:H^1(B_i)\rightarrow L^2(B_i)$ is compact, we find a subsequence $\{u^i_m\}$ such that for there exists $N_i$ such that for $m,n> N_i$
\begin{equation}
\|u^i_m-u^i_n\|_{L^2(B_i)}\leq \frac{1}{2^i}.
\end{equation}
In particular for $i+1$-th step, the sequence can be chosen from the sequence which was used for the $i$-th step, i.e., $\{u^{i+1}_m\}\subset\{u^i_m\}$. Now let $v_i:=u^i_i$. Then
\begin{align}
\|(v_m-v_n)/(1+|\cdot|^2)\|_{L^2(R^d)}&=\|(v_m-v_n)/(1+|\cdot|^2)\|_{L^2(B_i)}+\|(v_m-v_n)/(1+|\cdot|^2)\|_{L^2(R^d/B_i)}\\
&=:L_1+L_2.
\end{align}
Since $\{v_i\}$ is bounded in $C_0^\infty(R^d)$ by norm $1$, for each $\varepsilon>0$ $L_2$ can be estimated by $2\|(1+|\cdot|^2)\|_{L^2(R^d/B_i)}<\varepsilon$ for all sufficiently large $i$. Due to the construction of $\{v_i\}$, $L_1$ can be arbitrary small for all enough large $m,n$, then the claim is proved.


text:
Q: What is the most efficient way to loop on properties in array of objects? Is there a way I can achieve this code in a more efficient way ? because looping on a very big scores array just to find one score property is very costly
var scores = [{scoredBy:"youssef",score:5},{scoredBy:"omar",score:3}];

scores.forEach(score=>{
    if(score.scoredBy == "youssef"){
      console.log(score);
    }
})

A: Most efficient way would be to use an object instead of an array where the key is the scoredBy value. No looping, just a lookup.

var scores = { "youssef" : 5, "omar":3 };
console.log(scores["youssef"])

Other ways

*

*for of loop with break

*array find()

var scores = [{scoredBy:"youssef",score:5},{scoredBy:"omar",score:3}];

for (const value of scores) {
  if (value.scoredBy==="youssef") {
    console.log(value.score);
    break;
  }
}

var scores = [{scoredBy:"youssef",score:5},{scoredBy:"omar",score:3}];

var result = scores.find( value => value.scoredBy==="youssef")
console.log(result.score);


text:
Q: Unix Command to timestamp the output of a file, but with the relative-to-when-it-started time? There are numerous programmes (e.g. ts in moreutils), and various bash one-liners to prepend the output of a command/pipe with the timestamp of when that line was 'printed'.
However is there a command that, for each line that it gets, will print the time since the command started (and/or when it first saw a line), and the current line? So rather than print the current time, it'll print how long since that command started? (aswell as the line aswell)
When running commands that take a while, and spew a lot of output, it can be helpful to know how long you've been looking at it.
It would be trivial to whip a simple command up, but I don't want to re-invent the wheel.
This is on an Ubuntu Linux system.

A: Here's one way:
#!/bin/bash
SECONDS=0    # it will already be initialized to zero at the start of the script
while read -r line
do
    echo "$SECONDS: $line"
done < file    # or < <(command)

SECONDS is a variable that automatically increments every second.

A: Well, it looks like there are under-documented (missing on some man pages) options to ts that do exactly what you want.
From my system's man ts:

If the -i or -s switch is passed, ts reports incremental timestamps instead of absolute ones. The default format changes to "%H:%M:%S", and "%.S" and "%.s" can be used as well. In case of -i, every timestamp will be the time elapsed since the last timestamp. In case of -s, the time elapsed since start of the program is used.
The -m switch makes the system's monotonic clock be used.

Not sure if these existed when you asked but man says "Copyright 2006".
Example
cameron@linux:~$ (echo a; sleep 1; echo b; sleep 2; echo c) | ts -i 'delta: %.S' | ts -s 'abs: %.S'
abs: 00.000007 delta: 00.000009 a
abs: 00.973008 delta: 00.972945 b
abs: 02.974591 delta: 02.001582 c


text:
Q: SpringFox - Hide certain fields in Swagger-ui that aren't required for the call to an endpoint I would like to know if there is any way of making SpringFox to not show all the fields of a certain entity that aren't required in the call to an specific endpoint.
For example:
Having the following entity:
public class Car {
    long id;
    String name;
    int wheels;
    String type;
    boolean canFly;
}

And the following endpoints:
@RequestMapping(method = RequestMethod.GET,
                produces = MediaType.APPLICATION_JSON_VALUE)
public Car get(@RequestParam(value = "carId", required = true) long projectId) {
    return carService.get(carId);
}

@RequestMapping(method = RequestMethod.POST,
                consumes = MediaType.APPLICATION_JSON_VALUE,
                produces = MediaType.APPLICATION_JSON_VALUE)
public Car create(@RequestBody Car car) {
    return carService.create(car);
}

@RequestMapping(method = RequestMethod.PUT,
                consumes = MediaType.APPLICATION_JSON_VALUE,
                produces = MediaType.APPLICATION_JSON_VALUE)
public Car update(@RequestBody Car car) {
    return carService.update(car);
}

The thing is that in the create Car endpoint only name and wheels are required, but in the documentation Swagger-ui shows all the fields as if they were required. I've already tried @JsonViews but Springfox does not handle them yet.
Is there any way to avoid this?

A: Use the @ApiModelProperty (from io.swagger.annotations)

*

*With required you define whether the property is mandatory or optional.

*With hidden you can hide the property in Swagger UI, however if it's set it is returned anyway.

For example:
public class Car {

    @ApiModelProperty(value = "id", required = true)
    long id;

    @ApiModelProperty(value = "wheels", required = true)
    int wheels;

    @ApiModelProperty(value = "name", hidden = true)
    String name;

    @ApiModelProperty(value = "type", hidden = true)
    String type;

    @ApiModelProperty(value = "canFly", hidden = true)
    boolean canFly;
}

Since you use the same model for request and response (with the example above) the attributes in the documentation for GET endpoint will be also hidden (keep that in mind). If you don't want such behaviour then use separate models.

A: Starting from the springfox-boot-starter 3.0.0
    <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-boot-starter</artifactId>
        <version>3.0.0</version>
    </dependency>

you can do it very easily and efficiently by adding Jackson JsonProperty annotation on the field you need.
@JsonProperty(access = JsonProperty.Access.READ_ONLY)

E.g. you have a model class Client and you want both:

*

*hide field id in the swagger for the requests (e.g. POST and PUT) but show it in the responses

*do not accept field id in your controller (so that it always will have value 0 no matter what caller set) but return id value of the Client in the response.

You can achieve these by adding annotation on the id field
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Data;
@Data
public class Client {
    @JsonProperty(access = JsonProperty.Access.READ_ONLY)
    private long id;
    private String name;
}


text:
Q: How to draw circle around a pin using Google MAps API v2 I am using the new API(Google Map API V2) for my android application, i have done creating the map and adding markers to it, now my task is to manually create a circle around any of the marker and also i want to provide a functionality to the user that he can increase the radius of that circle accordingly, for this i have given a bar, when user increases that bar the radius of circle will increase and vice versa.
If anybody knows how to do this using Google Map API V2 then please help,
thanks

A: Perhaps help you :
 GoogleMap map;
 // ... get a map.
 // Add a circle in Sydney
 Circle circle = map.addCircle(new CircleOptions()
     .center(new LatLng(-33.87365, 151.20689))
     .radius(10000)
     .strokeColor(Color.RED)
     .fillColor(Color.BLUE));

From here :
HERE

A: I have been working on this too and I found the following solution. It's still not perfect, because I had to make a very large Canvas to prevent the edge of the circle from becoming blurry.
private void addCircleToMap() {

    // circle settings
    int radiusM = // your radius in meters
    double latitude = // your center latitude
    double longitude = // your center longitude
    LatLng latLng = new LatLng(latitude,longitude);

    // draw circle
    int d = 500; // diameter
    Bitmap bm = Bitmap.createBitmap(d, d, Config.ARGB_8888);
    Canvas c = new Canvas(bm);
    Paint p = new Paint();
    p.setColor(getResources().getColor(R.color.green));
    c.drawCircle(d/2, d/2, d/2, p);

    // generate BitmapDescriptor from circle Bitmap
    BitmapDescriptor bmD = BitmapDescriptorFactory.fromBitmap(bm);

// mapView is the GoogleMap
    mapView.addGroundOverlay(new GroundOverlayOptions().
            image(bmD).
            position(latLng,radiusM*2,radiusM*2).
            transparency(0.4f));
}

-- EDIT --
Google updated the API. You can now easily add a circle to your map:
https://developers.google.com/maps/documentation/android/shapes?hl=nl#circles

A: This is better:
    double radiusInMeters = 100.0;
     //red outline
    int strokeColor = 0xffff0000;
    //opaque red fill
    int shadeColor = 0x44ff0000;

    CircleOptions circleOptions = new CircleOptions().center(position).radius(radiusInMeters).fillColor(shadeColor).strokeColor(strokeColor).strokeWidth(2);
    mCircle = map.addCircle(circleOptions);

    MarkerOptions markerOptions = new MarkerOptions().position(position);
    mMarker = map.addMarker(markerOptions);

A: Using this method you can select any marker & it will create the circle object for particular marker.
you can dynamically change radius of the circle by passing the marker object & radius value to the createCircle() method.
 private GoogleMap mMap;
    /*Create circle objects*/
    Circle currentCircle;
     /**
     * create circle when user want to set region
     * @param currentMarker this is user selected marker
     * @param radius pass radius value to circle object
     */
    private void createCircle(Marker currentMarker ,Double radius){

          //check circle is exist or not
               //if exist remove
               if(currentCircle!=null){
                 currentCircle.remove();
                 }
        currentCircle=mMap.addCircle(new CircleOptions().center(currentMarker.getPosition()).radius(radius)
            .strokeColor(Color.parseColor("#FF007A93"))
            .fillColor(Color.parseColor("#40007A93"))
            .strokeWidth(2));
        float zoomLevel = getZoomLevel(radius);
        mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(currentMarker.getPosition(), zoomLevel));
    }


text:
Q: Local SI Remoto NO Stream Necesito de alguien me explique porque este stream solo me trabaja php de forma local y como hacer para que me trabaje en un server remoto.
Si ejecuto este PHP en Player como VLC me funciona de maravilla, pero al momento de subirlo a mi hosting no me trabaja. Pense que se trataba de la GEO localizacion y prove con otro Hosting teniendo el mismo resultado.
Logrando que esto funcione lograre re arrancar otros proyectos que tiene situaciones similares.
Gracias
ob_start();
//error_reporting(0);
header('Content-type: text/plain');

function m3u8($url)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch,CURLOPT_ENCODING, '');
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3',
'Accept-Encoding: gzip, deflate',
'Accept-Language: es-ES,es;q=0.9,fr;q=0.8',
'Cache-Control: max-age=0',
'Connection: keep-alive',
'Host: hochu.tv',
'Referer: http://hochu.tv/',
'Upgrade-Insecure-Requests: 1',
'User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.142 Safari/537.36'));
$server_output = urldecode(curl_exec($ch));
curl_close ($ch);
return $server_output;
}
function m3u82($url2,$ideee)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url2);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch,CURLOPT_ENCODING, '');
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3',
'Accept-Encoding: gzip, deflate',
'Accept-Language: es-ES,es;q=0.9,fr;q=0.8',
'Connection: keep-alive',
'Host: cdntvnet.com',
'Referer: http://hochu.tv/'.$ideee.'.html',
'Upgrade-Insecure-Requests: 1',
'User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.142 Safari/537.36'));
$server_output = urldecode(curl_exec($ch));
curl_close ($ch);
return $server_output;

}
function search($string, $start, $end){
    $string = " ".$string;
    $ini = strpos($string,$start);
    if ($ini == 0) return "";
    $ini += strlen($start);
    $len = strpos($string,$end,$ini) - $ini;
    return substr($string,$ini,$len);
}
$t= htmlspecialchars('olala');
$stream=m3u82('http://cdntvnet.com/'.$t.'.php',$t);
$streamurl=search($stream,'file:"','"});').'&type=m3u8';
$streamurl_par=parse_url($streamurl);
$hoster=$streamurl_par['scheme']."://".$streamurl_par['host'].":".$streamurl_par['port']."/".$t."/";
$geturl=m3u82($streamurl,$t);;

$part = explode(chr(10), $geturl);
for ($i = 0; $i < count($part) - 1; $i++) {
  if (strpos($part[$i], '#') !== false) {
    echo $part[$i] . chr(10);
    } else {
      echo  $hoster.($part[$i]).PHP_EOL;
      }
    }


text:
Q: monoid vs monad in Scala I have recently tried to find a good source on the difference between monads and monoids.
Could someone provide a link to a good resource on this or perhaps take one's time to elaborate on the similarities/differences?

A: Monads are monoids in the category of endofunctors. Therefore, a monad is just one example of monoid, which is a more general concept.
And, though that might be technically true, the most simple answer is that monads and monoids are really nothing like each other, and you shouldn't be trying to learn the difference between them, but just learn them. There's ton of material about it on the internet, easily googled.

A: See this answer on why monads are special cases of monoids in monoidal categories. The latter is, however, a generalization of the classical monoid defined via binary operation and unit. Monad is not a classical monoid. See the answer for more details and explanations.


text:
Q: Horrible redraw performance of the DataGridView on one of my two screens I've actually solved this, but I'm posting it for posterity.
I ran into a very odd issue with the DataGridView on my dual-monitor system. The issue manifests itself as an EXTREMELY slow repaint of the control (like 30 seconds for a full repaint), but only when it is on one of my screens. When on the other, the repaint speed is fine.
I have an Nvidia 8800 GT with the latest non-beta drivers (175. something). Is it a driver bug? I'll leave that up in the air, since I have to live with this particular configuration. (It does not happen on ATI cards, though...)
The paint speed has nothing to do with the cell contents, and custom drawing doesn't improve the performance at all - even when just painting a solid rectangle.
I later find out that placing a ElementHost (from the System.Windows.Forms.Integration namespace) on the form corrects the problem. It doesn't have to be messed with; it just needs to be a child of the form the DataGridView is also on. It can be resized to (0, 0)  as long as the Visible property is true.
I don't want to explicitly add the .NET 3/3.5 dependency to my application; I make a method to create this control at runtime (if it can) using reflection. It works, and at least it fails gracefully on machines that don't have the required library - it just goes back to being slow.
This method also lets me apply to fix while the app is running, making it easier to see what the WPF libraries are changing on my form (using Spy++).
After a lot of trial and error, I notice that enabling double buffering on the control itself (as opposed to just the form) corrects the issue!

So, you just need to make a custom class based off of DataGridView so you can enable its DoubleBuffering. That's it!
class CustomDataGridView: DataGridView
{
    public CustomDataGridView()
    {
        DoubleBuffered = true;
    }
}

As long as all of my instances of the grid are using this custom version, all is well. If I ever run into a situation caused by this where I'm not able to use the subclass solution (if I don't have the code), I suppose I could try to inject that control onto the form :) (although I'll be more likely to try using reflection to force the DoubleBuffered property on from the outside to once again avoid the dependency).
It is sad that such a trivially simple thing ate up so much of my time...

A: The answer to this worked for me too.  I thought I would add a refinement that I think should be standard practise for anyone implementing the solution.
The solution works well except when the UI is being run as a client session under remote desktop, especially where the available network bandwidth is low.  In such a case, performance can be made worse by the use of double-buffering. Therefore, I suggest the following as a more complete answer:
class CustomDataGridView: DataGridView
{
    public CustomDataGridView()
    {
        // if not remote desktop session then enable double-buffering optimization
        if (!System.Windows.Forms.SystemInformation.TerminalServerSession)
            DoubleBuffered = true;
    }
}

For more details, refer to Detecting remote desktop connection

A: You just need to make a custom class based off of DataGridView so you can enable its DoubleBuffering. That's it!

class CustomDataGridView: DataGridView
{
    public CustomDataGridView()
    {
        DoubleBuffered = true;
    }
}

As long as all of my instances of the grid are using this custom version, all is well. If I ever run into a situation caused by this where I'm not able to use the subclass solution (if I don't have the code), I suppose I could try to inject that control onto the form :) (although I'll be more likely to try using reflection to force the DoubleBuffered property on from the outside to once again avoid the dependency).
It is sad that such a trivially simple thing ate up so much of my time...
Note: Making the answer an answer so the question can be marked as answered

A: Here is some code that sets the property using reflection, without subclassing as Benoit suggests.
typeof(DataGridView).InvokeMember(
   "DoubleBuffered",
   BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.SetProperty,
   null,
   myDataGridViewObject,
   new object[] { true });

A: For people searching how to do it in VB.NET, here is the code:
DataGridView1.GetType.InvokeMember("DoubleBuffered", Reflection.BindingFlags.NonPublic Or Reflection.BindingFlags.Instance Or System.Reflection.BindingFlags.SetProperty, Nothing, DataGridView1, New Object() {True})

A: Adding to previous posts, for Windows Forms applications this is what I use for DataGridView components to make them fast. The code for the class DrawingControl is below.
DrawingControl.SetDoubleBuffered(control)
DrawingControl.SuspendDrawing(control)
DrawingControl.ResumeDrawing(control)

Call DrawingControl.SetDoubleBuffered(control) after InitializeComponent() in the constructor.
Call DrawingControl.SuspendDrawing(control) before doing big data updates.
Call DrawingControl.ResumeDrawing(control) after doing big data updates.
These last 2 are best done with a try/finally block. (or even better rewrite the class as IDisposable and call SuspendDrawing() in the constructor and ResumeDrawing() in Dispose().)
using System.Runtime.InteropServices;

public static class DrawingControl
{
    [DllImport("user32.dll")]
    public static extern int SendMessage(IntPtr hWnd, Int32 wMsg, bool wParam, Int32 lParam);

    private const int WM_SETREDRAW = 11;

    /// <summary>
    /// Some controls, such as the DataGridView, do not allow setting the DoubleBuffered property.
    /// It is set as a protected property. This method is a work-around to allow setting it.
    /// Call this in the constructor just after InitializeComponent().
    /// </summary>
    /// <param name="control">The Control on which to set DoubleBuffered to true.</param>
    public static void SetDoubleBuffered(Control control)
    {
        // if not remote desktop session then enable double-buffering optimization
        if (!System.Windows.Forms.SystemInformation.TerminalServerSession)
        {

            // set instance non-public property with name "DoubleBuffered" to true
            typeof(Control).InvokeMember("DoubleBuffered",
                                         System.Reflection.BindingFlags.SetProperty |
                                            System.Reflection.BindingFlags.Instance |
                                            System.Reflection.BindingFlags.NonPublic,
                                         null,
                                         control,
                                         new object[] { true });
        }
    }

    /// <summary>
    /// Suspend drawing updates for the specified control. After the control has been updated
    /// call DrawingControl.ResumeDrawing(Control control).
    /// </summary>
    /// <param name="control">The control to suspend draw updates on.</param>
    public static void SuspendDrawing(Control control)
    {
        SendMessage(control.Handle, WM_SETREDRAW, false, 0);
    }

    /// <summary>
    /// Resume drawing updates for the specified control.
    /// </summary>
    /// <param name="control">The control to resume draw updates on.</param>
    public static void ResumeDrawing(Control control)
    {
        SendMessage(control.Handle, WM_SETREDRAW, true, 0);
        control.Refresh();
    }
}

A: Just to add what we did to fix this issue: We upgraded to the latest Nvidia drivers solved the problem. No code had to be rewritten.
For completeness, the card was an Nvidia Quadro NVS 290 with drivers dated March 2008 (v. 169). Upgrading to the latest (v. 182 dated Feb 2009) significantly improved the paint events for all my controls, especially for the DataGridView.
This issue was not seen on any ATI cards (where development occurs).

A: I found a solution to the problem. Go to troubleshoot tab in the advanced display properties and check the hardware acceleration slider. When I got my new company PC from IT, it was set to one tick from full and I didn't have any problems with datagrids. Once I updated the video card driver and set it to full, painting of datagrid controls became very slow. So I reset it back to where it was and the problem went away.
Hope this trick works for you as well.

A: Best!:
Private Declare Function SendMessage Lib "user32" _
  Alias "SendMessageA" _
  (ByVal hWnd As Integer, ByVal wMsg As Integer, _
  ByVal wParam As Integer, ByRef lParam As Object) _
  As Integer

Const WM_SETREDRAW As Integer = &HB

Public Sub SuspendControl(this As Control)
    SendMessage(this.Handle, WM_SETREDRAW, 0, 0)
End Sub

Public Sub ResumeControl(this As Control)
    RedrawControl(this, True)
End Sub

Public Sub RedrawControl(this As Control, refresh As Boolean)
    SendMessage(this.Handle, WM_SETREDRAW, 1, 0)
    If refresh Then
        this.Refresh()
    End If
End Sub

A: We've experienced a similar problem using .NET 3.0 and DataGridView on a dual monitor system.
Our application would display the grid with a gray background, indicating that the cells could not be changed. Upon selecting a "change settings" button, the program would change the background color of the cells white to indicate to the user that the cell text could be changed. A "cancel" button would change the background color of the aforementioned cells back to gray.
As the background color changed there would be a flicker, a brief impression of a default sized grid with the same number of rows and columns. This problem would only occur on the primary monitor (never the secondary) and it would not occur on a single monitor system.
Double buffering the control, using the above example, solved our problem. We greatly appreciated your help.


text:
Q: How do I send data to a network printer with Perl on Win32? I need to print relatively complex layouts to networked/shared printers with Perl and I haven't had any luck finding modules or examples to help me in the task.  Does anyone have any links that could help me out?
I presume that what I want to do will work as Postscript.
update: Ok, I don't really need help with how to generate PDF or Postscript.  I'm sure that's well documented.  What I want to know is, what do I use to send a PDF to a printer in windows from perl.

A: Win32::Printer exposes the Win32 printing API including printer selection and low level printing commands.
However, the (IMHO) easy way of printing a PDF file on any printer would be to use Ghostscript to produce PCL or PS output (depending on the language the printer supports) and then to copy the resulting file to the printer (using its UNC path). You may need to specify the /b switch for the copy command.

A: Ok, I still need to learn postscript or something, but I found that the following works:
use autodie;
use File::Copy;
copy 'C:\\frew.ps', '\\\\oxygen\\HPLJ5100 PCL6';

Not too complicated.  This seems to work better than opening the printer and printing to it.

A: If you have a PDF file, and the user has Adobe Reader installed (which is pretty standard), you should be able to print the file to the default printer using the ShellExecute function in Win32::FileOp:
use Win32::FileOp 'ShellExecute';

ShellExecute(print => 'A:/Path/to/File.pdf');

A: Wx::Perl has very nice, liberally licensed Win32 pinting capabilities.
I haven't worked with Postscript or PDF from WxPerl, so I don't know what would be involved.  Googling wxPerl print pdf turns up this post on the wxperl list.

Subject:  Re: [wxperl-users] printing a
  PDF from wxPerl   Actions... From:    Mark
  Dootson (mark...@znix.com) Date:  Apr
  5, 2007 5:02:40 pm
  List: org.perl.wxperl-users
Hi,
After writing the last reply, a huge
  kludge occurred to me that, as it
  turns out, works just fine.
use Wx::ActiveX::IE pass it the URL of
  your pdf, and print merrily. e.g.

 my $obj = Wx::ActiveX::IE->new( $frame, -1, wxDefaultPosition, wxDefaultSize );
 $obj->LoadUrl("file:///C:/mytest.pdf");
 $obj->Print(0); # for no print dialog
 $obj->Print(1); # for print dialog

Of course, loading IE and the Acrobat
  plugin may seem a little excessive
  just to print a doc, but heck, this is
  windows and four lines of code is
  pretty impressive.
Mark

This command line program might be another option.  I haven't tried it, and can't vouch for it, but it claims to work for printing postscript data to non-postscript printers.