text:
Q: Reading executing assembly signature pfx / cert This is an academic question trying to understand new material. Not academic in the sense of formal school but in the sense of ongoing education and wanting to get a handle on an area of development I have not been exposed to before.
So in my understanding I create an assembly and by "signing it" I have created a strong name / X509Certificate.
So I create an empty winapp. I go to the project properties on the signing tab and sign the assembly using a password.
A file testing.pfx is added to my project.
In the form load I then execute this code thinking I would see my assembly signing cert only I don't as it is null...??
Assembly ass = Assembly.GetExecutingAssembly();
Module mod = ass.GetModules().First();
X509Certificate cert = mod.GetSignerCertificate();

cert is null. Why is that? Am I doing something wrong to retrieve the cert or do I have things jumbled up in my head and what I am looking for isn't where I am looking?
Thank You

Edit
@p e p I have used the following after reading your post and msdn.

signtool sign /a C:/....../MyFile.exe
signtool sign /f C:/....../MyCert.pfx /p MyPassword C:/....../MyFile.exe

Both said they completed with success. However running the code block above still produces a null cert.
Now what I may have missed or am doing wrong is I am working with visual studio debug version and that is the path to the exe that I used for signing.
c:....\LicensedControlTest\obj\x86\Debug

A: You need to Authenticode sign  the assembly. You can do this by using the File Signing Tool (Signcode.exe) which will sign your assembly with an Authenticode signature. Essentially you just run a command using signcode which will Authenticode sign your assembly.
If you look at the doc for GetSignerCertificate, you will see that null is expected if the assembly is not authenticode signed.
signcode /spc myCertificate.spc /v myKey.pvk  myAssembly

That's the basics, you can find more info here on MSDN http://msdn.microsoft.com/en-US/library/9sh96ycy(v=vs.80).aspx.


text:
Q: ggplot - geom_point with shape and colour dictated by variable, where colour comes from a custom palette Here's the data frame I want to plot:
   age composite_col  frequency
1   18          var1 0.65531200
2   19          var1 0.48697446
3   20          var1 0.21423509
4   21          var1 0.38887071
5   22          var1 0.27072698
6   23          var1 0.76371308
7   18          var2 0.05554554
8   19          var2 0.65048383
9   20          var2 0.98546390
10  21          var2 0.04171436
11  22          var2 0.13346492
12  23          var2 0.21246432

Here's the code for generating the dataframe:
library(tidyr)

set.seed(1911)
df_se = data.frame(age = c(18,19,20,21,22,23), var1 = runif(6,0,1), var2 = runif(6,0,1) )

df_se = gather(df_se, "composite_col","frequency",c(var1,var2))
df_se

I want to produce a single graph that consists of:

*

*A line graph where the colours dictated by the variable composite_col

*Overlayed geom_points with the both the colours and shapes dictated by the variable composite_col

*A black outline around the shapes

my attempt at a solution:
p = ggplot(data = df_se)

p = p + geom_line( aes(x=age, y=frequency, colour=composite_col) )

p = p + geom_point(aes(x = age, y= frequency, shape = composite_col, fill = composite_col, colour = "black"), pch = 21, size = 2.5)

p = p + scale_colour_manual(values=c("#DF4A2A", "#3D9813"))

p

produces the following error:
Error: Insufficient values in manual scale. 3 needed but only 2 provided.

When I add more colours to my palette it produces a graph but the colours are completely wrong and the scale is completely wrong

A: Since the outline of each point should always be black, you need to remove the colour = "black" line outside of the aes() call.
ggplot(data = df_se, aes(x=age, y=frequency)) +
    geom_line(aes(colour=composite_col)) +
    geom_point(aes(shape=composite_col, fill=composite_col), colour="black", pch=21, size=2.5) +
    scale_colour_manual(values=c("#DF4A2A", "#3D9813"))

And if you want the color of the point to match the color of the line, you can add a scale for the fill:
ggplot(data = df_se, aes(x=age, y=frequency)) +
    geom_line( aes(colour=composite_col) ) +
    geom_point(aes(shape = composite_col, fill = composite_col), colour = "black", pch = 21, size = 2.5) +
    scale_colour_manual(values=c("#DF4A2A", "#3D9813")) +
    scale_fill_manual(values=c("#DF4A2A", "#3D9813"))

Edit:
And to specify the shape with scale_shape_manual, you will need to remove the pch parameter from your geom_point:
ggplot(data = df_se, aes(x=age, y=frequency)) +
    geom_line( aes(colour=composite_col) ) +
    geom_point(aes(shape = composite_col, fill = composite_col), colour = "black", size = 2.5) +
    scale_colour_manual(values=c("#DF4A2A", "#3D9813")) +
    scale_fill_manual(values=c("#DF4A2A", "#3D9813")) +
    scale_shape_manual(values=c(3, 16))

redpajama_set_name: RedPajamaStackExchange


text:
Q: magento Adminhtml Users Grid by Role Id add column
I can filter the adminhtml users grid to only show users with a specific role ID as code in
\app\code\local\Mage\Adminhtml\Block\Permissions\User\grid.php
=> for collection
 protected function _prepareCollection()
{

    $collection = Mage::getResourceModel('admin/user_collection');
    $collection->getSelect()->join(array('ar' =>'admin_role'),'ar.user_id = admin_user.user_id')
    ->reset('columns')->columns(array('role_id'));
    $this->setCollection($collection);
    return parent::_prepareCollection();

}

=>and for add column
 protected function _prepareColumns()
{
  parent::_prepareColumns();
    $this->addColumn('role_id', array(
        'header'    =>Mage::helper('adminhtml')->__('Role ID'),
        'index'     =>'role_id',
        'align'     => 'right',
        'width'    => '50px'
    ));

But still not getting roll id in column ..

A: Replace following code.

$collection->getSelect()->join(
            array('ar' =>'admin_role'),
            'ar.user_id = main_table.user_id',
            array('role_id')
        );

So _prepareCollection looks like:

protected function _prepareCollection()
    {
        $collection = Mage::getResourceModel('admin/user_collection');
        $collection->getSelect()->join(
            array('ar' =>'admin_role'),
            'ar.user_id = main_table.user_id',
            array('role_id')
        );
        $this->setCollection($collection);
        return parent::_prepareCollection();
    }


text:
Q: Revoke Rails Doorkeeper Token via POST We know if we utilise the Resource Owner Password Credential flow for doorkeeper, the generated JSON params for POST are based on the URL here:
{
  "grant_type"    : "password",
  "username"      : "user@example.com",
  "password"      : "sekret",
  "client_id"     : "the_client_id",
  "client_secret" : "the_client_secret"
}

I would like to perform a token revocation via POST to /oauth/revoke; thus, what parameters which I need in order to perform the POST via JSON?
Thanks!

A: Ok I got it figured out; basically I need to send the following:
curl -H "Authorization: Bearer <token>" \
     -F token=<token>\
     -X POST http://livedo-gunter.codio.io:3000/oauth/revoke

This is based on the link here. Basic authorization has to be enabled first though.


text:
Q: Using PowerShell to trigger Dropbox api saveurl get 400 error I am following the API document here to code my powershell. It seems quite straight forward but I only get 400 invalid request error. May I know what's the problem or how can I further troubleshoot it? I have no clue for the 400 message. I tested simple upload file with PowerShell and works. So the token should be good.
Here is my PowerShell script:
$token = Get-Content -Path "c:\token.txt"
$authorization = "Bearer " + $token
$headers = New-Object "System.Collections.Generic.Dictionary[[String],[String]]"
$headers.Add("Authorization", $authorization)
$headers.Add("Content-Type", 'application/json')

$body = @"
{
    "path": "/test.mp3",
    "url": "http://sxxxxx.com/today.mp3"
}
"@

    Invoke-RestMethod -Uri https://api.dropboxapi.com/2/files/save_url -Method Post -Headers $headers -Body $body

A: My script work after amend the $body part to below:
$body = '{
    "path": "/test.mp3",
    "url": "http://sxxxxx.com/today.mp3"
}'

It seems I need to pass the parameter as a string instead of json format.


text:
Q: Capture Time Right Down to the Second How do I capture the date & time right down to the second and store it in a variable?
Take for example if I wanted Tuesday Dec 8th 2015 1:00:20 pm the output should look like this:
130020-8-12-2015
So far I only have the date:
function backup()
{
    local now="$(date +'%d-%m-%Y')"
    echo $now
}

A: You should check out the manpage for date. Use command man date. You will find in the manpage:
%H     hour (00..23)
%I     hour (01..12)
%k     hour ( 0..23)
%l     hour ( 1..12)
%M     minute (00..59)
%N     nanoseconds (000000000..999999999)
%s     seconds since 1970-01-01 00:00:00 UTC
%S     second (00..60)
%T     time; same as %H:%M:%S
%z     +hhmm numeric timezone (e.g., -0400)

Amongst many other tokens.
So the following should do what you need
function backup()
{
    local now="$(date +'%H%M%S-%d-%m-%Y')"
    echo $now
}

A: date +'%H%M%S-%d-%m-%Y' would give you your desired format.


text:
Q: In Codeigniter, how to validate radio buttons (without "checked")? In Codeigniter, I would like to validate radio buttons but I don't want to select one when the user loads the page (I mean no "checked" attribute).
This is what I have done so far...
My view file:
<?=validation_errors()?>
<form action="step1" method="post">
    <input name="food" type="radio" value="1" <?=set_radio('food', '1')?> />
    <input name="food" type="radio" value="2" <?=set_radio('food', '2')?> />
    <input name="food" type="radio" value="3" <?=set_radio('food', '3')?> />
</form>

My controller file:
$this->form_validation->set_rules('food', 'food', 'required');
if ($this->form_validation->run() == TRUE) redirect('step2');

The error message only appears if I add a field like an <input type="text">. But my wish is to have only 3 radio buttons and an error message if none are selected.
Do you know how to do that?

A: "required validation rule does not return error message when the form contains radio buttons only", because of CodeIgniter 2 bug. See details here - https://github.com/EllisLab/CodeIgniter/issues/138 .
I fixed it simply by adding hidden field e.g. <input type="hidden" value="true" name="fix_radio_required">

A: Have you tried checking for the ON status?
if($this->input->post('food') === 'on')

A: This approach worked well for us.
<?php
$member_type = 1;
    if(isset($_POST['member_type'])){
        $member_type = $_POST['member_type'];
    }
    echo form_radio("member_type", 1, $member_type == 1 ? TRUE : FALSE,' id="member_type" class="form-control"');

    echo form_radio("member_type", 2, $member_type == 2 ? TRUE : FALSE,' id="member_type" class="form-control"');
?>

To expand on what Andriy wrote we'll take the value of the submitted radio button and then do a TRUE or FALSE to set the checked value.

A: Using the Form Validation library, you can achieve that with the following:
Controller
$this->form_validation->set_error_delimiters('', '
');
$this->form_validation->set_rules('type', 'Type', 'trim|required|maxlength[1]|xss_clean');

View
Is this type one, two or three? *

<input type="radio" name="type" id="type_1"<?php echo set_radio('type', '1'); ?> value="1">One
<input type="radio" name="type" id="type_2"<?php echo set_radio('type', '2'); ?> value="2">Two
<input type="radio" name="type" id="type_3"<?php echo set_radio('type', '3'); ?> value="3">Three
<?php echo form_error('type'); ?><?php echo isset($errors['type']) ? $errors['type'] : '' ?>

A: Using Form Validation:
Controller:
    $this->load->library('form_validation');

    $this->form_validation->set_rules('food', 'Radio button', 'required');

    if ($this->form_validation->run() == FALSE)
    {
        $this->form_validation->set_message('required', 'Error message');
    }

Here you set rules for your radio buttons:
$this->form_validation->set_rules('food', 'Radio button', 'required');

'food' means name of your radio button.
'Radio button' - "human" name for this field
'required' - validation rule for this form field
With $this->form_validation->run() you run form validation library arnd check if your form passed (TRUE/FALSE).
View:
<?=validation_errors()?>
    <form method="post">
        <input type="radio" name="food" value="1">
        <input type="radio" name="food" value="2">
        <input type="radio" name="food" value="3">

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

Here is form with 3 radio buttons with same name 'radio' as used in controller.

A: View File
<?php echo form_error('gender')?>
<form name="frm" method="post">
<input type="radio" value="m" name="gender" /> Male

<input type="radio" value="f" name="gender" /> Female

<input type="radio" value="o" name="gender" /> Other
<input type="submit" value="submit" name="btn" />
</form>

Controller
public function index()
{

    $this->form_validation->set_rules('field' => 'gender', 'label' => 'Gender', 'rules' => 'required');

    if($this->form_validation->run()==TRUE)
    {
        echo "hello wordl"; exit;
    }
    //Your view loading script..
}


text:
Q: Imputation approaches for records with completely missing dimensions I have two sets of data provided by the government - one spans the years 2016-2020, while the other only covers 2018-2020. Data from each dataset, for each year, are used to predict some outcome in the next year. There are common joining criteria between these two datasets.
I have reason to believe the 2018-2020 dataset should be very useful in my predictive task. However, these data are completely missing (i.e. I cannot find them anywhere on the Internet and it's likely the government never collected this information for 2016 and 2017).
Without simply dropping the years 2016 and 2017 from my analysis, how could I best incorporate these 2018-2020 data? I saw this question but it didn't speak to an approach I thought of, which was to simply include the 2018-2020 as I normally would, and add a "this-type-of-data-was-completely-missing" flag in 2016 and 2017, in order to perhaps capture that any potential variation in the outcome that way. What potential pitfalls could there be with this approach?

A: That use of a "missing data" flag is not a very good choice.
Multiple imputation, as recommended on the page you link, can seem daunting at first. It's not that difficult to understand (at least in outline) or to implement, however. You do multiple probabilistic imputations of the missing data, and fit your model separately on each imputed data set. You then combine information from those models to take into account both the inherent modeling variability and the variability introduced by the imputation.
Stef van Buuren, a respected expert on imputation, has an online book that starts with an explanation of how the type of coding you propose can lead to problems even in simple models. I suspect that in your situation, where you use prior years' data to predict subsequent years' values in some way, would be even worse.
So use multiple imputation for the 2016 and 2017 data if those data are important for your modeling. Most serious statistical software supports that, either directly or as an add-on. In R, you can use van Buuren's package mice.


text:
Q: How can I send a text to a logfile given that a certain event has finished within a loop in R? I try to get error rates for different parameter settings for a random forest (classification).
Given that I use a loop and this takes considerable time i would like to know how much time has passed up until a certain point. For this I would like to get a result saved on a logfile each time a certain event has passed. the code looks like this.
library(randomForest)

ntree<-c(1:1000)

mtry<-c(1:30)

set.seed(123)

for (j in mtry) {

for (i in ntree) {

  rf1 <- randomForest(mymodel,mtry=j, ntree=i)

  result = data.frame(mtry=j,ntree=i,
                      OOB=rf1[["err.rate"]][nrow(rf1[["err.rate"]]),"OOB"])

  oob_NP = rbind(oob_NP, result)
}
}

I would like to get a result in a log file for every hundred model...So show me the error rate result for
mtry=1, ntree=100
mtry=1, ntree=200
.
.
.
mtry=30,ntree=1000
Anyone an idea how to integrate this in the code?

A: This can be solved with sprintf to produce the log text lines and cat to write them to a connection.
logfile <- "Tacatico.log"

ntree <- 1:10
mtry <- 1:3

logfile_con <- file(logfile, open = "wt")
for (j in mtry) {
  for (i in ntree) {
    logtext <- sprintf("mtry=%d    ntree=%d", j, i)
    cat(logtext, '\n', file = logfile_con)
  }
}
close(logfile_con)

Check what was written to the log file.
readLines(logfile)
# [1] "mtry=1    ntree=1 "  "mtry=1    ntree=2 "  "mtry=1    ntree=3 "
# [4] "mtry=1    ntree=4 "  "mtry=1    ntree=5 "  "mtry=1    ntree=6 "
# [7] "mtry=1    ntree=7 "  "mtry=1    ntree=8 "  "mtry=1    ntree=9 "
#[10] "mtry=1    ntree=10 " "mtry=2    ntree=1 "  "mtry=2    ntree=2 "
#[13] "mtry=2    ntree=3 "  "mtry=2    ntree=4 "  "mtry=2    ntree=5 "
#[16] "mtry=2    ntree=6 "  "mtry=2    ntree=7 "  "mtry=2    ntree=8 "
#[19] "mtry=2    ntree=9 "  "mtry=2    ntree=10 " "mtry=3    ntree=1 "
#[22] "mtry=3    ntree=2 "  "mtry=3    ntree=3 "  "mtry=3    ntree=4 "
#[25] "mtry=3    ntree=5 "  "mtry=3    ntree=6 "  "mtry=3    ntree=7 "
#[28] "mtry=3    ntree=8 "  "mtry=3    ntree=9 "  "mtry=3    ntree=10 "


text:
Q: Angular2: NgFor only supports binding to Iterables such as Arrays I'm creating a web app for a university project that comes in two parts: a Web API and a Frontend that connects to said API. The web app that I'm making is a recipe website. Having not touched new technologies such as Angular I took to the Tour of Heroes tutorial on their website and am coping fairly well with it.
However, I'm to the point now where I must link not use mock data sources and instead use my API to pull data from.
I have several components, and so I've included the relevant files for the HTTP section of the tutorial, recipe.service.ts and recipes.component.html, for this part of the app (the only files that should be edited in the tutorial.
It seems to me that Angular isn't reading the response as an array by the error code, although the supposed return text being JSON. I've looked this question up but couldn't seem to get the answers to work with my code correctly.
recipe.service.ts
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { of } from 'rxjs/observable/of';
import { Recipe } from './recipe';
import { RECIPES } from './mock-recipes';
import { MessageService } from './message.service';
import { HttpClient, HttpHeaders } from '@angular/common/http';

@Injectable()
export class RecipeService {

  private recipesURL = 'http://localhost:3000/api/recipes';

  constructor(
    private http: HttpClient,
    private messageService: MessageService) {}

  getRecipes(): Observable<Recipe[]> {
    //Todo: send the message after fetching heroes
    //this.messageService.add('RecipeService: fetched recipes');
    return this.http.get<Recipe[]>(this.recipesURL);
  }

  getRecipe(id: number): Observable<Recipe> {
    this.messageService.add(`RecipeService: fetched recipe id=${id}`);
    return of(RECIPES.find(recipe => recipe.recipeID === id));
    //return of(RECIPES.find(recipe => recipe.recipeName));
  }

  private log(message: string) {
    this.messageService.add('RecipeService: ' + message);
  }
}

recipes.component.html

My Recipes

      {{recipe.recipeName}} {{recipe.userID}}

The error I'm getting in the console when running the Angular app:
ERROR Error: Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays.
    at NgForOf.ngOnChanges (common.js:2537)
    at checkAndUpdateDirectiveInline (core.js:12092)
    at checkAndUpdateNodeInline (core.js:13598)
    at checkAndUpdateNode (core.js:13541)
    at debugCheckAndUpdateNode (core.js:14413)
    at debugCheckDirectivesFn (core.js:14354)
    at Object.eval [as updateDirectives] (RecipesComponent.html:3)
    at Object.debugUpdateDirectives [as updateDirectives] (core.js:14339)
    at checkAndUpdateView (core.js:13508)
    at callViewAction (core.js:13858)

A snippet of what the application is supposed to pull back (as JSON):
{
    "Error": false,
    "Message": "Success",
    "Recipes": [
        {
            "recipeID": 1,
            "recipeName": "orci",
            "ingredients": "Vivamus metus arcu, adipiscing molestie, hendrerit at, vulputate vitae, nisl. Aenean lectus. Pellentesque eget nunc. Donec quis orci eget orci vehicula condimentum. Curabitur in libero ut massa volutpat convallis.",
            "method": "Vivamus in felis eu sapien cursus vestibulum. Proin eu mi. Nulla ac enim. In tempor, turpis nec euismod scelerisque, quam turpis adipiscing lorem, vitae mattis nibh ligula nec sem. Duis aliquam convallis nunc. Proin at turpis a pede posuere nonummy. Integer non velit.",
            "createdBy": 150,
            "postedTime": "2017-06-01 15:11:27"
        },
        {
            "recipeID": 2,
            "recipeName": "sit",
            "ingredients": "Suspendisse potenti. In eleifend quam a odio.",
            "method": "Donec semper sapien a libero. Nam dui. Proin leo odio, porttitor id, consequat in, consequat ut, nulla. Sed accumsan felis. Ut at dolor quis odio consequat varius. Integer ac leo.",
            "createdBy": 982,
            "postedTime": "2017-02-21 08:40:58"
        }
    ]
}

If anyone could help me it would be great.
Thanks :)
EDIT - my recipes.component.ts
import { Component, OnInit } from '@angular/core';
import { Recipe } from '../recipe';
import { RecipeService } from '../recipe.service'

@Component({
  selector: 'app-recipes',
  templateUrl: './recipes.component.html',
  styleUrls: ['./recipes.component.css']
})
export class RecipesComponent implements OnInit {

  recipes: Recipe[];

  constructor(private recipeService: RecipeService) { }

  ngOnInit() {
    this.getRecipes();
  }

  getRecipes(): void {
    this.recipeService.getRecipes().subscribe(recipes => this.recipes = recipes);
  }

}

A:   getRecipes(): void {
    this.recipeService.getRecipes().subscribe(recipes => this.recipes = recipes.Recipes);
  }

Because your response is an object, not an array. You need to set this.recipes to recipes.Recipes. According to:
{
    "Error": false,
    "Message": "Success",
    "Recipes": [... //here is your array

A: You return the whole json response from the service not just the recipes array. You cannot iterate an object using *ngFor. Change this.recipes = recipes as below.
getRecipes(): void {
        this.recipeService.getRecipes().subscribe(recipes =>
        if(recipes){
          this.recipes = recipes.Recipes;
         }
        );
      }


text:
Q: Dismiss Authentication Prompt in FireFox I am trying to run selenium automation on a 3rd party website.
Selenium fails when firefox authentication prompt like this appears:

Works like the Display Image button here
Is there any way to dismiss this using javascript, as part of a firefox extension or otherwise?
We have tried dismissing the prompt in selenium with the following:
Alert alert = driver.switchTo().alert();
alert.dismiss();
We have also tried disabling javascript although this solution doesn't work as we also require javascript to be enabled for our automation.
There seems to be a possible solution, as there is an extension that can handle this, we are unable to use this as we can't use 3rd party code and we would like slightly different behaviour.
Edit: different to linked question as we are looking for a in-browser solution using javascript
Any help or guidance is appreciated,
Liam

A: I have tried with your inputs, Alert can be dismissed only after getting the alert text. Please try this working code
driver.get("http://www.httpwatch.com/httpgallery/authentication/#showExample10");

     // open URL
     driver.findElement(By.id("displayImage")).click();
     Thread.sleep(2000);
     driver.switchTo().alert();

     Alert promptAlert  = driver.switchTo().alert();
     String alertText = promptAlert .getText();
     System.out.println("Alert text is " + alertText);
     promptAlert.dismiss();


text:
Q: How to make DateTimeOffSet nullable on JSON Schema when generating client with openapi-generator? I have a model defined on an JSON Schema, with 2 properties that look like this:
"AffectedDevice": {
        "type": "object",
        "properties": {
          "id": {
            "type": "string"
          },
          "lastCheckin": {
            "type": "string",
            "format": "date-time",
            "nullable": true
          },
          "lastDownload": {
            "type": "string",
            "format": "date-time",
            "nullable": true
          },
          "operatorId": {
            "type": "string"
          },
          "serialNumber": {
            "type": "string"
          },
          "status": {
            "type": "string"
          },
          "tailId": {
            "type": "string"
          }
        },
        "title": "AffectedDevice"

The the code generated from this Schema is looking like this:
        /// <summary>
        /// Gets or Sets LastCheckin
        /// </summary>
        [DataMember(Name = "lastCheckin", EmitDefaultValue = false)]
        public DateTimeOffset LastCheckin { get; set; }

        /// <summary>
        /// Gets or Sets LastDownload
        /// </summary>
        [DataMember(Name = "lastDownload", EmitDefaultValue = false)]
        public DateTimeOffset LastDownload { get; set; }

My goal is to make the type of lastCheckin and lastDownload to be nullable. So basically the type to be: DateTimeOffSet?


text:
Q: Remove header line in chapter opening (Context) I'd like to remove only the header line, and only for chapter openings, but keeping the header at the chapter. I know its not usual. Is there any way to do it automatically?
\setupheader
  [text]
  [before={\startframed[frame=off,bottomframe=on,framecolor=blue,]},
   after={\stopframed},
  ]
\setupheadertexts[Text left][Text right]

\starttext

%\setupheader
%  [text]
%  [before=,
%   after=,
%  ]
\chapter{asdf}

\page
%\setupheader
%  [text]
%  [before={\startframed[frame=off,bottomframe=on,framecolor=blue,]},
%   after={\stopframed},
%  ]
\section{asdf}

\stoptext

A: Dirty trick using subpage numbers:
%For testing only
%\setuppapersize[A6]
\setupsubpagenumber[way=bychapter,state=start]
\startsetups zza
\doifelse{\the\numexpr\subpageno\relax}{1}{\startframed[frame=off]}{\startframed[frame=off,bottomframe=on,framecolor=blue,]}
\stopsetups
\setupheader
  [text]
  [before=\setup{zza},
   after=\stopframed,
  ]
\setupheadertexts[Text left][Text right]
\starttext
\chapter{Dari balgeun bam...}
\dorecurse{3}{\samplefile{knuth}}
\chapter{Siltago malhae...}
\dorecurse{3}{\samplefile{tufte}}
\stoptext


text:
Q: Rapid click event handling on Android If you very quickly tap 2 separate buttons, or even the same button, Android will process both click events. This becomes an issue when it can start services twice, or show dialogs twice, or start activities over each other, etc.
The fix for preventing double taps on a single button is pretty straight-forward and the answer is all over StackOverflow. You can simply check whether the button has been clicked using a boolean flag and stop processing any further click events.
My issue is that the user may rapidly press two (or more) different buttons (or list items, or ActionBar items, etc). Handling every combination of "has button x been clicked -> better disable button x, y, z" would be really tedious and error prone.
Does anyone have a decent solution to this?

A: I'll pitch in my .02, although this might not qualify as a decent solution. It's simple and doesn't take into account e.g. enabling of buttons, scheduling or any other sophisticated action. It may remove some boilerplate, for example disabling of buttons, but comes at a price of the ugly try-finally syntax:
public final class EventLocker {

    private static Object lock;

    public static synchronized boolean lock(final Object object) {
        if (null == object) { throw new IllegalArgumentException("object must not be null"); }
        if (null == lock) {
            lock = object;
            return true;
        }
        return false;
    }

    public static synchronized boolean release(final Object object) {
        if (null != lock && lock.equals(object)) {
            lock = null;
            return true;
        }
        return false;
    }

}

Then, let's say you wish to set an OnClickListener on a button:
button.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        if (EventLocker.lock(view)) {
            try {
                doSomething();
            } finally {
                EventLocker.release(view);
            }
        }
    }
});

If you consistently use the lock-unlock idiom, you're guaranteed e.g. Button B will not do anything until Button A releases the lock. On the plus side, it's easy enough to add custom requirements, if need be.

Answer to the first comment below:
You're absolutely right - a bit of sloppiness on my side for not specifically mentioning that in my answer.
Every onClick() event, for example, is post to the main thread queue. Funny enough, it brings up a topic I was inevitably trying to avoid; if the button click events are processed sequentially and don't leave the main thread, then e.g. double tap is not an anomaly but rather two valid actions being processed one after another in a short period of time.
There really is nothing wrong with that - a short period of 150 milliseconds might not make sense, but 10 seconds might be a completely viable option. In cases like these, I believe it's best to make sure the onClick implementations are clever enough to reuse, rebuild or in any other way handle resources at hand.

A:
If you very quickly tap 2 separate buttons, or even the same button, Android will process both click events. This becomes an issue when it can start services twice, or show dialogs twice, or start activities over each other, etc.

A well-written UI is idempotent, often via validation:

*

*don't start the service if you did that already

*don't show the dialog if the dialog is showing

*don't start another activity if you already did and have not yet been stopped yourself

*don't re-delete an item that is already deleted

*etc.

In some cases, developers don't worry about being fully idempotent because the framework handles it (e.g., given a well-written onStartCommand() method, starting a service twice should not be an issue; you cannot delete the same _ID twice). In some cases, developers don't worry about being fully idempotent because the impacts on the user are non-destructive (e.g., starting an activity twice). In some cases, developers don't worry about the problem because the trigger mechanism effectively blocks duplicate effects (e.g., long-press).
And in some cases, we're just lazy. :-)
But the validation should be for the work, not the trigger. Whether we are starting the service due to a button click, an action item click, a list row click, a shake of the device, an incoming GCM message, or whatever, we need to ensure that the work is handled in an idempotent fashion.

My issue is that the user may rapidly press two (or more) different buttons (or list items, or ActionBar items, etc).

This is transcending idempotence. It is also fairly unlikely, insofar as users just aren't that fast in moving their finger -- it's the sort of thing that the Test Monkey will run into more than will ordinary humans. And, it's the sort of thing that, AFAIK, few developers worry about.
If you really want to worry about it, then come up with the minimal possible set of "worry". For example, if the user taps two action bar items in succession, one of which marks the currently-viewed detail as a favorite, and the other of which pops up a dialog to allow the user to associate a password with the currently-viewed detail, who cares? Why is this intrinsically invalid?
But beyond that, yes, it's going to be tedious. You'll need to track all the possible "don't do this work in rapid succession" and determine whether or not you have hit a "rapid succession" case in the various callbacks (onClick(), onListItemClick(), onOptionsItemSelected()). A lot of the code can be factored out into some sort of EventMonitor that knows your business rules and can report whether you hit a rapid-succession scenario.


text:
Q: How can/do I configure my Spring app to check a specific tag of configs with custom directory? Suppose I have the following dir:

*

*root.properties

*dev-ci

*

*common.properties

*app_dir

*

*app.properties

*prod

*stage

*test

test/stage/prod all follow dev-ci's dir/path structure.
How can I setup my bootstrap.yml file so that when I start my app, it'll load the following:

*

*root.properties

*dev-ci/common.properties

*dev-ci/app_dir/app.properties

Is there a way to set up my yml so that it takes some parameter from commandline? Or will I have to map out all the possible 'paths' then pass in some label/name?
Lastly, where does the tag name come into play?


text:
Q: How to call the new data in JSON file for javascript I want to retrieve the data for use again, how to use it?
example script
const data = { a: 1, b: 2, c: 3 }

function deleteData() {
    const newData = data
    for (let index = 0; index < 2; index++) {
        if (index === 1) {
            delete newData.a
        }
    }
}
deleteData()
console.log("old data: "+ data)
console.log("new data: "+ newData)

expected
old data: { a: 1, b: 2, c: 3 }
new data: { b: 2, c: 3 }

A: use Object.assign or spread syntax.
const data = { a: 1, b: 2, c: 3 }
const newData = Object.assign({}, data)    // or {...data}

function deleteData() {
    for (let index = 0; index < 2; index++) {
        if (index === 1) {
            delete newData.a
        }
    }
}
deleteData()
console.log("old data: ", data)
console.log("new data: ", newData)

A: const data = { a: 1, b: 2, c: 3 }
function deleteData() {
    const newData = Object.assign({}, data)
    for (let index = 0; index < 2; index++) {
        if (index === 1) {
            delete newData.a
        }
    }
    console.log("new data: ", newData)
}
deleteData()
console.log("old data: ", data)

A: A few points:

*

*I'm not sure if you are trying to delete multiple elements from the object or if you are just trying to delete one. If you are only deleting one, you don't need the for loop. Just delete it directly.

*The const keyword declares a variable inside the nearest block scope. In your case, that is the deleteData function. You need to either declare it as a let outside of the function or as a var inside, or return it from the function.

*When you are deleting the item, the object is not a new object, but a reference to the old object. Therefore, both are being modified. To prevent this, copy the object into a new object and modify that. To do this, use Object.assign, or simply use the spread operator.

The best way to do this is like this:
const data = { a: 1, b: 2, c: 3 }

function deleteData(oldData) {
    const updated = {...oldData};
    delete updated.a;
    return updated;
}
const newData = deleteData(data);
console.log("old data: "+ data)
console.log("new data: "+ newData)

Some reference reading: Scope in Javascript, spread operator.


text:
Q: PHP printing on command prompt / terminal but not on browser I had been asked in an interview for PHP. In a PHP file index.php, there are 4 lines of code:

*

*Line 1 Takes input from user

*Line 2 Encrypts the User input

*Line 3 Decrypts the the Encrypted User input of line 2

*Line 4 Prints the Decrypted content of line 3

On executing this file via command prompt/terminal like php index.php, Original User input of line 1 gets printed/displayed by Line 4 in the command prompt/terminal but when opened/executed in browser the same code did not display anything.
What could be the reason ?
Please explain if anyone knows, would be helpful in future interviews if asked.

A: This could happen if the user input is a valid HTML tag, e.g. something as simple as
<b>

Or any other valid tag.
This value would still be output by the PHP program but the browser would see it as HTML and treat it as instructions rather than displaying it directly in the web page. You'd still be able to see it via the element inspector in the browser's Developer Tools.


text:
Q: Duplicity on macos not working, getting: env: python2: No such file or directory I'm trying to run duplicity on macos and I'm getting this error:

env: python2: No such file or directory

IMHO there is a link missing between python2 and python2.7 but I'm not sure
Is it safe to create a link from /usr/bin/python2 to /usr/bin/python for fixing this? Or would it be better to change duplicity to use /usr/bin/python?

A: You can create a symlink, but it is better to create it in /usr/local/bin/ or somewhere else where your normal user account has access, rather than globally in /usr/bin/ (which requires root access to modify).
Personally, I find if your install brew and Python from brew, not only do you get the latest Python builds, but it also manages these path problems for you.
Read more about brew at https://brew.sh/


text:
Q: Is there a way to limit heap space when running a single JUnit test? I have some code that needs to be able to run on systems with limited memory (i.e., 1750MB), and I have a JUnit test specifically for that code. However, my Jenkins integration server that runs the unit tests runs with a heap space set to 4GB.
On my development workstation in Eclipse, I can manually run the unit test with a VM argument of -Xmx1750m.
Is there some annotation that I can add to an individual JUnit test case that would force the test to run with the above VM argument (without affecting other unit tests)?

A: A JUnit Test is nothing more than a Java class that runs inside the JVM. Thus, it will be difficult to specify these constraints for just a single unit test. In the end, you would have to configure the JVM itself.
To achive this, you can use a seperate configuration for your tests, here demonstrated with Maven. First, you can make use of the surefire-plugins argLine configuration property to configure the environment. Next, limit the class to be tested with the include configuration, as described here.
<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-surefire-plugin</artifactId>
    <version>...</version>
    <configuration>
        <argLine>-Xmx2048m</argLine>
        <includes>
            <include>...</include>
        </includes>
    </configuration>
</plugin>

Then, use a custom profile that is probably triggered by a property active on your build server.
<profile>
    <id>low-memory-tests</id>
    <activation>
        <property>
            <name>...</name>
        </property>
    </activation>
</profile>

Notes:

*

*Even if you run only one single unit test in this profile, you still cannot guarantee that just the test can consume 2048m of heap space, but the whole application. But i suppose that this would be a good bet.

*Even if you are not using Maven, other build tools should have a similar way to apply above configuration, you get the idea.


text:
Q: Answer migrated from private beta not attributed
Original Question (I had the 2nd answer) - What guidelines should I follow while designing a library?

Not too long ago, I was part of the Arduino private beta. Unfortunately it got closed down, and the answers were therefore migrated to other sites. Having had the foresight to create a EE.SE account, the answers migrated there are linked to my profile. However, after being notified one had been moved to Programmers.SE, I created an account there - but, even several weeks later, my answer doesn't belong to me. Is this a bug, or is it my fault for not creating an account first?

A: I fixed up the attribution, so you should have ownership of that answer back now.
Because Arduino.SE was closed, the question no longer has migration history (since it'd just lead nowhere), and that is likely why the answer wasn't properly associated with your account.


text:
Q: Netbeans code format braces in PHP single line statements Intro
Im developing PHP in NetBeans IDE 7.2 (Build 201207171143) and I love the formatting to clean up my code in my custom format.
At the moment I work in a group with colleagues. Some of my colleagues are used to write single line statement without braces (I think this is bad practice).
Examples
What my colleagues do:
<?php

     if($stackoverflow == 'Cool')
           echo 'Stack Overflow is Cool!';

?>

What I want when I format the code.
<?php

     if($stackoverflow == 'Cool') {
           echo 'Stack Overflow is Cool!';
     }

?>

Question
So what I am looking for is the setting to achieve this. I can find every other setting to have nice braces.
Tools -> Options -> Editor -> Formatting -> PHP
WhatHaveITried
I have found this but I think this isn't the way for what I want to achieve since he talks about macros.
Could someone help me with this?

A: I am not sure if u have find the solution or not
Tools -> Options -> Editor -> Formatting
Language: PHP
Category: Braces
Select "same line" for all

A: Agree on a shared coding style! Don't rely on your editor to format and unformat code for you.
As for this example, I would argue that using brackets is better since it's less error prone - but this is something you have to agree upon with your collegues!

A: Ok so it isn't possible I guess.

A: It is possible to format braces in PHP.
This is an example:

A: I finally found the answer to this. It is found under Options -> Editor -> Formatting -> select PHP under the language drop down -> select "Wrapping" category -> scroll down to see "If Statement" and select "Never".


text:
Q: Magento product watermarks are not appearing transparent - any ideas? I have a Magento ver. 1.3.3.0 install, I am having a problem with the transparency of product watermarks.
The watermark is a .png file but when it is viewed on the product it loses its transparency and has a solid white background. The products on the shop are a wildlife artists paintings so this is really spoiling the artwork.
Has anyone experienced this with 1.3.3.0? Upgrading at this stage is not really an option as the site needs to go live soon.
Regards
Dan

A: If it only happens with PNG files and you have guaranteed that the original has the proper transparency then are you viewing the page in Internet Explorer?
Older versions of Internet Explorer don't properly render PNG alpha values, meaning that PNG transparency doesn't work. There are multiple javascript fixes for it online.
If it happens in Chrome/Firefox/Safari then post your CSS, as there may be a line affecting the alpha transparency of PNG files.

A: http://www.magentocommerce.com/bug-tracking/issue?issue=6020
known bug with your version - if you paste the 1.3.2.1 version of lib/varien/image/adapter/Gd2.php into your 1.3.1 version of Magento may be a quick fix.  Be sure and make a backup before overwriting the file, and I would suggest keeping a copy to rename upon performing a full upgrade.


text:
Q: get the custom post type data using a custom field value in wordpress Can I get the data using custom field value? My post_type is brand-name and the field name is generic-name. So How can I get all the data using the generic-name?
Here is the code:
$title = get_the_title();
$the_query = new WP_Query( array(
          'posts_per_page'=>9,
          'post_type'=>'brand-name',
          'order'   => 'ASC',
          'meta_query' => array(
           array(
                'key' => 'generic-name',// this key is advance custom field: type post_object
                'value' => $title,
                'type'  => 'char' // type not working
           ),
        ),
        'paged' => get_query_var('paged') ? get_query_var('paged') : 1)
      );`

This code was not working.

A: Your AFC field is a post object, which means the meta value is either a single post id, or a serialized array of post ids.
If your custom field is set to only allow a single selection, then it will be a single id, and can be queried like this:
$post_id = get_the_ID();
$the_query = new WP_Query( array(
      'posts_per_page'=>9,
      'post_type'=>'brand-name',
      'order'   => 'ASC',
      'meta_query' => array(
       array(
            'key' => 'generic-name',// this key is advance custom field: type post_object
            'value' => $post_id,
       ),
    ),
    'paged' => get_query_var('paged') ? get_query_var('paged') : 1)
  );`

If your custom field allows multiple selection, then it will a serialized php array of ids. Since mysql does not know how to read php serialized data, the best you can do is use a LIKE query:
$post_id = get_the_ID();
$the_query = new WP_Query( array(
      'posts_per_page'=>9,
      'post_type'=>'brand-name',
      'order'   => 'ASC',
      'meta_query' => array(
       array(
            'key' => 'generic-name',// this key is advance custom field: type post_object
            'value' => sprintf("\"%s\"", $post_id),
            'compare' => 'LIKE'
       ),
    ),
    'paged' => get_query_var('paged') ? get_query_var('paged') : 1)
  );`

A: I think this may help you. Please have a look at this.
Can I get the data using custom field value? -- Yes, you can get the data using custom field value.
First, we can get the custom field value by using the below code.
 <?php $custom_field_value= get_post_meta( get_the_ID(), 'generic-name', true ); ?>

This $custom_field_value return the value of 'generic-name' field.
By using that value we can form WP_Query.
$the_query = new WP_Query( array(
      'posts_per_page'=>9,
      'post_type'=>'brand-name',
      'order'   => 'ASC',
      'meta_query' => array(
       array(
            'key' => 'generic-name',
            'value' => $custom_field_value
       ),
    ),
    'paged' => get_query_var('paged') ? get_query_var('paged') : 1)
  );

Thanks.


text:
Q: How to implement HATEOAS with CQRS? Let's say I have a CQRS system where my write model contains the business rules. My read model is simply a DTO; it is a collection of properties and "dumb".
Now if you were to create a REST api, it would use this read model and return it.
Now I want to add HATEOAS to this REST api. Meaning that instead of just returning the data (let's say this is a reservation), it would also return links for cancelling the reservation and updating it.
These links should of course only be added when the user that is requesting the reservation is allowed to do so; if the reservation is already cancelled or the user is not the person that made the reservation, the link should not be added.
I do not really understand how this could work with CQRS. Our read model only has dumb properties; code like "CanCancelReservation()" lives in the write model, a part of the system our rest api doesnt (shouldnt?) Have access to.
So how could we still use HATEOAS in this scenario?
Some ideas I have but am not really happy with:

*

*the links could be generated in our write model and stored in the event
-- this doesn't solve the problem that only authorized people can perform certain actions. (Because that also lives in the write domain, right)
-- also, shouldnt the events and write model not be concerned with the HATEOAS part?

*the business logic is shared and can be accessed by the api as well
-- we use 2 different classes/models so this can be a bit ugly

I am curious for your ideas!

A:
Now if you were to create a REST api, it would use this read model and return it.

I don't think it would. Does an amazon product page return a dumb list of all product properties?
First, I think the design itself is strange. When you say "read model" I guess you mean the persisted data structure or some view thereof. The design in the code should reflect the business case at hand, not a technical detail. CQRS, or whatever persistence strategy is used, should not be visible in any of the objects. It's a detail.
Also, HATEOAS is not just about providing links. It's basically about building a web-site, where you can navigate through your workflow (defined by the server) from start to finish, just by choosing options provided by the server.
So the short answer to "how" is to hide implementation details more, then you may find the proper place to generate web-pages from.

A:
Now if you were to create a REST api, it would use this read model and return it.

You cannot implement a complete, full-featured REST API and link it just to the read model.
When handling a GET request, your REST API would indeed fetch the relevant data through the read model, but for handling a PUT, POST or DELETE request, the REST API definitely needs to use the write model.
As the REST API needs to have access to both the read and write models anyway, there is no real obstacle to accessing (parts of) the write model also when handling a GET request in order to determine what metadata (e.g. links) can be included in the response.
On the other hand, if it can happen more frequently that the REST API has to decide if certain data from the read model needs to be shown or not, you might want to consider extending the read model with logic that can answer such questions. For example, which details the current user is allowed to see of another user.

A:
Now I want to add HATEOAS to this REST api. Meaning that instead of just returning the data (let's say this is a reservation), it would also return links for cancelling the reservation and updating it.

So I think you have a misunderstanding of HATEOAS.
HATEOAS doesn't mean that you perform actions on a resource via hyperlinks to commands like cancelling or updating.
So if your URLs look something like this
reservation/343/cancel
reservation/343/update

you are not following HATEOAS.
Remember REST is REpresentational State Transfer. You change the current state of a resource (such as reservation/343) by transfering an updated state of that resource from the client to the server. The URL stays the same.
And this fits neatly with CQRS, since in HTTP there is a read request (GET) and requests that change the state of the resource (PUT, DELETE). Your server can neatly handle these requests through different paths in your application.
To simply read current state of the reservation from the server the client just does a GET reservation/343 returning some representation such as
{
  customer: 'customers/123',
  status: 'live'
}

To cancel this reservation you could just ask the server to delete it (DELETE reservation/343) or probably more commonly update it since most reservation systems want to keep a record of cancelled reservations
PUT reservation/343
{
   customer: 'customers/123',
   status: 'cancelled'
}

note here the client has changed the status field to cancelled and asked the server to update its version via a PUT.
The server will need some logic to figure out what has changed and do anything it needs to do because of this change (update a database, email a customer etc), but that is for the server to worry about. And most importantly all that logic for updating the server can be piped through your 'write' pipeline in the application.
You can tell easily what requests are going to potentially write to the system just be looking at the HTTP verb (GET vs PUT,DELETE etc). Maybe the client doesn't have authorisation to update the resource to cancelled? That check only has to be done when you get a PUT request from the server, the GET request can ignore it because with a GET the client is not attempting to update any state of the resource.
This is all standard REST.
So what does HATEOS mean if it doesn't mean making command URLs for actions to carry out on the resource.
Well look at the representation of the reservation. Notice that the customer field for the customer that booked the reservation isn't just an id. It is a hyperlink.
We could have just put an id there
{
   customer: 123,
   status: 'cancelled'
}

but then the client would have to know how to turn that id into a URL in order to navigate to the customer who made this reservation.
Instead when you use a link if the client wants to start at a reservation and then navigate to the customer that made the reservation it simply follows that hyper link to get to the customer. It doesn't have to know in advance how to construct that hyperlink from a customer id.
And, importantly, the server might change the URL scheme at some point, but the client won't care because it is just following the hyper link.
So say next week the server developers decide that the URL scheme needs and update. All of a sudden clients are getting this resource back
{
  customer: 'europe/customers/123',
  status: 'live'
}

The clients won't care. Yes the customer's URL has changed, but the client doesn't care because all it did was follow what ever URL was for that customer.
So HATEOAS simply says that any time you have another resource in the system represent it as a URL so that the client can navigate to it using hypertext links.


text:
Q: How to check in linq if the list is null? i am binding a checked list box with following ling that retrun a list list, but if the list is empty how should i manage it?
It throws exception in the ling statment and if null what should i set for checkedlist box
public List<dataObject> GetAllCustomItems(CategoryType currType, int mCategoryID)
        {
            List<dataObject> lst = null;
            try
            {
                switch (currType)
                {
                    case CategoryType.Dressing:
                        lst = (from xx in this.DressingItems
                               where xx.DressingInfo.CatID == mCategoryID
                               select new dataObject() {
                                   ID = xx.DressingInfo.DressingID,
                                   Name = xx.DressingInfo.Description,
                                   Selected = xx.IsDefault
                               }).ToList();
                        break;
              }
        }

It throws exception
Value cannot be null.
Parameter name: source

A: Are you sure this.DressingItems is not null or empty?
Check that before your LINQ query:
if (this.DressingItems != null && this.DressingItems.Any()) {
    lst = (from xx in this.DressingItems where...
}

Let the lst return null if DressingItems is null or empty.
Edit: (after the op comment)
Also, check the DressingInfo property:
where xx.DressingInfo != null &&...

A: How about checking DressingInfo for null first in the where clause
where xx.DressingInfo != null && xx.DressingInfo.CatID == mCategoryID

A: I don't think is xx.DressingInfo object problems cause it will come out Object reference not found first, sure is the values from xx.DressingInfo got problems. you can try iif to check it.
  var lst = (from xx in this.DressingItems
                           where xx.DressingInfo.CatID == mCategoryID
                           select new dataObject() {
                               ID = xx.DressingInfo.DressingID==null?0:xx.DressingInfo.DressingID,
                               Name = xx.DressingInfo.Description==null? "":xx.DressingInfo.Description,
                               Selected = xx.IsDefault
                           });
return IsNullThenNew<dataObject>(lst);

If you don't want to return null back to caller, you can return at least empty object by generic method below.
 public static bool IsNullOrEmpty<T>(this IEnumerable<T> enumerable)
        {
            return enumerable == null || !enumerable.Any();
        }
 public static List<T> IsNullThenNew<T>(this IEnumerable<T> t)
        {
            if (!IsNullOrEmpty<T>(t))
            {
                return t.ToList();
            }
            else
            {
                Type genericListType = typeof(List<>);
                Type listType = genericListType.MakeGenericType(t.GetType());
                object listInstance = Activator.CreateInstance(listType);
                return (List<T>)listInstance;
            }//end if-else
        }

A: You could change List<dataObject> lst = null;
to List<dataObject> lst = new List<dataObject>;
Or do something like this:
public List<dataObject> GetAllCustomItems(CategoryType currType, int mCategoryID)
{
    try
    {
        switch (currType)
        {
            case CategoryType.Dressing:
                List<dataObject> lst = (from xx in this.DressingItems
                       where xx.DressingInfo.CatID == mCategoryID
                       select new dataObject() {
                           ID = xx.DressingInfo.DressingID,
                           Name = xx.DressingInfo.Description,
                           Selected = xx.IsDefault
                       }).ToList();
                break;
      }
}


text:
Q: How can I tell a function enters kernel or not I am implementing a program to run in user space as often as possible. So I am trying to call functions which enter and leave kernel space as less as possible. For example, I use some DMA API which read/write but bypass the kernel.
I don't know how to tell a function needs to enter kernel space or not. For example, I want to call getenv() to get environment variables set by the host, but worrying it may pass my program and enter the kernel space. I cannot find this imformation from man pages. Here is the man page of getenv().

A: Have you run your program through strace?  That will let you know where you are making system calls that will enter kernel space

A: I thinks most IO functions will cause your program to the kernel?
Maybe you should check the system APIs that used by you


text:
Q: Are "thread-safe" functions parallelization framework dependent? I have this simple MATLAB code which calls imregionalmax in a parallel loop
over 256 pathces of 16X16 pixels.
function y = Parimregionalmax(x)
   assert(isa(x,'uint8'));
   assert( all(size(x)==[16 16 256]) );
   y = zeros(size(x));
   parfor k = 1:size(x,3)
     y(:,:,k) = imregionalmax(x(:,:,k));
   end
end

Giving this code to MATLAB's Coder gives the following C code:
/*
 * Parimregionalmax.c
 *
 * Code generation for function 'Parimregionalmax'
 *
 */

/* Include files */
#include "rt_nonfinite.h"
#include "Parimregionalmax.h"
#include "libmwimregionalmax.h"

/* Function Definitions */
void Parimregionalmax(const unsigned char x[65536], double y[65536])
{
  int k;
  int i0;
  int i1;
  double imSize[2];
  unsigned char varargin_1[256];
  boolean_T conn[9];//unsigned char
  double connSize[2];
  boolean_T BW[256];

#pragma omp parallel for \
 num_threads(omp_get_max_threads()) \
 private(i0,i1) \
 firstprivate(varargin_1,imSize,conn,connSize,BW)

  for (k = 0; k < 256; k++) {
    for (i0 = 0; i0 < 16; i0++) {
      for (i1 = 0; i1 < 16; i1++) {
        varargin_1[i1 + (i0 << 4)] = x[(i1 + (i0 << 4)) + (k << 8)];
      }
    }

    for (i0 = 0; i0 < 2; i0++) {
      imSize[i0] = 16.0;
    }

    for (i0 = 0; i0 < 9; i0++) {
      conn[i0] = true;
    }

    for (i0 = 0; i0 < 2; i0++) {
      connSize[i0] = 3.0;
    }

    imregionalmax_uint8(varargin_1, BW, 2.0, imSize, conn, 2.0, connSize);
    for (i0 = 0; i0 < 16; i0++) {
      for (i1 = 0; i1 < 16; i1++) {
        y[(i1 + (i0 << 4)) + (k << 8)] = BW[i1 + (i0 << 4)];
      }
    }
  }
}

/* End of code generation (Parimregionalmax.c) */

As you can see, the generated code (which works perfectly) uses openmp parallelization framework and calls the function imregionalmax_uint8 which is implemented in a separate "black-box" dll (with corresponding header and lib files).
Can I assume that this fuction is always thread safe no matter which parallelization framework I use?
Examples:
1.Is it OK to define two threads using C++ <thread> library in a console
  application (a.k.a exe file in VS) and call from  each thread to
  imregionalmax_uint8?

*Do two separate dlls (loaded by exe file) can call this function
simultaneously?

A: Yes and no.
No, because next to nobody writes out good guarantees for this kind of thing.  This is a wonderful podcast about NVidia using C++'s threading model to finally formalize a threading system, with the complaint that prior to C++'s attempts most abstract threading/memory models out there where crap.  At best you'd get very arcane and specific information about a specific set of hardware, or claims that you worked like some other (usually more ancient) hardware.
Except yes, because in practice, the kinds of mutexes and synchronization and the like they are using are going to be compatible on pretty much every desktop system.  Maybe less so on mobile computing CPUs and other more obscure systems.


text:
Q: Inviting People To A Party With Limitations
A person has 8 friends, of whom 5 will be invited to a party.
  (b) How many choices if 2 of the friends will only attend together?

Using inclusion-exclusion there are ${8\choose 5}-{2\choose 1}\cdot{6\choose 4}=26$.

Do counting the options that both of them were chosen ${6\choose 3}$  or both where not chosen ${6\choose 5}$, so overall the options are ${6\choose 3}+{6\choose 5}$ is it ok?


text:
Q: using boolean law to simplify equation I need to use boolean laws to simlfy the folliwng:
a) (A+B)(C+D)+(A+B)(C'+D')=
what I did for a)
(A+B)(C+D)+(A+B)(C'+D')
(A+B)[(C+D)+(C'+D'))
(A+B(C+B)+(A+B)(c'+D')
(A+B(C+B)+(A+B)(c'+D') Am I correct?
b) [A'(C+D)')'(A)]+B(DC'')+(D'C')+A+CB'
What I did for b) A+(C+D)(A) + [B(DC)+(D'C'] + A + CB'
                 A[1+( c+d) + B + A + CB'

Am I correct?
Anyone can please clarify this?

A: Seems to me C and D get reduced-out:
(A+B)(C+D)+(A+B)(C'+D') =
(A+B)((C+D)+(C'+D')) =
(A+B)(C+D+C'+D') =
(A+B)(C+C'+D+D') =
(A+B)((C+C')+(D+D')) =
(A+B)(1+1) =
(A+B)1 =
A+B


text:
Q: Contents are missing in urllib2.urlopen() Am parsing a web page by sending a request as,
request = urllib2.Request(urllink, None, {'User-Agent':'Mosilla/5.0 (Macintosh; Intel Mac OS X 10_7_4) AppleWebKit/536.11 (KHTML, like Gecko) Chrome/20.0.1132.57 Safari/536.11'})
print request
urlfile = urllib2.urlopen(request)
page = urlfile.read()
soup = BeautifulSoup(page)

Here the problem is some of the contents in the web page are missing in response coming from  urllib2.urlopen(). If i saved the page, am getting all contents.
I have noticed that one more request is going inside the web page through ajax call. Is there any method in python to get whole page by sending request

A: AJAX is asynchronous JS and XML - it means that you GET document, and after loading in browser some content is dynamically donloaded and injected in DOM.
What does it mean for you? You have all informations needed to get full document, but... well you probably have no way to execute JS which will download and inject dynamic data.
How to bypas this? I haven't found any JS engine for python yet, but I'm still searching. Instead, you can use some browser engine using Selenium (it is library that comunicates with browser installed on your computer and allows you to simulate user actions, like clicks, inputs, etc). Then, you can inspect DOM after those actions and perform another actions.
Other way is using Jython (as you're using p2.7, it should be compatible) and taking advantage of Rhino, or any other JS engine for Java to execute this code.


text:
Q: How many types of URLRequest is possible in iPhone for retrieve the data from WebServices? In my app i am retrieve data from web services and show in uitableview it is fine but problem is that in mu tableview suppose 10 row (that is city name and latitude longitude of all city that are in my table) after the retrieve city name i m trying to get Distance between user location and city so 10 times i need to call google mapAPI, in that process my app is crash.
i am using NSURLRequest
i had also used ASIHttpRequest - networkQueue but not get success.
so how many other ways to do this?
please suggest me any other types of request to fix it.
thanx for any suggestion.
here is my code
for (NSUInteger i=0; i<[latlongarray count]; i++)
{
    NSString *urlString=[NSString stringWithFormat:@"https://maps.googleapis.com/maps/api/distancematrix/json?origins=%@&destinations=%@&avoid=tolls&sensor=true",str,[latlongarray objectAtIndex:i]];
    NSLog(@"%@",urlString);
    NSURL *url = [NSURL URLWithString:urlString];
    NSURLRequest *myrequest=[[NSURLRequest alloc] initWithURL:url];
    CustomConnection *distanceconnection=[[CustomConnection alloc] initWithRequest:myrequest delegate:self startImmediately:YES tag:[NSNumber numberWithInt:i]];
    [distanceconnection start];
    [distanceconnection release];
    [myrequest release];
}

str is user location, and latlongarray is array for city's location.

A: You can go NSURLRequest operation with either synchronous or asynchronous way. According to me, dealing with NSURLRequest asynchronously is more advisable when response being is depended for further executions.


text:
Q: Rename iOS app in iTunes Connect - "name will be reviewed" I'm creating a new release of an iOS app in iTunes Connect.
The release has been reviewed and approved by Apple.
However, on the App Information page the following is stated: "The name will be reviewed before it is made available on the App Store."
Does this mean that, for this release, there will be an extra delay after I click "Release this version"?

A: There shouldn't be an additional delay more than the time it usually takes for your app to be reviewed. The message is simply to indicate that your name change must be reviewed at all (so it may not get approved), not to indicate any additional time penalty for review.


text:
Q: layout works different on different mobile android I am making a video calling app i have made the designs for both persons.One who make call(sender) and other who receive call(receiver) but the problem i face is that on one mobile i will get my own stream and opponent stream but on other mobile which have different android version i will get the opponent stream but my own stream is not showing it will be in background.
samsung s4 image this image show me both the streams.
LG G3 not showing its own stream.it will be in background
But i have made the same layout for both sender and receiver.I think this problem is due to different android version on each mobile.please help me how to solve this issue.
sender:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">

<RelativeLayout
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">

    <RelativeLayout
        android:id="@+id/whencalling"
        android:layout_width="match_parent"
        android:layout_height="70dp"
        android:layout_alignParentBottom="true"
        android:background="#DB2727"
        android:orientation="horizontal"
       >

        <CheckBox
            android:id="@+id/muteVoume"
            android:layout_width="50dp"
            android:layout_height="wrap_content"
            android:layout_marginLeft="40dp"
            android:layout_marginTop="10dp"
            android:button="@drawable/mutedrawable" />

        <CheckBox
            android:id="@+id/switchCameraAction2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerInParent="true"
            android:layout_marginLeft="175dp"
            android:layout_marginTop="20dp"
            android:button="@drawable/cemeradrawable" />

        <CheckBox
            android:layout_width="50dp"
            android:layout_height="50dp"
            android:layout_alignParentRight="true"
            android:layout_marginLeft="30dp"
            android:layout_marginRight="30dp"
            android:layout_marginTop="10dp"
            android:button="@drawable/micdrawable" />

    </RelativeLayout>

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:orientation="vertical"
        android:layout_alignParentTop="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true">

        <include
            android:id="@+id/tool_bar"
            layout="@layout/tool_bar"></include>

        <RelativeLayout
            android:id="@+id/whencallhappens"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
          >

                    <LinearLayout
                        android:orientation="horizontal"
                        android:layout_width="fill_parent"
                        android:layout_height="match_parent"
                        >

                        <Space
                            android:layout_width="wrap_content"
                            android:layout_height="match_parent"
                            android:layout_weight="1"/>
                        <LinearLayout
                            android:orientation="horizontal"
                            android:layout_width="match_parent"
                            android:layout_height="match_parent"
                            android:id="@+id/llPrimary">

                            <io.skyway.Peer.Browser.Canvas
                                android:layout_width="match_parent"
                                android:layout_height="match_parent"
                                android:id="@+id/svPrimary"/>

                        </LinearLayout>

                        <Space
                            android:layout_width="wrap_content"
                            android:layout_height="match_parent"
                            android:layout_weight="1"/>

                    </LinearLayout>

            <LinearLayout
                android:orientation="horizontal"
                android:layout_width="match_parent"
                android:layout_height="wrap_content">

                <Space
                    android:layout_width="wrap_content"
                    android:layout_height="match_parent"
                    android:layout_weight="1.0"/>

                <LinearLayout

                    android:orientation="horizontal"
                    android:layout_width="160dp"
                    android:layout_height="160dp"
                    android:id="@+id/llSecondary"
                    >

                    <io.skyway.Peer.Browser.Canvas
                        android:layout_width="match_parent"
                        android:layout_height="match_parent"
                        android:id="@+id/svSecondary"/>

                </LinearLayout>

                <Space
                    android:layout_width="20px"
                    android:layout_height="10px"
                    />

            </LinearLayout>

            <Button

                android:id="@+id/callend"
                android:layout_width="50dp"
                android:layout_height="50dp"
                android:layout_alignParentBottom="true"
                android:layout_centerInParent="true"
                android:layout_gravity="center|bottom"
                android:layout_marginBottom="80dp"
                android:background="@drawable/endcall" />

        </RelativeLayout>

    </LinearLayout>
</RelativeLayout>

receiver:
<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">

<RelativeLayout
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">

    <RelativeLayout
        android:id="@+id/whencalling"
        android:layout_width="match_parent"
        android:layout_height="70dp"
        android:layout_alignParentBottom="true"
        android:background="#DB2727"
        android:orientation="horizontal">

        <CheckBox
            android:id="@+id/muteVoume"
            android:layout_width="50dp"
            android:layout_height="wrap_content"
            android:layout_marginLeft="40dp"
            android:layout_marginTop="10dp"
            android:button="@drawable/mutedrawable" />

        <CheckBox
            android:id="@+id/switchCameraAction2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerInParent="true"
            android:layout_marginLeft="175dp"
            android:layout_marginTop="20dp"
            android:button="@drawable/cemeradrawable" />

        <CheckBox
            android:layout_width="50dp"
            android:layout_height="50dp"
            android:layout_alignParentRight="true"
            android:layout_marginLeft="30dp"
            android:layout_marginRight="30dp"
            android:layout_marginTop="10dp"
            android:button="@drawable/micdrawable" />

    </RelativeLayout>

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_alignParentTop="true"
        android:orientation="vertical">

        <include
            android:id="@+id/tool_bar2"
            layout="@layout/tool_bar2"></include>

        <RelativeLayout
            android:id="@+id/whencallhappens"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
           >

            <LinearLayout
                android:layout_width="fill_parent"
                android:layout_height="match_parent"
                android:orientation="horizontal">

                <Space
                    android:layout_width="wrap_content"
                    android:layout_height="match_parent"
                    android:layout_weight="1" />

                <LinearLayout
                    android:id="@+id/llPrimary"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:orientation="horizontal">

                    <io.skyway.Peer.Browser.Canvas
                        android:id="@+id/svPrimary"
                        android:layout_width="match_parent"
                        android:layout_height="match_parent" />

                </LinearLayout>

                <Space
                    android:layout_width="wrap_content"
                    android:layout_height="match_parent"
                    android:layout_weight="1" />

            </LinearLayout>

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="horizontal"
                >

                <Space
                android:layout_width="wrap_content"
                android:layout_height="match_parent"
                    android:layout_weight="1.0" />

                <LinearLayout
                    android:id="@+id/llSecondary"
                    android:layout_width="160dp"
                    android:layout_height="160dp"
                    android:orientation="horizontal">

                    <io.skyway.Peer.Browser.Canvas
                 android:id="@+id/svSecondary"
                 android:layout_width="match_parent"
                 android:layout_height="match_parent"
                  />

                </LinearLayout>

                <Space
                    android:layout_width="20px"
                    android:layout_height="10px" />

            </LinearLayout>

            <LinearLayout
                android:layout_marginBottom="80dp"
                android:id="@+id/Not_received"
                android:layout_width="wrap_content"
                android:layout_height="60dp"
                android:layout_alignParentBottom="true"
                android:layout_centerInParent="true"
                >

                <Space
                    android:layout_width="220dp"
                 android:layout_height="match_parent"
                    android:layout_weight="1.0" />

                <Button
                    android:id="@+id/ReceiveCall"
                    android:layout_width="50dp"
                    android:layout_height="50dp"
                    android:layout_marginBottom="80dp"
                    android:layout_marginRight="20dp"
                    android:background="@drawable/callpick" />

                <Button
                    android:id="@+id/EndCall"
                    android:layout_width="50dp"
                    android:layout_height="50dp"
                    android:layout_marginBottom="80dp"
                    android:background="@drawable/endcall"
                    />

                <Space
                    android:layout_width="300px"
                    android:layout_height="match_parent" />

            </LinearLayout>

            <LinearLayout
                android:layout_width="wrap_content"
                android:layout_height="60dp"
                android:layout_marginBottom="80dp"
                android:layout_alignParentBottom="true">

                <Space
                    android:layout_width="250dp"
                    android:layout_height="match_parent"
                    android:layout_weight="1.0" />

                <Button
                    android:id="@+id/EndVideoCall"
                    android:layout_width="50dp"
                    android:layout_height="50dp"
                    android:layout_marginBottom="80dp"
                    android:background="@drawable/endcall" />

                <Space

                    android:layout_width="350px"
                    android:layout_height="match_parent" />

            </LinearLayout>

        </RelativeLayout>

    </LinearLayout>
</RelativeLayout>

A: Use The Scalable Size Unit :
-To add sdp to your project Using Android Studio and Gradle :
   dependencies {
        compile 'com.intuit.sdp:sdp-android:1.0.4'
   }

-for Example Use in xml :
 <ImageView
    android:id="@+id/spin_view"
    android:layout_width="@dimen/_20sdp"
    android:layout_height="@dimen/_60sdp"
    android:layout_centerHorizontal="true"
    android:layout_marginTop="@dimen/_120sdp"/>

A: Use this to support all resolution devices :
https://github.com/intuit/sdp
sdp for margin/padding and ssp for font size.


text:
Q: How to get an existing EKS cluster's OIDCProvider using CDK? I have an existing EKS cluster (Created by a separate CF stack) and I want to extract the OIDCProviderURL associated with that cluster using CDK.
Here's my snippet of code
const k8sCluster = <eks.Cluster>(eks.Cluster.fromClusterAttributes(this, "k8scluster", {
      clusterName: "k8s-sample"
    }))
const oidcprovider = k8sCluster.clusterOpenIdConnectIssuerUrl

When I execute cdk synth the oidcprovider value is undefined. The documentation for Cluster.fromClusterAttributes mentions that the output would be "undefined" if the cluster is not kubectl-enabled. I am not sure what is meant by kubectl-enabled. Can anyone let me know how I can get the k8s cluster's OIDC provider using CDK.

A: I have a very simple cluster definition here . CFN returns the oidc issue url for the cluster with both the output values I have defined there.
    cdk.CfnOutput(
        self,
        "oidcendpointurl",
        value=_cluster.cluster_open_id_connect_issuer_url
    )

    cdk.CfnOutput(
        self,
        "oidcendpoint",
        value=_cluster.cluster_open_id_connect_issuer
    )


text:
Q: How do I change img size on click, and return it to normal on toggle using javascript? I want an image in an html file to change in size by 50% and toggle back to normal size on a second click. I tried to do it the same way I do onmouseover but it's not working. Does anyone have any ideas on how to do this in javascript?
html code -

Featured Artists

external javascript -
    function func3() {
       x = document.getElementsByTagName("img")[11];
       x.height = 50%;
       x.width = 50%;
    }

A: Here's a much simpler example making use of transforms. Just toggle a class on click.

document.querySelector("img").addEventListener("click", function(){
  this.classList.toggle("half");
});
img
{
  transition-duration: 0.4s;
}

img.half
{
  transform: scale(0.5);
}

If you really want it to change the size of the element and the flow, then you can just change the width/height inside the .half class.

document.querySelector("img").addEventListener("click", function(){
  this.classList.toggle("half");
});
img
{
  transition-duration: 0.4s;
  width: 100px;
  height: 100px;
}

img.half
{
  width: 50px;
  height: 50px;
}


text:
Q: How to call managed c++ dll functions in lua cpp module Description:
All my functions are defined in C# dll project.Then I wrap the c# functions in a cpp library project,Now I want to write a lua module using c++ and call the wrapper function.
Question:
How to call the wrapper functions in lua cpp module? Please give me some suggestions, Thanks!
Codes:

*

*libutilscore Project(C# DLL)
 namespace libutilscore
 {
     public static class SharpFTP
     {
         public static string ShowHello()
         {
             return "Hello From C Sharp.";
         }
     }
  }

*ManagedDll Project(C++ DLL)

*

*ManagedDll.h
#pragma once
#ifdef MANAGEDDLL_EXPORTS
#define MANAGEDDLL_API __declspec(dllexport)
#else
#define MANAGEDDLL_API __declspec(dllimport)
#endif

MANAGEDDLL_API const char *CPP_ShowHello();

*ManagedDll.cpp
#include "ManagedDll.h"
#include <string>
using namespace System;
using namespace std;
using namespace libutilscore;

namespace ManagedDll
{
   public ref class CS_FTP
   {
       public:
          static string CS_ShowHello()
          {
              String ^ message = libutilscore::SharpFTP::ShowHello();
              string result = "";
              MarshallString(message, result);
              return result;
          }
       private:
          static void MarshallString(String ^csstr, string &stdstr)
          {
              using namespace Runtime::InteropServices;
              const char *chars = (const char*)(Marshal::StringToHGlobalAnsi(csstr)).ToPointer();
              stdstr = chars;
              Marshal::FreeHGlobal(IntPtr((void *)chars));
          }

          static void MarshallWstring(String ^csstr, string &wstr)
          {
              using namespace Runtime::InteropServices;
              const char *wchars = (const wchar_t*)(Marshal::StringToHGlobalAnsi(csstr)).ToPointer();
              wstr = wchars;
              Marshal::FreeHGlobal(IntPtr((void *)wchars));
          }
    };
}

MANAGEDDLL_API string CPP_ShowHello()
{
    return ManagedDll::CS_FTP::CS_ShowHello();
}

*libutils Project(Lua CPP Module)

*libutils.h
#pragma once

#ifdef LIBUTILS_EXPORTS
    #define LIBUTILS_API __declspec(dllexport)
#else
    #define LIBUTILD_API __declspec(dllimport)
#endif // LIBUTILS_EXPORTS

*libutils.cpp
#include "libutils.h"
#include "lua.hpp"

LIBUTILS_API int showHello(lua_State *luaEnv)
{
    const char *msg = "";
    // TODO Call DLL function
    // msg = CPP_ShowHello().c_str();
    lua_pushstring(luaEnv, msg);
    return 1;
}

static const luaL_Reg libutils_funcs[] = {
    {"showHello", showHello},
    {"NULL", NULL}
};

LIBUTILS_API int luaopen_libutils(lua_State *luaEnv)
{
    luaL_newlib(luaEnv, libutils_funcs);
    return 1;
}

A: One option MAY be to make your "Lua CPP Module" a mixed-mode DLL.  I have answered previously on this topic, so read my instructions there on how to do it: VC++ Calling a function of /clr project from a function of non /clr project within a solution  The short answer is that you can compile specific parts of a DLL to use the CLR without making the whole thing that way, and then call between them.
Basically, once you've figured out how to call a mixed-mode DLL from PURE C++ code, then this problem is very similar.  I don't know about restrictions on LUA C++ modules, though I would presume if they can load/call other DLLs, then you're fine.
For extra fun, then figure out how to pass information all the way back and forth.  And calling pure C++ from C#/.NET.  Or callbacks to/from each.  That gets really fun quickly.


text:
Q: Transforming Kinect coordinates to character model I have the latest Kinect SDK, XNA 4.0, and a model with a skeleton and I'm looking into working with the kinect to create some simple games. I heard that various engines, such as the DigitalRune engine provide an easy way to map the skeleton generated from the Kinect sensor to the skeleton of the model.
Which engine is the best for this task and why? I'd prefer if you could list both the best free engine and the one you have to pay for, as well as any additional suggestion, should you have them.
I really need help with this. While I did manage to find about five engines that might suit my needs (Ploobs, Engine Nine, DigitalRune, Hilva, Xen, XNA Final Engine) I have no way of telling which is better than the other, as there is very little activity in the related forums and I really don't have the time (or, more importantly, the knowledge) to test all these engines.

A: I think XNA is better, because it gives more transparency when it comes to game programming, there is no doubt it is the most used for game programming and as a plus point you will have tons of tutorials. xna framework will be best even you can have e-books too.


text:
Q: Dynamic meta (keywords, description) I know that that this topic has been elaborated on many times, but I can still not figure out how to do it. Maybe My site structure is not like it should; I don't know.
Anyway, I have the following:
An Index.php containing a heading in which I have :
<meta name="description" content="<?php echo $pg_desc; ?>"/>
<meta name="keywords" content="<?php echo $pg_key; ?>"/>

This index.php is also containing all the referenced stylesheets and jquery code.
Then I have all content of the pages in SQL. Each page in my database is formatted as follows (as a longtext):
<?php ##commented out page name just for my own convenience ?>
<div class="#"
body
</div>

Now I thought I had to put
$pg_desc = "my page is about"
and
$pg_key = "you,name,it"
in the php part, but that did not seem to work. Can anyone help me?

A: You would need to declare that variables before outputting them to meta tags.
For example:
<?php
$pg_key = "you,name,it";
$pg_desc = "my page is about";
?>

<meta name="description" content="<?php echo $pg_desc; ?>"/>
<meta name="keywords" content="<?php echo $pg_key; ?>"/>


text:
Q: To create a login form using php, mysql and html I want to create a working login form. Here's what I have done and this displays cannot select db.
Edited login.php file
<?php
    error_reporting(E_ALL);
    //Connection Variables:
    $dbhost = "localhost";
    $dbname = "";
    $dbuser = "";
    $dbpass = "";
try{
    //Connection to SQL:
        $conn = new PDO("mysql:host=$dbhost; dbname=$dbname", $dbuser, $dbpass);
    //Error messagin enabled:
        $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    }
    catch (PDOException $e)
    {
        echo $e->getMessage();
    }

    $user = '';
    $pass = '';
    $sum = 0;
    $error_msg = "Please type a username and a password";
    if(isset($_POST['login']))
    {
        //Start a session:
        session_start();

        $user = $_POST['email'];
        $pass = $_POST['password'];
        if(empty($user) && empty($pass))
        {
            echo $error_msg;
            $pass = '';
        }
        if(empty($user) || empty($pass))
        {
            echo $error_msg;
            $user = '';
            $pass = '';
        }
        if(!empty($user) && !empty($pass))
        {
            //SQL:
            $query = $conn->prepare("SELECT * FROM login WHERE user = :u AND password= :p LIMIT 1");
            $query->bindParam(":u", $user);
            $query->bindParam(":p", $pass);
            //Execute query:
            $query->execute();
            $number_rows = $query->fetch(PDO::FETCH_NUM);
            if($number_rows>0)
            {
                echo $user;
                $_SESSION['usern'] = $user;
                $_SESSION['passw'] = $pass;
                header("Location: ./pages/home.php");
            }
            //echo $user;
            else
            {
                echo "Invalid username or password";
                header("Location: index.html");
            }
        }
    }
    if(!isset($_POST['login']))
    {
        echo "Login button not clicked";
    }
?>

I read more and more articles on this, still I can't find a solution.
Edited HTML
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <meta name="description" content="">
    <meta name="author" content="">
    <link rel="icon" href="../../favicon.ico">

    <title>Signin for OTMS</title>

    <link href="css/bootstrap.min.css" rel="stylesheet">

    <link href="signin.css" rel="stylesheet">

      <form action="login.php" method="post" class="form-signin">

Please sign in

        Email address
        <input type="email" name="email" id="inputEmail" class="form-control" placeholder="Email address" required autofocus>
        Password
        <input type="password" name="password" id="inputPassword" class="form-control" placeholder="Password" required>

            <input type="checkbox" value="remember-me"> Remember me

        <button class="btn btn-lg btn-primary btn-block" type="submit" name="login">Sign in</button>
      </form>

Please help me to find what is the error.
I created my database using phpMyAdmin and it's in localhost. And interfaces I designed using Bootstrap.
This is the error I'm getting now:

database name- otmsdb
table name- login
email, passowrd,
button name- login

A: Sir, your code is vulnerable to SQL injections. Please start using MySQLi or PDO. Here is a PDO code for login that should works fine with you:
Source: Udemy Online course.
EDIT: use this code, and change the variables into yours
<?php
session_start();
if(isset($_POST['login'])){
    $errmsg_arr = array();
    // configuration
    $dbhost     = "localhost";
    $dbname     = "your database name";
    $dbuser     = "your username";
    $dbpass     = "your password";

    // database connection
    $conn = new PDO("mysql:host=$dbhost;dbname=$dbname;charset=utf8mb4",$dbuser,$dbpass);
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    // new data

    $user = $_POST['username'];
    $password = $_POST['password'];

    if($user == '') {
        $errmsg_arr[] = 'You must enter your Username';
    }
    if($password == '') {
        $errmsg_arr[] = 'You must enter your Password';
    }

    // query
    if (!$errmsg_arr) {
        $result = $conn->prepare("SELECT * FROM login WHERE username= :user");
        $result->execute(['user' => $username]);
        $row = $result->fetch(PDO::FETCH_NUM);
        if($row && password_verify($_POST['password'], $row['password']) {
            $_SESSION['user'] = $row;
            header("location: ./pages/home.php");
            exit;
        }
        else{
            $errmsg_arr[] = 'Username and Password are not found';
        }
    }
}
?>

HTML FORM:

<?php foreach($errmsg_arr as $msg): ?>
    <?=htmlspecialchars($msg, ENT_QUOTES) ?>

<?php endforeach ?>
<form action="" method="post" name="login">
<input type="text" name="username" placeholder="Username" value="<?=htmlspecialchars($user, ENT_QUOTES)?>" />
<input type="password" name="password" placeholder="password"  value="<?=htmlspecialchars($password, ENT_QUOTES)?>"/>
<input type="submit" name="login_submit" value="login"/>
</form>

A: Suggestions:

*

*echo mysql_error() to determine why the error is occurring:
mysql_select_db("$db_name") or
    die("cannot select DB: " . mysql_error());

*Stop using deprecated functions " mysql_connect()", "mysql_query()"  and friends.  You'd be much better served with mysqli instead.

*Use Prepared Statements instead of building your "select" directly from your POST parameters.


text:
Q: css fixed positioned div disapears when i scroll down at certain point or when i refresh I have a jquery plugin so i don´t know what is the problem, i tried to make it all again but whe i get to the fixed part it happens all again, i really don´t know what to do i must deliver this work by tomorrow
//This is my css
@media only screen and (max-width:360px) {
#menu a:link {
color : #FFF;
}
#menu a:visited {
color : #FFF;
}
#menu a:hover {
color : red;
}
#menu {
position : relative;
left : 0;
padding : 0;
margin : 0;
}
#logo {
width : 100%;
}
#menu ul {
position : relative;
left : 0;
height : auto;
top : 0;
margin : 0;
padding : 0;
width : 100%;
margin : 0;
}
}

#menu{
font-family : 'Roboto Condensed', sans-serif;
font-size : 15px;
position : relative;
left: 0;
top: 0;
border: rgba(73, 73, 73, 0.3) solid 1px;
width: 100%;
background-image: url(grain.png);
background-color: rgba(0, 0, 0, 0.53);
padding: 0;
margin: 0;
text-align: center;
display: inline-block;

}
#menu ul {
list-style : none;
}
#menu li {
position : relative;
top : 69px;
line-height : 18px;
float : left;
}

@media only screen and (min-width:641px) {
#menu ul {
display : inline-block;
text-align : center;
height : 104px;
width: 980px;
margin : 0;
padding : 0;
}
#menu ul li a {
padding : 2px 0;
margin : 8px;
}
#menu ul li a:link {
-webkit-transition-duration: 0.2s;
-moz-transition-duration: 0.2s;
transition-duration: 0.2s;
background : transparent;
width : 100%;
color : rgb(255, 255, 255);
text-decoration : none;
transition-duration : 0.2s;
}
#menu ul li a:visited {
width : 100%;
height : 104px;
color : rgb(255, 255, 255);
text-decoration : none;
background : transparent;
}
#menu ul li a:active {
width : 100%;
color : rgb(255, 255, 255);
text-decoration : none;
}
#menu ul li a:hover {
background : transparent;
border-bottom : 3px solid #fff;
color : #f4f4f4;
text-decoration : none;
}
}

@media only screen and (max-width:641px) {
#menu ul {
height : auto;
width : 100%;
}
#registro {
display : none;
}
}

#barra_arriba {
z-index : 30;
position : fixed;
left : 0;
top:0;
border : rgba(73, 73, 73, 0.3) solid 1px;
width : 100%;
background-image : url(grain.png);
background-color : rgba(0, 0, 0, 0.53);
padding : 0;
margin : 0;
text-align : center;
display : inline-block;
-webkit-transition-duration: 0.4s;
-moz-transition-duration: 0.4s;
transition-duration: 0.4s;
}

#barra_arriba img {
width: 238px;
float: left;
}

//AND THIS IS MY HTML

IMICH

INSCRIPCIONES

LICENCIATURA

MAESTRÍAS

DOCTORADO

DIPLOMADOS

CONTACTO

A: I was having the same issue with Chrome, it seems to be a bug that occurs when there is too much going on inside the page, I was able to fix it by adding the following transform code to the fixed position element, (transform: translateZ(0);-webkit-transform: translateZ(0);) that forces the browser to use hardware acceleration to access the device's graphical processing unit (GPU) to make pixels fly. Web applications, on the other hand, run in the context of the browser, which lets the software do most (if not all) of the rendering, resulting in less horsepower for transitions. But the Web has been catching up, and most browser vendors now provide graphical hardware acceleration by means of particular CSS rules.
Using -webkit-transform: translate3d(0,0,0); will kick the GPU into action for the CSS transitions, making them smoother (higher FPS).
Note: translate3d(0,0,0) does nothing in terms of what you see. it moves the object by 0px in x,y and z axis. It's only a technique to force the hardware acceleration.
#barra_arriba {
    position: fixed;
    z-index...
    /* MAGIC HAPPENS HERE */
    transform: translateZ(0);
    -webkit-transform: translateZ(0);
}


text:
Q: Debug Asynchronous plugin How can I debug an asynchronous plugin( or custom workflow ) registered in CRM Dynamics online. As following post indicate it is working for synchrounous plugin I am just wondering is it possible for Asynchrounous plugins as well.
Debuggin plugin in CRm 2013 online

A: Recheck following video that shows how to debug any kind of plugin - either sync or async - http://blogs.msdn.com/b/devkeydet/archive/2015/02/17/debug-crm-online-plugins.aspx