text:
Q: creating a customer login function using the prestashop webservice I'm currently working on an application that makes use of the prestashop webservice. This means that the application i'm building is an extension of an existing prestashop application. The connection between both applications is through the prestashop webservice
Currently i'm trying to create a login script for thecustomers. The email and password are obtained from the database through the webservice and i'm able to filter the inputs with the existing row's. So when filling in login@test.com. The filter will only obtain the row with that email address.
The problem i'm having is with the password. Prestashop uses a _COOKIE_KEY_ together with anmd5() to encrypt passwords. See this link for more information: link
So i've been trying some different things for a while to check the inputted password with the customers password but i haven't found the solution yet.
Take a look at the code below:
<?php

require_once('./PSWebServiceLibrary.php');

/**
 * get information from PrestaShop
 */

$webService = new PrestaShopWebservice($url, $key, $debug);

define('_COOKIE_KEY_', '...');
$email = "login@test.nl";
define('password', "test");
$md5passwd = md5(_COOKIE_KEY_ . password);

$opt = array(
    "resource" => "customers",
    "display" => "[email , passwd]",
    "filter[email]" => "$email"
);

$optPass = array(
    "resource" => "customers",
    "display" => "[email]",
    "filter[email]" => "$email",
    "filter[passwd]" => "$md5passwd"
);

$jsonPass = ($webService->get( $optPass ));

//json encode it
$jsonPasswd = json_encode($jsonPass);

echo($jsonPasswd);

if(password_verify($md5passwd, $jsonPasswd)) {
    echo "password is valid";
} else {
    echo "password is not valid";
}

$jsonUrl = ($webService->get( $opt ));

//json encode it
$json = json_encode($jsonUrl);

echo($json);

As you can see i've been trying out things like the password_verify and the md5() but i can't quite get it. So is there anyone who has done this or who knows how to create a correct login script on the prestashop webservice?
Update -- 12/1/2017
So after doing some research i've come up with a new way of checking the user input. First the code checks the email and if it's true it will continue with checking the password input. But the problem i'm having is with the password and the password encryption of prestashop. I'm not able to compare the two hashes together. The first hash would be the hash from the database were the second hash is the user input password. The input would need a hash() function from prestashop. But i can't quite get to the right hash sequence of prestashop.
I've searched all over the internet for this but couldn't find a decent solution for logging in through the prestashop webservice. The script i've created for logging in is shown below.
require_once('./PSWebServiceLibrary.php');

/**
 * get information from PrestaShop
 */

$webService = new PrestaShopWebservice($url, $key, $debug);

$COOKIE_KEY = '_key';
$email = $_REQUEST['email'];
$password = md5('_key' . $_REQUEST['password']);

// The database hash for testing (random)
$passwordString = '$2y$10$UsYrIFQUOr5LBUZBoqSdxODuhbToEc.2QEqfAVB1r\/fhO5EfOyO96';

$opt = array(
    'resource'       => 'customers',
    'filter[email]'  => '['.$email.']',
    'display' => '[email,lastname,firstname, passwd]'
);

$result = ($webService->get( $opt ));

$json = json_encode($result);

$optUser = array(
    'resource'       => 'customers',
    'filter[email]'  => '['.$email.']',
    'display' => '[email,lastname,firstname,passwd]'
);

$resultUser = ($webService->get( $optUser ));

$userResult = json_encode($resultUser);

// Check the email
function hasEmail($string, $email)
{
    return strpos($string, $email) !== false;
}

// Check the Password
function hasPassword($string, $password)
{
    return strpos($string, $password) !== false;
}

if(hasEmail($userResult, $email) == true and hasPassword($userResult, $password) == true)  {
    session_start();
    $_SESSION['user'] = $email;
    // redirect is kut.
    echo
        '<html>
         <head>
           <meta content="text/html; charset=utf-8">
         </head>
         </html>';
} else {
// Here, we use single quotes for PHP and double quotes for JavaScript
    echo '<script type="text/javascript">';
    echo 'alert("Wrong username or password!")';
    echo '</script>';
}

Small second question: How would i be able to run a -> go to url in the success statement, Currently the echo "<script></script>"; isn't working and since the header() can't be used i'm having some trouble redirecting on succes.
As always, Thanks in advance!

A: if PrestaShop version is 1.6, the function to encrypt customer passwords is Tools::encrypt($passwd). This method just do this:
return md5(_COOKIE_KEY_.$passwd);

So knowing the _COOKIE_KEY_ you must be able to generate the hash.
_COOKIER_KEY_ is defined in config/settings.inc.php
If PrestaShop version is 1.7, Tools is not used and maybe md5(_COOKIE_KEY_.$passwd) will not match. It is used crypto from Symfony.
However, I guess PrestaShop webservice must have something to check users, in Customer class there is the method getByEmail(...) that is used in both 1.6 and 1.7 versions.
Regards.

A: To generate the cookie key prestashop uses:
array('_COOKIE_KEY_', Tools::passwdGen(56)),
array('_COOKIE_IV_', Tools::passwdGen(8)),

So that cookie key is different everytime. In order to verify if the password is good you should get existing password from database and compare with your user-submitted password:
//CHECK IF THE GIVEN EMAIL MATCHES A ROW IN OUR LEGACY TABLE AND RETRIEVES THE LEGACY PASSWORD
$resultZC = Db::getInstance()->getRow('
SELECT `password`
FROM `zc_legacy_passwords`
WHERE `email` = \''.pSQL($email).'\'
AND `updated` = 0');

 if (!$resultZC)
return false; //<- EMAIL NOT FOUND IN NONE OF THE TABLES, SO IT IS AN INVALID LOGIN

//ENCRYPTS THE GIVEN PASSWORD IN ZEN-CART / OSCOMMERCE FORMAT
$salt = substr($resultZC['password'], strrpos($resultZC['password'],':')+1, 2);
$ZCpassword = md5($salt . $passwd) . ':' . $salt;

if ($ZCpassword != $resultZC['password'])
return false; //<- WRONG ZEN-CART/OSCOMMERCE PASSWORD GIVEN

This is the part that you're asking for:
//ENCRYPTS THE GIVEN PASSWORD IN ZEN-CART / OSCOMMERCE FORMAT
$salt = substr($resultZC['password'], strrpos($resultZC['password'],':')+1, 2);
$ZCpassword = md5($salt . $passwd) . ':' . $salt;

where $resultZC['password'] is the password stored in the database and, $passwd is your password


text:
Q: Passing radio value with angularjs I have a form that has a set of radio buttons (3 choices), and I am using angular and the ng-repeat directive to populate the html:
<div ng-repeat="fruit in fruitbasket">
  <input type="radio" name="fruit" data-ng-model="fruit.isSelected">{{fruit.id}}
</div>

the inside of the controller for the fruit basket looks like this:
$scope.fruitbasket = [{isSelected: false, id: "Orange", value: "1"}, {isSelected: true, id: "Pear", value: "2"}, {isSelected: false, id: "Apple", value: "3"}]

The choices in the view are Orange, Pear, and Apple, but after one is selected I want to pass the numeric "value"
Not sure how to do this in angular, I have tried several things, but non successful.  Each time the passed value shows as nil
How does a connected element of an object get passed from a radio button in Angularjs?

A: Here's how you do it:

*

*isSelected is not needed. The fruitbasket is not part of your model, only the selected fruit is.
$scope.fruitbasket = [
    {id: "Orange", value: "1"},
    {id: "Pear", value: "2"},
    {id: "Apple", value: "3"}
];

$scope.model={selectedFruit:2};

*Assign the value (fruit.value) to each option and bind it to your model (model.selectedFruit)
<input value="{{fruit.value}}" data-ng-model="model.selectedFruit" type="radio" name="fruit" > {{fruit.id}}

Check out this working plnkr example.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Unable to Import Key Vault Certificate in Azure Government Cloud I am trying to import a certificate from a Key Vault to an App Service to configure SSL in the Azure Government Cloud. When I do this I get an error stating:
Failed to get App Service Service principal details.
I am getting a similar error when I try to do this through an ARM template which it what caused me to try this manually. I have tried giving my App Service a managed identity and giving that identity access to the key vault. I have tried a technique that worked in the regular Azure Cloud of giving "Microsoft Azure App Service" account permission to the key vault but that doesn't seem to exist in the Government Cloud.
I would have expected this to simply work and allow me to configure my SSL correctly on the app service so I don't need to manage the certificates individually on every app service.

A: You have to enable in the Identity of your app services that can be assigned through the azure permissions, then you have to go to the KeyVault and grant the permissions to the App Services.
https://learn.microsoft.com/en-us/azure/app-service/media/app-service-managed-service-identity/msi-blade-system.png
More information:
https://learn.microsoft.com/en-us/azure/app-service/overview-managed-identity
https://learn.microsoft.com/es-es/azure/key-vault/tutorial-net-create-vault-azure-web-app
https://azure.microsoft.com/en-us/resources/samples/app-service-msi-keyvault-dotnet/

A: I eventually found the solution to the issue.
Following the directions found here:
https://github.com/Azure/azure-quickstart-templates/tree/master/201-web-app-certificate-from-key-vault
I tried to authorize the 'Microsoft.Azure.WebSites' Resource Provider as described in the link, but that GUID doesn't exist in the Government Cloud.
This link however does give you the equivalent GUID for the Government Cloud:
https://github.com/MicrosoftDocs/azure-docs/blob/master/articles/azure-government/documentation-government-services-webandmobile.md#app-services
After using the script from the first link with the GUID value from the second link I was able to get both deployments and manual SSL added.


text:
Q: noConflict in Coffeescript? I have the following JavaScript for a datepicker in my rails application but I want to use coffeescript and I am wondering how to implement no conflict on this function in coffeescript?
<script>
var $j = jQuery.noConflict();
$(function(){
  $('#datepicker').fdatepicker({
    initialDate: '02-12-1989',
    format: 'dd-mm-yyyy',
    disableDblClickSelection: true
  });
});
</script>

Also the above works but I have to refresh the page before it does. Any advice on both? Thanks.

A: Here's what it might look like in CoffeeScript.
$j = jQuery.noConflict()
$ ->
  $('#datepicker').fdatepicker
    initialDate: '02-12-1989'
    format: 'dd-mm-yyyy'
    disableDblClickSelection: true
  return

When it runs in the browser it's still running as JavaScript so the functionality jQuery.noConflict() offers is still going to be there.


text:
Q: Rewrite does not seem to be recognizing my regex I have this in my htaccess:
RewriteEngine on
RewriteBase /myTest

RewriteRule    ^/members/.+$    /members.php?a=$1

It's basically supposed to rewrite members.php?a=login to work with /members/login but it doesn't seem to be working. Is there something I'm doing wrong?
Not sure if this is worth mentioning but I'm running on port 81

A: Use this:
RewriteEngine on
RewriteRule ^members/(.+)$ members.php?a=$1


text:
Q: Local Plugin permission issue not apply on course manager specifically - Moodle I am new in Moodle and i have a task to create local plugin with course manager role. In my system i have bulk of users in specific course and they are categories in different roles. Some of are bind with students and rest of are Managers. For my case i have received request from the client to make a local plugin which generate multiple reports against student records. I have successfully made the plugin but the condition is this plugin only can access those one who has enrolled in course as a Manager. I m trying with following code which i share you in below but no success. right now only admin can access local plugin rest of are received error messages from the moodle state.
["Sorry, but you do not currently have permissions to do that Project view "]
No idea how it will be resolved.
Please advise.
local/project/db/access.php
defined('MOODLE_INTERNAL') || die();

$capabilities = array(

    'local/project:view' => array(
        'riskbitmask' => RISK_PERSONAL,
        'captype' => 'read',
        'contextlevel' => CONTEXT_SYSTEM,
        'archetypes' => array(
            'manager' => CAP_ALLOW
        ),
    'local/project:manage' => array(
        'captype' => 'write',
        'contextlevel' => CONTEXT_SYSTEM,
        'archetypes' => array(
            'manager' => CAP_ALLOW
        )
    )
    )
);

local/project/header.php
require(dirname(__FILE__).'/../../config.php');
global $DB;
//Get the system context
$url = new moodle_url('/local/project/index.php');

require_login();
require_capability('local/project:view', context_system::instance());

A: I have successfully achieved the target against moodle permission. I have used has_capability method with course context and check authenticity with require_capability. Following procedure only work with admin and manager other would not access until when they get full rights from the site administration.
local/project/db/access.php
defined('MOODLE_INTERNAL') || die();

$capabilities = array(

    'local/project:view' => array(
        'riskbitmask' => RISK_SPAM,
        'captype' => 'write',
        'contextlevel' => CONTEXT_COURSE,
        'archetypes' => array(
            'manager' => CAP_ALLOW,
        ),
    )
);

local/project/header.php
require(dirname(__FILE__).'/../../config.php');
require_login();

//Get the system context
$context = context_course::instance($course_id);

if (!has_capability('local/project:view', $context)) {
    require_capability('local/project:view', $context);
}

A: There is no standard Moodle role called 'Course manager'.
There is a role called 'Manager' ('manager') and another called 'Course creator' ('coursecreator').
If you have debugging enabled you might get some extra warning messages if there is anything wrong with the code (e.g. if you have not run the install/upgrade process to create the capabilities or if you have not increased the plugin version number after creating the capabilities).


text:
Q: Is there any way to update a label in C# without using a timer? I am trying to make a label update automatically, but since in Windows Phone 8.1 Silverlight I can't use a timer, I have to do it in a different way.

A: use the Task or Threading something like this
private async Task ChangeLabel()
{
   while(true)
   {
      await Task.Delay(100)
      label1.Text = "lorem impus";
   }
}

A: Yes, here is a in depth example
label.Text = "Your text here";


text:
Q: ExtJS - Hiding ComboBox based on other Combo value I'm having a weird issue where I'm defining a combo has hidden:true, which works fine, but when I show the combobox and select a value from it, it hides. Here's some example code:
(I'm using some custom extended ComboBox's, but that's not the issue)
First ComboBox:
var bulkImportType = {
    xtype: 'ibwComboLocal',
    fields: ['id', 'name'],
    data: [[1, '3rd Party Tag'], [2, 'Image'], [3, 'Template']],
    fieldLabel: 'Type',
    listeners: {
        'select': function(combo, record, index) {
            if (record.get('name') == 'Template') {
                this.bulkImportTemplateCombo.show();
            } else {
                this.bulkImportTemplateCombo.hide();
            }
        }, scope: this
    }
};

Second ComboBox (shown only when the first Combo == Template)
var bulkImportTemplate = {
    xtype: 'ibwComboJson',
    hidden: 'true',
    url: 'http://itads-dl06.tweb.aol.com:3080/IBW/templates?returnJson=1',
    ref: '../bulkImportTemplateCombo',
    root: 'templateList',
    fieldLabel: 'Template'
};

The hiding/showing works fine, but it seems that when I select a value from the "Template" dropdown box, it re-fires the config and hides the combobox. Selecting a value from other combo's in the form seems to do the same thing, but ONLY the ones that are remote calls (from a URL that returns JSON for the combo).
Any fixes for remote combo's "resetting" form configs?
EDIT: All code for ComboBox's. All of these are just rendered inside a FormPanel.
var inventorySelectDropdown = {
    xtype: 'ibwComboLocal',
    fields: ['id', 'name'],
    data: [[1, 'O&O'], [2, 'Network']],
    value: 1, // set to O&O by default
    fieldLabel: 'Inventory'
};

var bulkImportType = {
    xtype: 'ibwComboLocal',
    fields: ['id', 'name'],
    data: [[1, '3rd Party Tag'], [2, 'Image'], [3, 'Template']],
    fieldLabel: 'Type',
    listeners: {
        'select': function(combo, record, index) {
            if (record.get('name') == 'Template') {
                this.bulkImportTemplateCombo.show();
            } else {
                this.bulkImportTemplateCombo.hide();
            }
        }, scope: this
    }
};

var bulkImportTemplate = {
    xtype: 'ibwComboJson',
    hidden: 'true',
    url: 'xxx',
    ref: '../bulkImportTemplateCombo',
    root: 'templateList',
    fieldLabel: 'Template'
};

var vendorDropdownBulk = {
    xtype: 'ibwComboJson',
    url: 'xxx',
    root: 'vendorList',
    fieldLabel: 'Vendor'
};

var bulkImportUploadField = {
    xtype: 'fileuploadfield',
    fieldLabel: 'Select Import File',
    width: 400
};

A: In the 'select' listener's if loop, after the show() function call, add the following statement:
this.bulkImportTemplateCombo.setVisible(true)


text:
Q: Can't run Venv in VsCode For the last 3 days, I have been trying to set up virtual Env on Vs Code for python with some luck but I have a few questions that I cant seem to find the answer to.

*

*Does Vs Code have to run in WSL for me to use venv?

*When I install venv on my device it doesn't seem to install a Scripts folder inside the vevn folder. Is this out dated information or am I installing it incorrectly. I am installing onto Documents folder inside my D: drive using python3 - m venv venv. The folder does install and does run in WSL mode but I am trying to run it in clear VsCode so I can use other add-ons such as AREPL that doesn't seem to like being ran in WSL.

For extra context I have oh-my-ZSH set up and using the ubuntu command line on my windows device. Any information will be helpful at this point because I am losing my mind.
venv folder in side D: drive
result

A: If you have the python extension installed you should be able to select your python interpreter at the bottom.

You should then be able to select the appropriate path

A: Run Set-ExecutionPolicy Unrestricted -scope process before activating virtual environment.
All the best

A: You don't have to create a virtual environment under WSL, it will work anywhere. But the reason you don't have a Scripts/ directory is because (I bet) you're running VS Code with git bash and that makes Python think you're running under Unix. In that case it creates a bin/ directory. That will also confuse VS Code because the extension thinks you're running under Windows.
I would either create a virtual environment using a Windows terminal like PowerShell or Command Prompt or use WSL2.


text:
Q: ribbon controls How do I enable ribbon buttons which are disabled after clicking the more commands button in a quickaccessbar using Delphi?

A: This is a known bug
Quality Central report 70342:

When using Ribbon Controls, if one
  adds a quick access toolbar, and then
  at runtime chooses "More Commands" to
  customize the quick access toolbar,
  many (although not always all)  of the
  action components in various ribbon
  groups will become permanently
  disabled.

Please see the report itself for more information:
http://qc.embarcadero.com/wc/qcmain.aspx?d=70342
The report is still open, so I it may not have been solved in D2011 either, but Quality Central could be lagging behind a bit.
Update
The report states there is no work around, but Jack Sudarev posted one in the comments:
procedure TForm6.ActionManager1StateChange(Sender: TObject);
begin
UpdateActions(ActionManager1);
end;

procedure TForm6.UpdateActions(ActionManager: TActionManager);
var
  i: Integer;
begin
  if not Assigned(ActionManager) then
    Exit;

  for i := 0 to ActionManager.ActionCount - 1 do
  begin
    (ActionManager.Actions[i] as TAction).Enabled := False;
    (ActionManager.Actions[i] as TAction).Enabled := True;
  end;
end;

A: This is what i did:
procedure TmainTranslatform.MyUpdateActions(ActionManager: TActionManager);
var
  i: Integer;
begin
  if not Assigned(ActionManager) then
    Exit;

  for i := 0 to ActionManager.ActionCount - 1 do
  begin
  if (ActionManager.Actions[i] is TFileOpen)  then
  begin
    (ActionManager.Actions[i] as TFileOpen).Enabled := False;
    (ActionManager.Actions[i] as TFileOpen).Enabled := True;

  end;
  if (ActionManager.Actions[i] is TAction)  then
  begin
    (ActionManager.Actions[i] as TAction).Enabled := False;
    (ActionManager.Actions[i] as TAction).Enabled := True;
  end;
  end;
end;


text:
Q: How to allocate static storage dynamically in c? In a recursive method to group the external nodes of a tree, i need to allocate memory dynamically inside that function.But the statement
static node* ext_node = malloc (sizeof(node));

is not working, and compiler gives error,which says

initializer element is not constant.

In short i want to ask that how can i use the static keyword with a pointer in a recursive call when the memory to which the pointer is pointing is dynamically acquired?
I require this because, when it is required to add more element in the list, the method insert_to_end (node*) will take the responsibility of allocating the storage for new node, so with this i can create list of any length and that is too with exact memory requirement.
But how to achieve this in c language?

A: Note that in general using static in a recursive function is a mistake (and is also thread-unsafe). It is almost always better to pass required data into the function via parameters.
However, if you insist, you can do it this way:
static node* ext_node;
if (ext_node == NULL) ext_node = malloc (sizeof(node));

That error doesn't make sense

A C compiler will initialize static variables at compile time (this requirement was relaxed in C++, and your original code will compile with a C++ compiler).
You can do this:
static int foo;  // default initialized to 0
static int bar = 42;

but not this:
static int baz = some_func();  // Error: at compile time the value to put into baz is not known.

A: If you really need to do so, just split it into 2 operations, like this:
static node *ext_node;

if (ext_node == NULL)
    ext_node = malloc(sizeof(node));

But it looks like flawed design for me (usually using static variables inside functions  is a bad practice -- makes function not reentrable).
Why don't pass this ext_node to your function, as a parameter? And why are you need to do this variable static in the first place?


text:
Q: Prevent "show" event to trigger of "tabs" widget on page load in JQuery I am using tabs widget of jquery to display some content. It works ok but I need tabs to show first tab content but not trigger "show" event when page loads. Later it should trigger show event when I change tabs. Is this possible?
Edit: Problem solved
Ok I solved my problem but let me explain what I was trying to do.
My tabs were in a container and I was using .animate() to adjust css top value according to the height of my selected tab content to keep everything in the middle of the page. But on page load, I want to show content of first tab but not animate so the code below didn't work because it triggers show event when page loads.
$( ".tabs" ).tabs({
   show: function(event, ui) { animatemycontainer() }
});

But this code does what I need. It simply binds show event after tabs are created so it doesn't trigger show event on page load.
$( ".tabs" ).tabs();
$(".tabs").bind("tabsshow", function(event, ui) {
    animatemycontainer();
});

A: $( ".selector" ).tabs({ selected: -1 });

I googled and found the documentation here: jQuery


text:
Q: How to "rollout" Kubernetes Deployment to a previous revision using "rollingUpdate" strategy? I'm using K8s Deployment API. When applying update I use RollingUpdate strategy and works perfectly.
However when I do "rollout undo", k8s kills all of the pods and create new ones, i.e. the rollback is disruptive.
Is there a way to configure "rollout undo" to use a RollingUpdate (to previous version) as well?

A: Rollback should use the same strategy you specified (i.e. RollingUpdate). The behavior you saw isn't expected. Can you provide the configuration (yaml/json) of your Deployment?


text:
Q: How to determine the pthread utilized memory Any given point of time, how can i get the memory size utilized by each thread?

A: You can't, the heap is shared between all threads in the process.

A: If all you want is a heap profiler consider Google performance tools with their own allocator TCMalloc.
http://code.google.com/p/google-perftools/
An alternative high performance allocator is jemalloc which provides statistics reporting including per-thread cache bin details with malloc_stats_print()
http://www.canonware.com/jemalloc/index.html

A: To check the thread's stack size you could use non-portable GNU extension pthread_getattr_np
and also you could check /proc/self/maps (or  /proc/PID/maps) but this way is more complex.


text:
Q: What can cause cutting of the slash in the url? Let's say I have url similar to this:
https://sprerererer.blablabla.systems/confirm-reservation/5cbe0e49e611ac1f06b39342a9b35c93a69cef6f8fbe6136752af4c8fe86eb64323031382d31312d31392031313a30303a3434

(due to security reasons, it's not my real url)
If I paste it to chrome it redirects me to:
https://sprerererer.blablabla.systemsconfirm-reservation/5cbe0e49e611ac1f06b39342a9b35c93a69cef6f8fbe6136752af4c8fe86eb64323031382d31312d31392031313a30303a3434

cutting of the slash at the end of domain. I never encountered anything like it. What can cause it? Is it chrome? Is it my server's fault?


text:
Q: Loading a string ot a JTable column I have a problem filling my JTable with values I have stored in a string.
The string has the form:
String factor = {"UMIN2\nT_UMIN2\nUMIN1\nT_UMIN1\nUMAX1\nT_UMAX1\nUMAX2\nT_UMAX2"};

and the code for the Jtable looks like:
    int len = factor.split("[\n\r]").length;
    final String[] columnNames = {"Factor", "Tol, min", "Exp, min", "Exp, max", "Tol, max", "Test 1", "Test 2", "Test 3", "Test 4", "Test 5", "Test 6", "Test 7", "Test 8", "Test 9", "Test 10"};
    final Object[][] data = {{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},        };
    model = new DefaultTableModel(data, columnNames);
    model.setRowCount(len);
    table = new JTable(data, columnNames);
    table.setModel(model);

    for(int x = 0; x < len; x++) table.setValueAt(factor,x,0);

    JTableHeader header = table.getTableHeader();
    header.setFont(new Font("Times New Roman", Font.BOLD, 13));
    header.setBackground(Color.black);
    header.setForeground(Color.white);

    JScrollPane scrollPane = new JScrollPane(table);
    scrollPane.setSize(988, 618);
    scrollPane.setFont(new Font("Times New Roman", Font.BOLD, 13));
    scrollPane.setLocation(10, 60);
    getContentPane().add(scrollPane);

What I am getting looks like:
[   **factor**   ]
[ UMIN2T_... ]
[ UMIN2T_... ]
[ UMIN2T_... ]
[ UMIN2T_... ]
[ UMIN2T_... ]
[ UMIN2T_... ]
[ UMIN2T_... ]
[ UMIN2T_... ]

However what I am looking for is that every newline entry gets its own box so that i looks like:
[ **factor** ]
[ UMIN2  ]
[ T_UMIN2]
[ UMIN1  ]
[ T_UMIN1]
[ UMAX1  ]
[ T_UMAX1]
[ UMAX2  ]
[ T_UMAX2]

Right now I am using the setValueAt function.
I have also tried to alter the height of the box and have all data in only one dox, this Works fine however, I need the individual boxes because I later on have to color them according to other data in the table.
Thanks for your help.

A: You have to split factor and set each token to each row.
    int row = 0;
    for (StringTokenizer stringTokenizer = new StringTokenizer(factor, "\n"); stringTokenizer.hasMoreTokens();) {
        String token = stringTokenizer.nextToken();
        table.setValueAt(token, row++, 0);
    }


text:
Q: Directive on ng-repeat images only pulls information about the first image My intention is to dynamically add a class based on the height and width so that it will fit inside of a div. This directive here is pulling the height and width, then adds the class. The problem I am running into is that it takes the information for the first image and uses that data to add classes to all the rest. So all images are returned with 'portrait-image' even though they need 'landscape-image'.
Here's my directive
function dynamicImageDirective(){
    return {
        restrict: 'A',
        link: function(scope, elem, attr) {
            elem.on('load', function() {
                setTimeout(function(){
                    var w = $(this).width(),
                        h = $(this).height();
                    if (w > h) {
                        elem.addClass('landscape-image');
                    } else {
                        elem.addClass('portrait-image');
                    }
                },0);
            });
        }
    };
}

And the repeat:

A: I was able to get it working by changing it to 'bind' instead of 'on load'.
function dynamicImageDirective(){
    return {
        restrict: 'A',
        link: function(scope, elem, attr) {
            elem.bind('load', function() {
                var w = this.width;
                var h = this.height;
                if (w > h) {
                    $(this).addClass('landscape-image');
                } else {
                    $(this).addClass('portrait-image');
                }
            });
            elem.bind('error', function(){

            });
        }
    }
}


text:
Q: Hash collect Ruby23 --> Ruby27 and Rails 5.2 --> Rails 6.1 giving wrong element type nil at 0 (expected array) I am upgrading Ruby and Rails version for some code package.
I have the following code block that is giving me error of wrong element type nil at 0 (expected array) .
def some_method(var1)
    address_to_field_mapping = { 'name' => 'name'
      'countryCode' => 'countryCode'
    }
# following line errors:
    fields = Hash[address_to_field_mapping.collect{|k,v| [v, var1[k]] unless var1[k].nil?}]
    return {'fields' => fields}
  end

I am not familiar at all with Ruby/Rails, can someone explain what the highlighted line means , and what is actually causing this error ? fields = Hash[address_to_field_mapping.collect{|k,v| [v, var1[k]] unless var1[k].nil?}]

A: This looks like an insanely overcomplicated way of writing:
def some_method(var1)
  { 'fields' => var1.slice('name', 'countryCode').compact }
end

This returns a hash containing the 'name' and 'countryCode' fields if they are not nil. Or at least it would have been if it wasn't broken.
I'm guessing the person writing it didn't know Ruby (hinted by the unnessicary return) yet was very concerned with job security.
So lets break it down:
address_to_field_mapping.collect{|k,v| [v, var1[k]] unless var1[k].nil?}

Hash#collect is an alias of map and loops across the keys and values of an array and returns an array consisting of the return values of the block. The return value here is an array of pairs ['name', 'bob'] or nil. The latter part being where it goes tits up.
Hash[] is a special hash constructor that takes an array of pairs:
irb(main):001:0> Hash[[[foo: 1], [bar: 2], [baz: 3] ]]
=> {{:foo=>1}=>nil, {:bar=>2}=>nil, {:baz=>3}=>nil}

But if you throw a nil in there it blows up.
irb(main):002:0> Hash[[[foo: 1], [bar: 2], nil ]]
(irb):2:in `[]': wrong element type nil at 2 (expected array) (ArgumentError)

Which could have been fixed by using .compact to remove the nils:
def some_method(var1)
  address_to_field_mapping = { 'name' => 'name'
      'countryCode' => 'countryCode'
  }
  fields = Hash[address_to_field_mapping.collect{|k,v| [v, var1[k]] unless var1[k].nil?}.compact]
  {'fields' => fields}
end


text:
Q: Multiple Regression Alternative In the text on multiple regression I am reading, it gives an example of %BODYFAT as a function of HEIGHT and WAIST SIZE. It is a good example of a multiple regression because controlling for the variable of WAIST SIZE means HEIGHT has an effect on %BODYFAT.
My question is why not run a regression of %BODYFAT on WAIST SIZE/HEIGHT ratio so it becomes proportional and there is no need to control for variables.
Do simple solutions like this exist for many multiple regression analysis? If so can someone explain why multiple regression would be better than the solution I proposed above.

A: There is nothing stopping you from fitting the second model you described, if the theory or prior empirical research supports it.  Your model covariates are limited only by your imagination and how you want to interpret the parameter estimates.  However, your second model is not a "substitute" or "alternative" to multivariate modeling, as the interpretation of the parameters differ between the two.  Consider the models you described above:
$PctBodyFat_i=\beta_0+\beta_1Height_i+\beta_2WaistSize_i+\epsilon_i$ (1)
and
$PctBodyFat_i=\delta_0+\delta_1WaistHeightRatio_i+\nu_i$  (2)
In Model 1, $\beta_1$ is interpreted as the expected change in $PctBodyFat$ corresponding to a one unit increase in $Height$ after controlling for $WaistSize$.  Meaning, among people of the same $WaistSize$, what is the average (expected) change we see in $PctBodyFat$ when $Height$ increases by one unit.  Similarly, $\beta_2$ is the expected or average change in $PctBodyFat$ corresponding to an increase in $WaistSize$, all other things equal. That is what "controlling for" means, holding all other values constant and changing only one parameter at a time.  In Model 2, on the other hand, the interpretation of $\delta_1$ is, the expected change in $PctBodyFat$ corresponding to a one unit increase in waist-to-height ratio.  Do you see how these two models are not equivalent?
Here's a worked example based on what you described above using Body Fat Data.  I used Stata in this example.  I also converted height to cm so everything would have the same unit of measurement.
. *model 1 multivariate
. reg pctbodyfat heightcm waistsize

      Source |       SS       df       MS              Number of obs =     252
-------------+------------------------------           F(  2,   249) =  274.24
       Model |  12090.3059     2  6045.15297           Prob > F      =  0.0000
    Residual |  5488.68364   249  22.0429062           R-squared     =  0.6878
-------------+------------------------------           Adj R-squared =  0.6853
       Total |  17578.9896   251   70.035815           Root MSE      =   4.695

------------------------------------------------------------------------------
  pctbodyfat |      Coef.   Std. Err.      t    P>|t|     [95% Conf. Interval]
-------------+----------------------------------------------------------------
    heightcm |  -.1458789   .0319761    -4.56   0.000     -.208857   -.0829009
   waistsize |   .6423569    .027589    23.28   0.000     .5880194    .6966944
       _cons |  -14.31075   6.042646    -2.37   0.019    -26.21196   -2.409532
------------------------------------------------------------------------------

$Height$ and $WaistSize$ are both statistically significant at p<0.001 in this example, with a 1 cm increase in $Height$ expected to decrease $PctBodyFat$ whilst a 1 cm increase in $WaistSize$ expected to increase $PctBodyFat$.
So far so good.  Now here's the output from Model 2 where a waist to height ratio was entered instead of height and weight separately:
. *model 2 ratio
. reg pctbodyfat wthratio

      Source |       SS       df       MS              Number of obs =     252
-------------+------------------------------           F(  1,   250) =  214.53
       Model |  8118.31801     1  8118.31801           Prob > F      =  0.0000
    Residual |  9460.67157   250  37.8426863           R-squared     =  0.4618
-------------+------------------------------           Adj R-squared =  0.4597
       Total |  17578.9896   251   70.035815           Root MSE      =  6.1516

------------------------------------------------------------------------------
  pctbodyfat |      Coef.   Std. Err.      t    P>|t|     [95% Conf. Interval]
-------------+----------------------------------------------------------------
    wthratio |     69.829   4.767533    14.65   0.000     60.43935    79.21864
       _cons |  -17.28263   2.517475    -6.87   0.000    -22.24079   -12.32447
------------------------------------------------------------------------------

Again, waist-to-height ratio is highly statistically significant in Model 2.  The reason the coefficient is so huge is because waist-to-height ratio is less than 1 for most people, so a 1-unit increase in waist-to-height ratio can be expected to produce a fairly large magnitude in change for $PctBodyFat$.  If you're uncomfortable with the large coefficient, you can multiply waist-to-height ratio by 100 and your model coefficient will be divided by 100 (i.e., 0.69829), but it's a matter of preference and what makes sense.  What is interesting to note here is that Model 1 appears to have a better fit than Model 2 based on the adjusted R-squared values.
After fitting a regression model, we can predict outcome values for observations based on certain characteristics.  Suppose we want to know what the predicted values are from each of the 2 models for people with these characteristics.
$$
\begin{array}{phwws}
Person & Height & WaistSize & WaistHeightRatio \\
\hline
A & 170 & 80 & .47058824  \\
B & 152 & 80 & .52631579 \\
\end{array}
$$
From model 1, we expect the following percentage body fat for the 2 hypothetical cases above:
. margins, at(heightcm==170 waistsize==80)

Adjusted predictions                              Number of obs   =        252
Model VCE    : OLS

Expression   : Linear prediction, predict()
at           : heightcm        =         170
               waistsize       =          80

------------------------------------------------------------------------------
             |            Delta-method
             |     Margin   Std. Err.      t    P>|t|     [95% Conf. Interval]
-------------+----------------------------------------------------------------
       _cons |   12.27839    .509845    24.08   0.000     11.27423    13.28254
------------------------------------------------------------------------------

. margins, at(heightcm=152 waistsize=80)

Adjusted predictions                              Number of obs   =        252
Model VCE    : OLS

Expression   : Linear prediction, predict()
at           : heightcm        =         152
               waistsize       =          80

------------------------------------------------------------------------------
             |            Delta-method
             |     Margin   Std. Err.      t    P>|t|     [95% Conf. Interval]
-------------+----------------------------------------------------------------
       _cons |   14.90421   .9258657    16.10   0.000     13.08068    16.72773
------------------------------------------------------------------------------

We expect Person A to have a percent body fat of 12.3 and person B to have a percent body fat of 14.9.  Now if we were to predict percent body fat for the same exact people using Model 2, we would get:
. margins, at(wthratio=(.47058824 .52631579))

Adjusted predictions                              Number of obs   =        252
Model VCE    : OLS

Expression   : Linear prediction, predict()

1._at        : wthratio        =    .4705882
2._at        : wthratio        =    .5263158

------------------------------------------------------------------------------
             |            Delta-method
             |     Margin   Std. Err.      t    P>|t|     [95% Conf. Interval]
-------------+----------------------------------------------------------------
         _at |
          1  |   15.57807   .4578963    34.02   0.000     14.67625     16.4799
          2  |   19.46947   .3881273    50.16   0.000     18.70506    20.23389
------------------------------------------------------------------------------

Using Model 2, both persons are expected to have higher percentage body fat than in Model 1, 15.6% and 19.5% for Person A and Person B, respectively.  To summarize
$$
\begin{array}{phwws}
Person & Height & WaistSize & WaistHeightRatio & E(PBF|Model_1) &E(PBF|Model_2)\\
\hline
A & 170 & 80 & .47058824 &12.3 &15.6  \\
B & 152 & 80 & .52631579 &14.9 &19.5 \\
\end{array}
$$
Of course, as I stated above, there is no stopping you from entering your variables in the model every which way you like.  It all depends on the theory, your preference, and what you want your model parameters to mean as far as your research question is concerned.  If you have the relationships between the variables worked out beforehand and want to enter it that way, then great, but combining variables before entering into the model is still not an alternative to multivariate modeling.
As you say, this is a simple example.  In reality, there is probably no getting around multivariate modeling.  In fact, you may even lament the fact that you do not have enough variables to control for in your dataset, and you start worrying about endogeneity and other sources of bias in your model.


text:
Q: Duplicate Values - keep one of the values I have my excel workbook sorted in colors by duplicate values.
The excel document has all of the values of the duplicates selected, how do I keep one of the values instead of completely removing all of the duplicates, including the unique value.

A: in Excel 2007:
Data tab >> Remove Duplicates

A: Just select your data/column(s) and go to Data / Remove Duplicates Or
select data and press Alt + A, M.


text:
Q: A plan to mitigate PDU failures? A client just experienced a complete failure of an APC AP7911A switched/metered rack power distribution unit (PDU). This obviously took all of the connected equipment down with it. The equipment is fine, as well as the upstream UPS units.
In situations where it's not possible to balance devices across multiple power feeds/PDUs/UPS units (e.g. switches with single power supplies, lack of high-line power feeds, etc.), how do you mitigate failures like this? This was a single rack installation in a less-than-ideal computer room, but typical for most small/medium businesses. Should one plan for individual PDU failure, or is it just something that gets dealt with when it happens?

A: Multiple PSUs in servers are ok but not a magic bullet. Often when things to do with power go they take out other things around them eg. the backplane that your redundant psus both connect to.  Far more likely to keep running if you have two servers on seperate UPSs.
Best of all is to work in redundancy at your application or platform layer so that machines or racks can go out without it causing a problem but when you haven't got the budget for that you can still reduce the risk by having spares of any non redundant equipment ready to swap out, but also by keeping things simple.  A fancy managed PDU is far more likely to go down than a dumb power bar.
Also it is worth bearing in mind that many small businesses simply can't do things the proper way or choose to do things the cheapest way and live with the consequences if they happen.  I've seen inexperienced admins go out of their way to avoid doing things a certain way that have been slated around here or similar sites only to put something worse in place.  A less than ideal solution is often better than nothing.

A: I've been in exactly the same situation, where I've done my best to have redundancy across a cluster of servers, but the situation has been let down by the failure of one power source which in turn has caused a device that has only one PSU to fail.  Sometimes the single PSU device has been critical, like a backup DC, a switch or a rack cabinet fan array.
The best answer I've come up with is using an PDU with an **Automatic Transfer Switch ** (ATS). This allows you to link the PDU to two power sources and it will switch over between the two with no downtime if one fails.  This is ideal for your single PSU devices, obviously because they stay on.  The ATS switch typically has about 8 outlets so that it effectively takes the place of a PDU.
For typical SME scenarios where you don't have two power circuits in the datacentre, but you may have a rack wired to either one UPS and the mains, or from mains through two UPSs, this provides good protection, otherwise you are always going to gamble on which PDU source is going to fail first.  I also think that these ATS switches are more resilient than standard PDUs so this further mitigates disaster.

A: As for legacy kit with a single PSU, as far as I know it's as you say, it's just something that gets dealt with when it happens, but definitely plan for it to happen.
I'd make a note of the kit which is set up like this if possible, and plan for the failure, and expect it at one point.
I'd suggest making sure backups are well planned and running well, and disaster recovery plans are well thought through and tested regularly.
When it comes round to buying new kit, I'd be buying buy those servers with dual PSU, and plugging each into a separate UPS (via PDU if necessary). Even cheap low-end Small-Medium business Dell servers can be bought with dual PSUs.

A: I'm in a slightly unusual situation as we have multiple datacentres that are our own and we get to decide how things work, and we use blades, but in general we have half our PSUs go to one PDU and the other half go to another PDU for exactly this reason. Now typically both PDUs are on the same very large PDU/UPS each of which serves multiple half row of 40 racks. So we split our clusters along rows, i.e. cluster member 1 in one of the first 20 racks of the first row, number 2 in the second 20 racks of the first row, number 3 in the first 20 racks of the second row etc. This way we're covered if we lose a PSU, PDU, large-PDU/UPS or whole row (through flooding, fire etc.). But as I say this is I guess a little unusual but hopefully some insight into how we do it, I'd always suggest different PDUs but make sure if you use multiple central/large PDUs and UPSs that you're not getting phases too far out for safety reasons (search SF for previous cross-phase arguments :) )

A: If you can't install a second PDU in the rack, you have no other options than setting up your server in such a way that sudden power losses do only minimal damage.

*

*First of all, I'd make sure to use battery-backed RAID controllers, so that the on-disk data will be consistent, or at least can be brought to a consistent state when power is restored.

*Second, use journaling filesystems. This helps keeping the filesystem consistent.

*Third, try to have all running services set up in such a way so that there's something akin to transactions: All data structures can be brought back to a consistent state, and accept a minimal data loss if necessary (Rollback). This varies greatly from service to service (Databases, Frequency of modifications, Logs...) and may or may not require quite a lot of handiwork on your side. If it's possible at all...

*Fourth, adjust your backup strategy accordingly and try to have more and smaller backups (instead of few and big ones).

But I need to be honest here, the first three won't give you 100% protection. Be prepared to restore from backup any time.


text:
Q: How can i get a popup window for my results? I dont know how to get the results into a popup window i tried a lot of things but nothing works. Can anyone help me? I want the erge and erge 1 to be in the new window. Here is my current code:
{n, p} = Input["Eingabe der Parameter in der Form {n,p}
   n=Größe der Stichprobe
   p=Wahrscheinlichkeit"];
Stichp4 = RandomVariate[BernoulliDistribution[p], n];
xquer = N[1/n \!\(
\*UnderoverscriptBox[\(\[Sum]\), \(i =
       1\), \(n\)]\(Stichp4[\([i]\)]\)\)];
pneu = xquer;
erge = Print["Geschätzter Parameter p = ", xquer]
erge1 = Print["Abweichung zum wahren Parameter p: ", Abs[pneu - p]]

Thanks in advance

A: You can arrange in the form of a button "Click to print" using PopupWindow[]:
{n, p} = Input["Eingabe der Parameter in der Form {n,p}
      n=Größe der Stichprobe
      p=Wahrscheinlichkeit"];
Stichp4 = RandomVariate[BernoulliDistribution[p], n];
xquer = N[1/n \!\(
\*UnderoverscriptBox[\(\[Sum]\), \(i =
       1\), \(n\)]\(Stichp4[\([i]\)]\)\)];
pneu = xquer;
PopupWindow[
 Graphics[{Red, Circle[], Inset["Click to print", {0, 0}]}],
 Grid[{{"Geschätzter Parameter p = ",
    xquer}, {"Abweichung zum wahren Parameter p: ", Abs[pneu - p]}}]]


text:
Q: Getting the rational function with given characteristics
The curve C has an equation
  $$y = \frac{ax^2+bx+c}{x+d},$$
  where $a$, $b$, $c$, and $d$ are constants. The curve cuts the $y$-axis at $(0,-2)$ and has asymptotes $x=2$ and $y = x + 1$.

From a previous part of the question, I have obtained $d = -2$. I am now asked to obtain the values of $a$, $b$ and $c$. Here is what I have done,
First, I would find $c$ since I know the curve cuts the $y$ axis at $(0,-2)$
$$\begin{align} \frac{a(0)^2+b(0)+c}{0-2} & = -2 \\
                        \frac{c}{-2}      & = -2 \\
                                       c  & = 4
\end{align}$$
I do not know what to do next to find $a$ and $b$ but I tried to substitute $y = x+1$ into the equation of the curve and compared the coefficients but that did not work. Could someone please guide me how to do so? I find questions like these unusual since my textbook only showed how to find the asymptotes and graph such functions.

A: Hint:
$$
\lim_{x \to \infty}\dfrac{ax^2+bx+4}{x(x-2)}=1
$$
and
$$
\lim_{x \to \infty}\left[\dfrac{ax^2+bx+4}{x-2}-(x+1) \right]=0
$$


text:
Q: SVN sub-changeset commit? I am using AnkhSVN in Visual Studio 2008 as a source control solution.  I love to check out, edit and then re-commit partial changes as a way to ensure I never lose incremental progress.  Is there anything smaller than a changeset that will allow me to check-in incremental changes as a way to ensure I don't lose them/overwrite them between changesets without having me creating 20 changesets in the process?

A: Not in SVN, but what you can do is layer GIT in front of SVN.  That way you can make a ton of local changes without having to push them up to SVN.  It is also useful in shops which don't make proper use of branching, you can isolate yourself from the pollution of mainline.  It also adds the ability to shelve changes in case you wnat to put some changes aside for later.  Check out
http://blog.tsunanet.net/2007/07/learning-git-svn-in-5min.html


text:
Q: Extract gurobi muti-dimensional variable value and form a numpy array I want to know that when I defined a multi-dimension variables in Gurobi, how can I extract all the value of the solution and organize them in to a Numpy array according to the original coordinate of the variable.
I have the following decision variables defined in Gurobi using Python API:
for i in range(N):
  for t in range(M):
      Station_Size[i,t] = m.addVar(ub=Q, name = 'Station_Size_%s_%s' %(i,t))
      for j in range(N):
         Admission[i,j,t] = m.addVar(ub = Arrival_Rate[t,i,j], obj=-1, name = 'Admission_Rate_%s_%s_%s' %(i,j,t))
         Return[i,j,t] = m.addVar(name = 'Return_Rate_%s_%s_%s' %(i,j,t))

I have the problem solved and I have three dictionary:
Station_Size, Admission and Return

I know that the solution can be accessed as:
Station_Size[i,t].X, Admission[i,j,t].X and Return[i,j,t].X

I want to creat three Numpy array such that:
Array_Station_Size[i,t] = Station_Size[i,t].X
Array_Admission[i,j,t] = Admission[i,j,t].X

I can definitely do this by creating three loops and creat the Numpy Array element by element. It's do-able if the loop doesn't take a lot of time. But I just want to know if there is a better way to do this. Please comment if  I did not make myself clear.

A: Assuming your model's name is m, do the following:
Array_Station_Size = m.getAttr('x', Station_Size)

which is a gurobipy.tupledict now.
see gurobi doc here
http://www.gurobi.com/documentation/8.1/quickstart_windows/py_results.html

A: I figured this problem out.
Do the following:
Array_Station_Size = np.array()
Array_Station_Size[i,] = [Station_Size[i,t].X for t in rang(T)]


text:
Q: Questions about the glht function for planned comparison I have a nested model with the following effects

*

*fixed: treatments

*random: experiment_date

I used lme() to model the data
mod1 <- lme(N_cells ~treatments-1, random=~1|experiment_date, method='ML')

Then I want to compare all the other treatments to the control (included in
the "treatments" in mod1). After a fair amount of searching around, I
decided to use glht() from the multcomp package (any other suggestions?).
lvl.treatments=table(treatments)
K = contrMat(lvl.treatments,type='Dunnett',base=1)
mc<-glht(mod1, linfct=mcp(treatments=K),alternative='greater')

But I got the following error:

Error in contr.treatment(n = 0L) :   not enough degrees of freedom to
  define contrasts

I tried to extract the df parameter using modelparm(), but the function
couldn't be applied to lme

Error in UseMethod("modelparm") :   no applicable method for
  'modelparm' applied to an object of class "lme"

The degree of freedom of the fixed effect was 194. I tried to specify the
number in glht(), but got the same error as "not enough degrees of freedom to
define contrasts".
Does anyone know what's happening and how I could possibly solve the
problem? Thank you so much.

A: If your treatments are factors (and not ordered factors), you could add the intercept into the model (i.e. remove the "-1") and just do summary(mod1)
The default contrasts, as set in options, is to use contr.treatment for factors.  This sounds like what you want.  contr.treatment means that each coefficient represents a comparison of that level with level 1 (omitting level 1 itself).
# view default contrasts in options
options("contrasts")
#$contrasts
#        unordered           ordered
#"contr.treatment"      "contr.poly"

When you do summary(mod1), the first level will not be labelled, but all the other levels will be in comparison to it.
If your control condition is not your first level, you need to use factor() with a levels argument or relevel() to make it first.


text:
Q: C: Does locking a pthread mutex place the thread in a FIFO queue? Lets say thread 1 has locked the mutex and does some work.
If thread 2 calls:
pthread_mutex_lock(&mutex);

Then thread 3 calls the same:
pthread_mutex_lock(&mutex);

Then thread 1 unlocks the mutex. Does FIFO (First In First Out) apply to the threads trying to lock the mutex?
If so, thread 2 would guaranteed be the next one to acquire the mutex.

A:
Does FIFO (First In First Out) apply to the threads trying to lock the mutex?

Nope, no FIFO is guaranteed.
See https://man7.org/linux/man-pages/man3/pthread_mutex_lock.3p.html:

If there are threads
blocked on the mutex object referenced by mutex when
pthread_mutex_unlock() is called, resulting in the mutex becoming
available, the scheduling policy shall determine which thread shall
acquire the mutex.

On Linux pthread mutex is implemented using futex and pthread_mutex_unlock() involves FUTEX_WAKE:

No guarantee is provided about which waiters are awoken (e.g.,
a waiter with a higher scheduling priority is not guaranteed
to be awoken in preference to a waiter with a lower priority).

A: It does depend on the prevailing scheduling policy. If it's SCHED_FIFO, then for each priority level there really is a fifo list of waiters, and indeed futexes make allowance for this (see futexes, section FUTEX_LOCK_PI). SCHED_FIFO tends to be the policy used for real time applications. The page on


text:
Q: What is the difference between $\mathcal B(E\times F)$ and $\mathcal B(E)\bigotimes\mathcal B(F)$
What is the difference between $\mathcal B(E\times F)$ and $\mathcal B(E)\bigotimes\mathcal B(F)$

I know the definition of $\mathcal B(E)\bigotimes\mathcal B(F)=\sigma\{A\times B:A\in\mathcal B(E), B\in\mathcal B(F)\}$
I heard that, $\mathcal B(E)\bigotimes\mathcal B(F)\subset\mathcal B(E\times F)$ with the following argument
$\pi_1:E\times F\to E$ and $\pi_2:E\times F\to F$ must be continuous, hence measurable. So if we endow these sets with the corresponding $\sigma$-algebras, we get for every $A\in\mathcal B(E),\ \pi_1^{-1}(A)\in\mathcal B(E\times F)$ and the same with the second projection, but what have we reached now, what has this to do with the definition above ?
Do you know an example, where the inclusion is strict, i.e. $\mathcal B(E)\bigotimes\mathcal B(F)\subsetneq\mathcal B(E\times F)$
I think i found it in the lecture notes, but the example is missing
http://imgim.com/img_20140404_143200.jpg (here the proposition, we need for the following lemma)
http://imgim.com/img_20140404_143214.jpg ( and the lemma, there's a typo in the lemma $f_2$ maps to $(F_2,\mathcal B_2)$)


text:
Q: Microservices authorization A microservice supposed to own its own data, no shared database.
A token includes the userid, clams, but claims are just authentication, not authorization.
So if I have a monolit application, I can check if the user is part of a group (claim), and if it is, I fetch from the database what that group is able to do.
But if I have a microservice, I can't do that, I don't want to replicate this authorization information into all of the microservices.
For example, all users belong to a team, and everything in service in the application belong to a team (for example, members of team "A" has access to forums of team "A", gallery of team "A", etc.
Even if I store the team in a claim (what I don't want, because membership can change while the token is still alive), I need to have team data in all microservices. But that sounds very bad.
So what can I do?
thanks

A: You should pass user token(that up read from claims) in request header through the chain of microservices such that each microservice just have to validate the token to determine the user has been successfully authenticated, and permission enforcement is done in the microservice itself.


text:
Q: Is there a way in Tkinter to left-align tabs (Notebook)? I use ttk.Notebook to create different tabs. The notebook is placed on the left side.
The labels in the tabs should not be aligned to the right, but to the left.
Can this be configured?
Right-aligned tabs:

Code Snippet:
import tkinter as tk
from ttkthemes import ThemedTk
import tkinter.ttk  as ttk

class MyApp(ThemedTk):
    def __init__(self, theme="arc"):
        ThemedTk.__init__(self, fonts=True, themebg=True)
        self.set_theme(theme)

        self.style = ttk.Style()
        self.style.configure('lefttab.TNotebook', tabposition='wn')
        current_theme =self.style.theme_use()
        self.style.theme_settings(current_theme, {"TNotebook.Tab": {"configure": {'background':'white', "padding": [10, 8]}}})

        self.nb = ttk.Notebook(self, style='lefttab.TNotebook')
        self.nb.grid(row=0, column=0, sticky='w')

        self.page0 = ttk.Frame(self.nb, width=500, height=300)
        self.page1 = ttk.Frame(self.nb, width=500, height=300)
        self.page2 = ttk.Frame(self.nb, width=500, height=300)

        self.style.configure("TFrame", background='white')

        self.nb.add(self.page0, text='Allgemein', sticky="nsew")
        self.nb.add(self.page1, text='Wand leicht', sticky="nsew")
        self.nb.add(self.page2, text='Wand schwer', sticky="nsew")

        self.ok = ttk.Button(self.page1)
        self.ok["text"] = "Button"
        self.ok["command"] = self.handler
        self.ok.grid(row=0, column=0)

    def handler(self):
        print("Button clicked")

if __name__ == "__main__":

    app = MyApp()
    app.geometry("500x300")
    app.mainloop()

A: Add some spaces in the text to match the length of longest label.


text:
Q: Just installed 14.04 LTS on new computer no ethernet I know the ethernet controller is : Qualcomm Atheros Device e0a1 (rev 10) from lspci, and I think the problem is that I have no network interface adapter.  I have no internet access on the computer, but I can download whatever on my laptop and move it over with an usb drive.  I already added the following lines to /etc/network/interfaces:
auto eth0
iface eth0 inet dhcp
but don't know what else to do.


text:
Q: Grouping columns based on multiple condition and concatenating strings I have the following pandas DataFrame:
import pandas as pd

df = pd.DataFrame({
    'name': ['John', 'Jack', 'John', 'Tim', 'John'],
    'city': ['New York', 'London', 'Paris', 'Berlin', 'New York'],
    'nickname': ['aaa', 'bbb', 'ccc', 'ddd', 'eee']
})

I'm trying to group based on the condition that if values in columns name and city are same we add the values in column nickname. Result for the above DataFrame should look like this:

I'm using the below groupby function but the values under nickname column aren't getting concatenated as they are strings.
df1 = df.groupby(['name','city'])['nickname'].apply(' '.join())

but the above code does not concatenate cell values in column nickname
Can anyone help?

A: Hello your code was correct you just need to apply the function join for every element in the column nickname, using the apply() method. (You gotta tell the join function what to join)
import pandas as pd

#i fixed your dataframe data dictionary was missing the " : " colon.

df=pd.DataFrame({'name':['John','Jack','John','Tim','John'],
                 'city':['New York','London','Paris', 'Berlin','New York'],
                 'nickname':['aaa','bbb','ccc','ddd','eee']})

df1 = df.groupby(['name','city'])['nickname'].apply(lambda x:' '.join(x)).reset_index()

A:
I use sort cause maybe is what you are looking for!

import pandas as pd

df = pd.DataFrame({
    'name': ['John', 'Jack', 'John', 'Tim', 'John'],
    'city': ['New York', 'London', 'Paris', 'Berlin', 'New York'],
    'nickname': ['aaa', 'bbb', 'ccc', 'ddd', 'eee']})
tmp = (df.groupby(['name', 'city'])['nickname']
           .agg(nickname = lambda s: sorted(s.unique()))
           .reset_index()
      )
df['nickname'] = tmp.nickname.str.join(' ')
df = df[df['nickname'].notna()]

Output
        name    city        nickname
0       John    New York    bbb
1       Jack    London      aaa eee
2       John    Paris       ccc
3       Tim     Berlin      ddd


text:
Q: Express - How do I pass data to the model without using query string parameters So, I have two controllers, authController and onboardingController. authController communicates with onboardingController with this line:
res.redirect('/onboarding/info?profileId=' + profile.id + '&emailAddress=' + profile.emails[0].value)
onBoardingController receives the query string parameters and transforms them into metadata that is accessible when rendering the corresponding page:
model.profile = { id: req.query.profileId, email: req.query.emailAddress };
res.render('onboarding/missingInfo', model);

Now, since model.profile in onboardingController doesn't know the context behind the actual profile data from the authController, I only thought of passing and receiving data through query strings. Is there any other way I can do this because having an email address in the URL makes it look wonky.
Edit: I've read that it's possible to use express sessions to do what I need.

A: You could create a POST request and send it in the body of the request (using axios, or the Fetch API).
Nice article of W3Schools about it


text:
Q: Wpf textblock partial background I need to set a marker on a derived (inherited) textblock that will give the user an indication whether text is Left Right or Center justified. Derived class has a property called justification which is an enum with Left Right and Centre values. So I want to change background color of the textBlock partially i.e. if it is Left Justified then 25% of background on the left is a different color. Length of the string in the text block can vary and is not static.
Putting the textblock in another element e.g. border is not an option but I am open to any other suggestions that can manipulate Textblock without changing its size to visually mark justification.

A: You could assign a LinearGradientBrush to the background and manipulate the colors and the offsets of the gradientstops.


text:
Q: Use __get__, __set__ with dictionary item? Is there a way to make a dictionary of functions that use set and get statements and then use them as set and get functions?
class thing(object):
    def __init__(self, thingy)
        self.thingy = thingy
    def __get__(self,instance,owner):
        return thingy
    def __set__(self,instance,value):
        thingy += value

theDict = {"bob":thing(5), "suzy":thing(2)}

theDict["bob"] = 10

wanted result is that 10 goes into the set function and adds to the existing 5
print theDict["bob"]
>>> 15

actual result is that the dictionary replaces the entry with the numeric value
print theDict["bob"]
>>> 10

Why can't I just make a function like..
    theDict["bob"].add(10)
is because it's building off an existing and already really well working function that uses the set and get. The case I'm working with is an edge case and wouldn't make sense to reprogram everything to make work for this one case.
I need some means to store instances of this set/get thingy that is accessible but doesn't create some layer of depth that might break existing references.
Please don't ask for actual code. It'd take pages of code to encapsulate the problem.

A: No, because to execute theDict["bob"] = 10, the Python runtime doesn't call any methods at all of the previous value of theDict["bob"]. It's not like when myObject.mydescriptor = 10 calls the descriptor setter.
Well, maybe it calls __del__ on the previous value if the refcount hits zero, but let's not go there!
If you want to do something like this then you need to change the way the dictionary works, not the contents. For example you could subclass dict (with the usual warnings that you're Evil, Bad and Wrong to write a non-Liskov-substituting derived class). Or you could from scratch implement an instance of collections.MutableMapping. But I don't think there's any way to hijack the normal operation of dict using a special value stored in it.

A: You could do it if you can (also) use a specialized version of the dictionary which is aware of your Thing class and handles it separately:
class Thing(object):
    def __init__(self, thingy):
        self._thingy = thingy
    def _get_thingy(self):
        return self._thingy
    def _set_thingy(self, value):
        self._thingy += value

    thingy = property(_get_thingy, _set_thingy, None, "I'm a 'thingy' property.")

class ThingDict(dict):
    def __getitem__(self, key):
        if key in self and isinstance(dict.__getitem__(self, key), Thing):
            return dict.__getitem__(self, key).thingy
        else:
            return dict.__getitem__(self, key)

    def __setitem__(self, key, value):
        if key in self and isinstance(dict.__getitem__(self, key), Thing):
            dict.__getitem__(self, key).thingy = value
        else:
            dict.__setitem__(self, key, value)

theDict = ThingDict({"bob": Thing(5), "suzy": Thing(2), "don": 42})

print(theDict["bob"])  # --> 5
theDict["bob"] = 10
print(theDict["bob"])  # --> 15

# non-Thing value
print(theDict["don"])  # --> 42
theDict["don"] = 10
print(theDict["don"])  # --> 10

A: theDict["bob"] = 10 is just assign 10 to the key bob for theDict.
I think you should know about the magic methods __get__ and __set__ first. Go to: https://docs.python.org/2.7/howto/descriptor.html Using a class might be easier than dict.


text:
Q: How to get cdata?
Possible Duplicate:
PHP: How to handle <![CDATA[ with SimpleXMLElement?

I have the following xml
<locale id="us">
    <toFieldLabel><![CDATA[YOUR FRIEND'S NAME]]></toFieldLabel>
</locale>

When I parse it with php's simple xml, I get the following result.
    $xml = simplexml_load_file("config.xml");

    echo '<pre>';
    print_r($xml);

[locale] => Array
    (
        [0] => SimpleXMLElement Object
            (
                [@attributes] => Array
                    (
                        [id] => us
                    )

                [toFieldLabel] => SimpleXMLElement Object
                    (
                    )
            )
    )

look at the 'toFieldLabel', it's empty!!
How do I get the value?!
Updated:
full xml
<?xml version="1.0" encoding="UTF-8"?>
<configuration>

    <locale id="us">
        <toFieldLabel><![CDATA[YOUR FRIEND'S NAME]]></toFieldLabel>
    </locale>

</configuration>


text:
Q: R - converting data frame to matrix, get different results when using head() I have a data frame that has around 78,000 rows and looks like this:
EmailAddress    Column1 Column2 Column3
abc1@gmail.com     1       0       0
abc2@gmail.com     0       0       0
abc3@gmail.com     1       1       0
abc4@gmail.com     1       1       0

I want to run a kmeans clustering on it using kcca() function.
I want to convert this data frame into a matrix but I want to keep column EmailAddress so that I can link the output to the original data.
I ran the as.matrix() function as follows and I seems to get different results when I run str() command.
first time Im running it on the whole data frame, as you can see I get the first element, which should be column names as NULL and the second element, which should be the data 1 or 0, as EmailAddresses.
second time I run it, Im using head() function, asking for the top 100,000 and now I get the matrix that Im looking for.
why is this the case?
> y <- as.matrix(clicked_data[,1:24])
> str(y)
 chr [1:78748, 1:24] "abc1@gmail.com" "abc2@gmail.com" "abc3@msn.com" ...
 - attr(*, "dimnames")=List of 2
  ..$ : NULL
  ..$ : chr [1:24] "EmailAddress" "Column1" "column2" "Column3" ...

> y <- as.matrix(head(clicked_data[,1:24],100000))
> str(y)
 chr [1:10000, 1:24] "abc1@gmail.com" "abc2@gmail.com" "abc3@msn.com" ...
 - attr(*, "dimnames")=List of 2
  ..$ : chr [1:78748] "1" "2" "3" "4" ...
  ..$ : chr [1:24] "EmailAddress" "Column1" "column2" "Column3" ...

A: In the first case NULL is because rows of the matrix is not named. On the other hand, head() seems to put row names so that it appears in dimnames.
The output clarifies it.
df <- read.table(head = T, text = "EmailAddress    Column1 Column2 Column3
abc1@gmail.com     1       0       0
abc2@gmail.com     0       0       0
abc3@gmail.com     1       1       0
abc4@gmail.com     1       1       0")

mat <- as.matrix(df)
#         EmailAddress     Column1 Column2 Column3
#[1,] "abc1@gmail.com" "1"     "0"     "0"
#[2,] "abc2@gmail.com" "0"     "0"     "0"
#[3,] "abc3@gmail.com" "1"     "1"     "0"
#[4,] "abc4@gmail.com" "1"     "1"     "0"
mat1 <- as.matrix(head(df, 2))
#      EmailAddress     Column1 Column2 Column3
#1 "abc1@gmail.com" "1"     "0"     "0"
#2 "abc2@gmail.com" "0"     "0"     "0"


text:
Q: Can a function that was passed as a component property be called in a test using react-testing-library What I want is:

*

*Find the way to call the component's function;

*Test the value after function execution.

For example, the behavior is:

*

*A user types something into an input;

*After each typing, a function is fired and updates the value and passes this value into another component.

I have to write a test that the passed value to not exceeds the max length. In this case, updated value will represent a property from the local state that is passed to another component after its update.
So, how can I call this function and verify that the max length is not greater then I expect?

A: I've created a sample where I show how to manage to fire a function and control the value I pass after function execution.
A brief description is:

*

*Mock nested component

*return a jsx with indicating parameters as a function params for the mocked component

*simulate an event for mocked component (function attached to the event will be fired and local state will be updated)

*use getByTestId to get an element that contains updated data

*Verify if data is what is expected to be.


text:
Q: React-Router-DOM | URL gets redirected to the root Path I have set an AppRouter with React-Router-DOM. Version 4. I have a table with Links attached to them, and I fetch data from the server, for each one. I want to see the details screen, of each item, when I click the Link in the table. That doesn't work.
Below is the AppRouter, which is the Router for the Application. All other routes are working perfectly FYI:
import React from 'react';
import PropsTypes from 'prop-types';
import { withProps } from 'recompose';
import ReactRouterPropTypes from 'react-router-prop-types';
import { Route, Switch, Redirect, withRouter } from 'react-router-dom';
import { connect } from 'react-redux';

import { Authorization } from 'util/viewPermissionUtil';
import { Permission } from 'util/permissionsUtil';
import permissions from 'constants/roles';

import GroupDetailsScreen from 'GroupDetailsScreen';
import GroupsScreen from 'GroupScreen';
import UsersScreen from 'containers/UserScreen';

const GetUser = Authorization(({ user }) =>
  Permission(user, [permissions.somepermission])
);

const AuthUsers = GetUser(
  ({ ...props }) => <UsersScreen {...props} />,
  () => <Redirect to="/" />
);

const GetGroupsDetails = Authorization(({ user }) =>
  Permission(user, [permissions.someOtherPermissions])
);

const AuthGroupDetails = GetGroupsDetails(
  ({ ...props }) => <GroupDetailsScreen {...props} />,
  () => <Redirect to="/" />
);

const UsersRoute = ({ user }) => withProps({ user })(AuthUsers);
const GroupDetailsRoute = ({ user }) => withProps({ user })(AuthGroupDetails)

const Router = ({ match: { path }, user }) => (
  <Switch>
    <Route path={`${path}/groups`} component={GroupsScreen} />
    <Route path={`${path}/groups/details/:name`} component={GroupDetailsRoute({ user })} />
    <Route path={`${path}/users`} component={UsersRoute({ user })} />
    <Redirect to={`${path}/users`} />
  </Switch>
);

Router.propTypes = {
  match: ReactRouterPropTypes.match.isRequired,
  user: PropsTypes.object
};

function mapStateToProps(state) {
  return {
    user: state.auth.user
  };
}

const ConnectedRouter = connect(mapStateToProps)(Router);
const AppRouter = withRouter(({ ...props }) => <ConnectedRouter {...props} />);

export default AppRouter;

In the TableConfig Component, which is the configuration file for the Table columns:
function groupNameRenderer(cell, row) {
  return (
    <span className="text-align-left">
      <Link
        to={{
          pathname: `/groups/details/${row.name}`
        }}
      >
        {cell}
      </Link>
    </span>
  );
}

export const columns = [
  {
    dataField: 'name',
    sort: false,
    text: 'Group',
    formatter: groupNameRenderer,
  },
  {
    dataField: 'field',
    sort: true,
    text: 'FIELD'
  },
  {
    dataField: 'someField',
    sort: true,
    text: 'SOME FIELD'
  }
];

In the Service file, which makes the endpoint call to the server:
import { endpointInstance } from 'services/httpFactory';
import httpMethod from 'constants/httpMethod';

import endpoint from './endpoint';

export const getGroup = name => {
  const options = {
    method: httpMethod.GET,
    url: endpoint.GET_GROUP(name)
  };
  return endpointInstance(options);
};

I mean what is the problem here. I really don't get it at all. I tried a few different scenarios.
I try manually inserting a BrowserRouter in the AppRouter, although, the Router is set higher in the App chain, DIDN'T WORK.
I tried, manually inserting the endpoint data, as a constant file. Without making an API call, DIDN'T WORK.
I get the URL, changing for a single second, but on refresh, it does go back to /. I am really stumped. I implemented the same architecture in 2 different instances with the same methodology. Worked perfectly. Exactly the same.
My App is built on React/Redux/Redux-Observable, for asynchronous operations. On another note. I also pass the getGroup Service, to my GroupDetailsScreen to fetch either data or an error message, but the problem is with the router. I get the groupName on the URL, but get redirected, for some reason. What is going on?
One small Update I just deiscovered. It seems, that the URL for react-router-dom, is dropping one parameter. What I mean is this.
On the TableOverview Screen, the URL is localhost:3000/something/groups,
But when I click the link it goes to localhost:3000/groups/details/name.
**
I am readin on Github about this issue here : https://github.com/ReactTraining/react-router/issues/5870, haven't found a solid solution yet. But I can go and add something here:
pathname: `something/groups/details/${row.name}`

It is a very weird solution, that I am not willing to continue. Foe development is fine, but I need to actually find a solution on this. Any input is welcomed..
Can someone tell me what stupid thing I do here, and doesn't work. Thank you!!


text:
Q: Django rest-framework filter models by the name of other models connected with foreign key class Genre(models.Model):
    name = models.CharField(unique=True,max_length=255)
    def __str__(self):
        return self.name
class BlogText(models.Model):
    mytext = models.TextField(null=True)
    genre = models.ForeignKey(Genre, on_delete=models.CASCADE,null=True,blank=True)
    pub_date = models.DateTimeField('date published')

Each BlogText has Genre.
Now I can filter BlogText by contains
mytext = filters.CharFilter(lookup_expr='contains')

then I want to filter BlogText models by blogtext.genre.name
I googled around but not found the reference other than CharFilter Contains. (even can't find IntFilter... I try to filter genre id directly....)
How can I make it??

A: Specify field_name
genre = filters.CharFilter(lookup_expr='contains', field_name='genre__name')


text:
Q: MVC 4 - Regular Expression Validation - Why is this not working? I have a field on an MVC 4 View which requires regular expression validation. I'm trying to limit entry to characters 'A' through 'Z' (case insensitive) only.
My C# property looks as follows:
   ///
    /// Gets or sets the Revision property
    ///
    [DataMember]
    [Required]
    [RegularExpression("(/^[a-z]+$/i)", ErrorMessage = "Please enter a character between 'A' and 'Z'")]
    public string Revision { get; set; }

The generated HTML looks as follows:

        <input Style="width:30px;" data-val="true" data-val-regex="Please enter a character between 'A' and 'Z'" data-val-regex-pattern="(/^[a-z]+$/i)" data-val-required="The Revision field is required." id="Revision" name="Revision" type="text" value="" />

But when I execute it, I get the following error on valid data entry:

I don't have a great deal of experience with MVC 4 or RegEx, so it's not clear to me why this isn't working.

A: You're regular expression is only allowing lowercase characters. Therefore when you input a 'D' it responded with the error. For all letters, case insensitive, your regex should look like this ^[a-zA-Z]*$. Try that and it should work.

A: You have (/ to start with, but this makes the delimiters ().  I'm not sure that you even need delimiters at all.  Remove the ( and ).  If that doesn't work, use
^[a-zA-Z]+$


text:
Q: How to create a generic class in what I can call an Enum.valueOf() in Java? So I have these classes:
public class DeviceInState implements MyInterface<Device> {

    private List<DeviceState> toStates(String statesString) {
        List<String> states = Lists.newArrayList(statesString.split(","));

        return states.stream().map(DeviceState::valueOf).collect(Collectors.toList());
    }
}

public class DeviceHistoryInState implements MyInterface<DeviceHistory> {
    private List<EventType> toStates(String statesString) {
        List<String> states = Lists.newArrayList(statesString.split(","));

        return states.stream().map(EventType::valueOf).collect(Collectors.toList());
    }
}

And these enums:
public enum EventType{
    NEW("N"), ACTIVE("A"), INACTIVE("I");
}

public enum DeviceState{
    REGISTRATED("R"), SUSPENDED("S"), DELETED("D");
}

The differences are:

*

*DeviceInState implements MyInterface<Device>; but DeviceHistoryInState implements MyInterface<DeviceHistory>

*DeviceState::valueOf is called in DeviceInState; but EventTypes::valueOf is called in DeviceHistoryInState
I have a couple of other classes like these so I would like to make a generic one. But I have no idea whether or not it is possible. How might I parameterize my classes or methods in a way that I can call the ::valueOf method?
Thanks in advance.

A: This is how I would do it…
public interface State< E extends Enum< E > > { … }

Then my enums would implement that…
…
public enum DeviceState implements State< DeviceState > { … }
…
public enum EventType implements State< EventType > { … }
…

"…Actually not these methods are overridden. These methods are just called from the overridden method…"

Considering that you annotated the methods in your snippet with @Overrides, I found that to be a pretty confusing comment. To make things a little less confusing for myself,  my experimental implementation does actually override something…
public class DeviceInState extends ToStateable< DeviceState > implements Specification< Device > {

    @Override
    public List< DeviceState > toStates( String statesString ) {

        List< String > states = asList( statesString.split( "," ) );

        return states.stream( ).map( String::trim ).map( DeviceState::valueOf ).collect(Collectors.toList());
    }
}

I was able to call that successfully like…
…
ToStateable< DeviceState > deviceToStateable = new DeviceInState( );

List< DeviceState > deviceStates = deviceToStateable.toStates( "SUSPENDED,REGISTERED,DELETED" );

ToStateable< EventType > eventToStateable = new DeviceHistoryInState( );

List< EventType > eventTypes = eventToStateable.toStates( "INACTIVE, NEW, ACTIVE"  );
…

Printing those objects out I could see…
                                  [SUSPENDED, REGISTERED, DELETED]
                                           [INACTIVE, NEW, ACTIVE]
                                                         SUSPENDED
                                             EXPERIMENT SUCCESSFUL

A: You can remove your two similar implementations of toState() inside DeviceHistoryInState and DeviceInState and define a single generic method that works with any enumeration type:
static <E extends Enum<E>> List<E> toStates(Class<E> cls, String statesString) {
    List<String> states = Arrays.asList(statesString.split(","));
    return states.stream().map(String::trim).map(s -> Enum.valueOf(cls, s))
                          .collect(Collectors.toList());
}

There is however a small cost: you have to pass in the EnumType.class as a parameter, but this is fairly straightforward:
List< DeviceState > devStates = toStates(DeviceState.class, "SUSPENDED,REGISTRATED,DELETED");
=> [SUSPENDED, REGISTRATED, DELETED]
List< EventType > evTypes = toStates(EventType.class, "INACTIVE,NEW,ACTIVE");
=>  [INACTIVE, NEW, ACTIVE]

Alternatively you can make simple definition of EventType.toState(String) which calls the above.


text:
Q: Strange problem using landscape, afterpage and split I have a problem in Latex where \afterpage somehow seems to have problems with a split equation, so that the code does not compile. I use \afterpage to fill a page before a large landscape figure is presented, to avoid the whitespace that is produced otherwise.
This is the MWE (comment out the \afterpage command and it will compile):
\documentclass[a4paper]{scrbook}
\usepackage{amsmath, amssymb}
\usepackage{graphicx}
\usepackage{pdflscape}
\usepackage{afterpage}
\usepackage{lipsum}

\begin{document}
\lipsum[1-2][1-20]
\afterpage{
\begin{landscape}
\begin{figure}
\includegraphics[width=\textwidth]{example-image-a}
\caption{Caption}
\end{figure}
\end{landscape}}
\lipsum[1-5]
\begin{equation}
\begin{split}
x&=\frac{\pi}{2}\\
&=\frac{3}{2}
\end{split}
\end{equation}
\lipsum[1-2]
\end{document}

A: An easy solution is to separate the equation from the preceding paragraph.  This solution puts the equation inside a splitable paragraph, but the spacing on the first and last lines are slightly off.
\documentclass[a4paper]{scrbook}
\usepackage{amsmath, amssymb}
\usepackage{graphicx}
\usepackage{pdflscape}
\usepackage{afterpage}
\usepackage{lipsum}

\newsavebox{\tempbox}

\begin{document}
\lipsum[1-2]
\afterpage{%
\begin{landscape}
\begin{figure}
\centering
\includegraphics[width=\textheight]{example-image-a}
\caption{Caption}
\end{figure}
\end{landscape}}
\lipsum[1-3]

\setbox\tempbox=\vbox{\strut
Text in pragraph before equation.
Text in pragraph before equation.
Text in pragraph before equation.
Text in pragraph before equation.
Text in pragraph before equation.
Text in pragraph before equation.
Text in pragraph before equation.
\begin{equation}
\begin{split}
x&=\frac{\pi}{2}\\
&=\frac{3}{2}
\end{split}
\end{equation}
Text in same paragraph after equation.
}\unvbox\tempbox
\lipsum[1-2]
\end{document}


text:
Q: Does Sitecore use Fast Query automatically? According to Sitecore Data Definition Reference, version 6.4, section 4.3.1:

Sitecore processes queries using the
  fasted technology possible. This could
  be either the SQL database, if the
  data provider supports the requested
  query, or in the Sitecore data
  manager.

If this is so, is there any benefit to using the "fast:" syntax? With what release did automatic technology selection get introduced?
Update
I think I figured it out.  Reqular Sitecore queries can only use SQL Server if they do not have predicates.  Fast Query allows simple predicates (e.g. *[@somefield='somevalue']) while still making use of SQL Server.
From Sitecore CMS 6.4 Data Definition Reference (Section 4.3.4):

The SQL Server data provider does not
  support predicates (the portion of the
  search string enclosed in square
  brackets: [@IsHidden != '1']).

From Sitecore CMS 6 Using Sitecore Fast Query (Section 4.2):

This section describes the predicates
  that are available in Sitecore Fast
  Query. Predicates are
   always embedded in square brackets.

Example: fast:/sitecore/content/Home/*[@Title = 'Welcome to Sitecore']

Result: returns the items that have the value of the 'Title' field set to 'Welcome to Sitecore'. The
  search is performed in the children of the Home Item.

A: There are several different approaches to querying items from Sitecore:

*

*Sitecore Query

*Fast Query

*Lucene

Each approach has its own pros and cons. For example, Sitecore Query and Fast Query both have a limit to the number of items they can return. This limit is the Query.MaxItems setting in the web.config. Lucene on the other hand is its own beast and uses search indexes stored on disk to access items.
Sitecore query is the most flexible in terms of filtering items right in the query, however the more complex your query is, the longer it will take to run (that's a generalization). Its often easier to make a more generic query then use .NET to filter it, like LINQ. Fast query goes straight to the database to query and thus has limit on the filtering. It runs faster but you can't be as granular with what you want to check in your query.
Lucene is another approach as it uses search indexes to query content and filter. This requires additional configuration work up front and maintenance of the search index.
This can help you decide which approach to take:

*

*100 items or less: Sitecore Query

*1000 items or less: Fast Query

*1000+ items: Lucene

I've also previously written blog post on this same topic:

*

*Options For Querying Items From Sitecore


text:
Q: Validity of domain entity method based on context or caller I am currently reading about DDD and have a issue how to implement a certain validation.
Scenario:
I have an entity Group that contains a list of Members which in turn consists of a User and a MemberState (Member, Admin). The entity has a method MakeAdmin(User user) that turns a member into an admin.
The rule is: Only if the current user is admin of the group, it is allowed to turn the member to an admin.
I have three possible implementations in mind, with some caveats each.
Variant 1
Group enitity gets a dependency IUserContext injected via constructor to get the current user. With that the entity can check if the current user is admin and is allowed to switch the member state.
Caveat: I don't like that the domain entity has such a dependency injected and I don't think that is correct in a DDD view.
Variant 2
Method MakeAdmin() gets an additional parameter which turns it into MakeAdmin(User user, User currentUser). That removes the requirement for the IUserContext dependency in the entity.
Caveat: I am not sure if it is correct at all that the entity validates this rule, because it is not really an invariant of the entity.
Variant 3
Validate this rule in an application service, and only call MakeAdmin(User user) if validation passed.
Caveat: I consider the rule domain specific, so I think it is not correct to put it in application layer.
So what would be the best option, or is there some totally different variant?

A: My suggestion would be to go with your third option:  Authorise access in the application/integration layer and then call into the domain.
This goes for any domain functionality really.  The domain should not concern itself with whether the action may or may not be performed based on authorisation but rather only with domain concerns.  If that authorisation action happens to be a domain concern in a particular Identity & Access Control bounded context that it would make sense but you would not run into those too often.


text:
Q: Programatically "picking up" connections between elements in jsPlumb jQuery When elements are connected using jsPlumb there is one rather important feature and use-case that I feel is missing:
The ability to, for example on mousedown, release a connector from one of it's endpoints and cause it to be dragged and able to be reapplied to an endpoint or target. When using flowchart connectors or in general cases where the connectors share endpoints, how can the user decide which connector to move? You always pick up the top one, or one specified by order.
The use-case I mean is in dynamic diagramming user interfaces, where an end user will drag and drop connections from endpoint to endpoint between elements. If several connectors share an endpoint, the user can't choose which connector to move.
To work around this, I want to make it possible to drag the connector by anything except the endpoint, and thus make it release from the target endpoint and become dragged by the user.
Example: http://jsplumbtoolkit.com/jquery/flowchartConnectorsDemo.html
Try to drag several of the "drag" endpoints to "drop" endpoints. If you click and drag the "drop" endpoint now, you pick up a predetermined connector (perhaps not the one you want). Is it possible to instead make it be picked up by, say, dragging the middle of the connector (anywhere on the yellow line)?
Question:
How can you "trick" jsPlumb that someone clicked and dragged an endpoint, when in fact the user clicked and dragged the connector?
Note: I do not want to delete connections. That I know how to program. I want to trigger a connector being picked up and dragged by it's endpoint, without clicking the endpoint directly.

A: I see that your question is quite old, but I solved it
All you need to do is trigger the mousedown event on the endpoint.canvas element, this will start the connector drag.
Of course the mouse won't be in the same place for the start drag, and the dragging doesn't actually start until the mousemove event, so I added little cheeky adjust on document.mousemove. There probably is a better way to do this, but this might be a good starting point for other people.
$(function() {

jsPlumb.ready(function() {
   var jsp = jsPlumb.getInstance();
    jsp.draggable($("#start"));
    jsp.draggable($("#end"));

    var endpoint = jsp.addEndpoint($("#start"), {
        isSource:true
    });

    jsp.addEndpoint($("#end"), {
        isTarget:true
    });

    $("#dragbutton").bind("mousedown", function(e) {

        $(document).bind("mousemove.adjust", function(e) {

            var left = e.offsetX;
            var top = e.offsetY;
            $(endpoint.canvas).css({"left":left, "top":top});
            $(document).unbind("mousemove.adjust");
        });

        $(endpoint.canvas).trigger(e)
    })

})

})
http://jsfiddle.net/VvKZ6/14/


text:
Q: Swipe gesture action is not called I am trying to do basic 2D snake game for tv.
I have problem with gestures. I add gestures to view in didMoveToView(view: SKView) method inside GameScene class. This class also extends SKScene class. This is my didMoveToView method and handleSwipe method.
override func didMoveToView(view: SKView) {
    let swipeUp = UISwipeGestureRecognizer(target: self, action: "handleSwipe:")
    swipeUp.direction = .Up
    view.addGestureRecognizer(swipeUp)

    let swipeDown = UISwipeGestureRecognizer(target: self, action: "handleSwipe:")
    swipeDown.direction = .Down
    view.addGestureRecognizer(swipeDown)

    let swipeLeft = UISwipeGestureRecognizer(target: self, action: "handleSwipe:")
    swipeLeft.direction = .Left
    view.addGestureRecognizer(swipeLeft)

    let swipeRight = UISwipeGestureRecognizer(target: self, action: "handleSwipe:")
    swipeRight.direction = .Right
    view.addGestureRecognizer(swipeRight)

    backgroundColor = SKColor.blackColor()
}

func handleSwipe(sender: UIGestureRecognizer) {
    if let gesture = sender as? UISwipeGestureRecognizer {
        switch(gesture.direction) {
            case UISwipeGestureRecognizerDirection.Right: m_snake.moveRight()
            case UISwipeGestureRecognizerDirection.Left: m_snake.moveLeft()
            case UISwipeGestureRecognizerDirection.Up: m_snake.moveUp()
            case UISwipeGestureRecognizerDirection.Down: m_snake.moveDown()
            default:
                break
        }
    }
}

It seems like my program does not enter handleSwipe method when I swipe on remote. I am testing this on simulator. Any idea why this doesn't work?

A: func handleSwipes(sender:UISwipeGestureRecognizer) {
    if let gesture = sender as? UISwipeGestureRecognizer {
        switch(gesture.direction) {
            case UISwipeGestureRecognizerDirection.Right: m_snake.moveRight()
            case UISwipeGestureRecognizerDirection.Left: m_snake.moveLeft()
            case UISwipeGestureRecognizerDirection.Up: m_snake.moveUp()
            case UISwipeGestureRecognizerDirection.Down: m_snake.moveDown()
            default:
                break
        }
    }
}

I just tested your code in my current project and it worked perfectly fine
To get the swipe working, configure the simulator like this;

*

*Show the remote by going to Hardware > Show Apple TV Remote

*Hold down option while your mouse is over the trackpad.

*Move the mouse sideways in a swipe movement