text:
Q: How to create an interface with an unknown amount of string properties and one specific property with number type? I have an object that contains an unknown amount of error messages and exactly one property with a type number. How to create an interface for this object?
  interface IFormErrors {
    [key: string]: string; // So here is an unknown amount of strings
  }

  const initialFormErrors: IFormErrors = {
    nameErr: "",
    emailErr: "",
    linkErr: "",
    errorCounter: 0,
  };

A: The way to achieve exactly what you are looking for is to use an intersection type:
  type IFormErrors = { errorCounter: number } & {
    [key: string]: string; // So here is an unknown amount of strings
  }

  const initialFormErrors: IFormErrors = {
    nameErr: "",
    emailErr: "",
    linkErr: "",
    errorCounter: 0,
  };

This is a bit of a workaround as Typescript doesn't let you have properties of other types once you define an index signature. The recommended way to do this would be to use a nested index signature to avoid the problem:
interface IFormErrors {
  errorCounter: number;
  // you can name this property whatever you like, `errors` was just
  // what I came up with
  errors: {
    [key: string]: string; // So here is an unknown amount of strings
  }
}

I recommend reading this section of the Typescript Deep Dive gitbook to learn more about how to work efficiently with index signatures: https://basarat.gitbook.io/typescript/type-system/index-signatures#declaring-an-index-signature

A: It is doable, but there are some limitations:
interface IFormErrors {
    [key: string]: string; // So here is an unknown amount of strings
}

type Result = IFormErrors & {
    errorCounter: number;
}

const merge = <T, U>(a: T, b: U) => ({ ...a, ...b })
const build = (obj: IFormErrors, errorCounter: number) => merge(obj, { errorCounter })

const result = build({ a: '2' }, 5)

const anyProperty = result.sdf // string
const numberProperty = result.errorCounter // number

/**
 * But you are unable to create literal type
 */
const y: Result = { // error
    a: '23',
    errorCounter: 42
}

result variable has Result type - which is exactly what you want


text:
Q: Can knit2pdf use the global environment? In this answer, @Yihui said that knitr uses the global environment. This confused me--my experience had been that it doesn't. I never really use knit though, I usually go straight to PDF.
In a little experiment, it seems that knit does use the global environment (or whatever environment you specify using the envir argument), but that knit2pdf doesn't.
Minimal example: global_test.Rnw file
\documentclass{article}
\begin{document}
<<>>=
    print(x)
@
\end{document}

R Script:
x <- "Hello World"
knit(input="global_test.Rnw")
# Works as expected, could now call tools::texi2pdf to generate pdf.

knit2pdf(input="global_test.Rnw")
# Doesn't

The latter generates PDF file that won't display and gives a warning:
running command '"C:\PROGRA~2\MIKTEX~1.9\miktex\bin\texi2dvi.exe" --quiet --pdf
"global.pdf"  -I "C:/PROGRA~1/R/R-215~1.3/share/texmf/tex/latex" -I
"C:/PROGRA~1/R/R-215~1.3/share/texmf/bibtex/bst"' had status 1

I tried passing an environment to knit2pdf (envir = globalenv()) hoping it would be ... passed on, I just get an unused argument error.
Generally, I know that referencing the global environment is poor form, but is there a way to do it with knit2pdf, or to pass an environment explicitly, or am I better off using brew and sprintf as in @Ramnath's answer to the same question above?
In my use case, I don't think tools::texi2pdf is useful because I need to compile with XeLaTeX, which knit2pdf handles effortlessly.

A: The problems with the examples in the question seem to have nothing to do with environments. Everything will compile correctly and without warnings if the output argument is left off of knit2pdf.
For reference, I was using knitr 1.1 on R 2.15.3 on Windows 7. I'll let Yihui know as it appears to be a bug in knit2pdf (which calls tools::texi2pdf, which doesn't accept an output file path).
UPDATE: The problem has been fixed in the development version of knitr, available here.
It's also worth noting that the Compile PDF button in RStudio does not use your current environment, so if you want to have access to global variables and you are using RStudio, make an explicit call to the appropriate knit function rather than relying on the shortcut. In fact, it doesn't use knit2pdf directly, rather it calls rmarkdown::render.

redpajama_set_name: RedPajamaStackExchange


text:
Q: WCF - ignore byte array serialization I am trying to improve my service performance, I saw that I have CPU peak when my serivce sends the same data to many clients.I thought to ignore the serialization by passing byte array but I saw that wcf serial it to Base64, is there a way to ignore the serialization?

A: There are many ways to improve your service performance, like Caching and Throttling. First of all make sure what your bottleneck is. It could even be memory taken by server on a pick, anything. Run some load tests to figure it out.
If you want to send you data as binary have you considered to use TCP binding? It can speed up your service a bit as well.
Also make sure that none of the service instance are blocking each other. Consider using re-entry concurrency instanciating of a service.
But since you said "same data" I'm pretty sure what you are looking for is output caching.


text:
Q: How to run a Iphone backup with idevicebackup2? I try to do a backup of my Iphone SE iOS12.1.4. My Ubuntu version is Ubuntu 18.04.2 LTS.
I want to use the idevicebackup tool but I think I do something wrong because nothing happens.....
this is the command I try to use:
:~$ idevicebackup2 -u-d backup --full ~/backupiphone

but the only reaction what happens is that I get the -help information.
What I am doing wrong?
Terminal Picture
I also tried the code from this man page but it has no different effect.
Thank you for your help and please be gentle, I am a new woman in the ubuntu tech world...
UPDATE
-I hava a Iphone SE Model A1723 with iOS12.1.4.
-Yes I can exchange pictures.
-I connected my Iphone with Ubuntu and used this comand:
sudo fdisk -l && lsusb && dmesg && usb-devices lsblk && sudo blkid

And get a hell of a lot information.... I think this are the three parts they are interesting...
Bus 001 Device 005: ID 05ac:12a8 Apple, Inc. iPhone5/5C/5S/6

and
[  514.793618] ipheth 1-1.2:4.2: Apple iPhone USB Ethernet device attached

and

T:  Bus=01 Lev=02 Prnt=02 Port=01 Cnt=02 Dev#=  5 Spd=480 MxCh= 0
  D:  Ver= 2.00 Cls=00(>ifc ) Sub=00 Prot=00 MxPS=64 #Cfgs=  4
  P:  Vendor=05ac ProdID=12a8 Rev=08.04
  S:  Manufacturer=Apple Inc.
  S:  Product=iPhone
  S:  SerialNumber=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
  C:  #Ifs= 3 Cfg#= 4 Atr=c0 MxPwr=500mA
  I:  If#= 0 Alt= 0 #EPs= 3 Cls=06(still) Sub=01 Prot=01 Driver=usbfs
  I:  If#= 1 Alt= 0 #EPs= 2 Cls=ff(vend.) Sub=fe Prot=02 Driver=usbfs
  I:  If#= 2 Alt= 1 #EPs= 2 Cls=ff(vend.) Sub=fd Prot=01 Driver=ipheth

A: The syntax in your command is a little bit wrong.
Your command is: :~$ idevicebackup2 -u-d backup --full ~/backupiphone
You are missing a space in your command between -u and -d.
So the right command would be:
:~$ idevicebackup2 -u -d backup --full ~/backupiphone

Then you get the expected output.
For more information about the idevicebackup2 command see here.


text:
Q: Cannot modify a primary key in MySQL So I want to change kd_absen's length from 10 to 20 in the table called "absen". It's a primary key though.
And what happened next, phpmyadmin gave me this error massage
https://s.kaskus.id/r320x320/images/2017/07/08/9793710_20170708101310.JPG
What I tried so far: I tried to temporarily deleting the kd_absen in "penggajian" table (and re create it later). But a similar message appeared.
Any help will be appreciated, thanks in advance.

A: 1 - Remove the constraint of the primary key
2 - Alter the primary key field length
3 - Create another constraint to the primary key


text:
Q: Subselect, joins and O/R mapping i am following struts 2 and hibernate 5.
I have two tables A and B with different primary keys A_ID and B_ID.
They have common columns like model, name.
In my hbm file, I didnt refer to any of the above tables instead I have a subselect query which joins the two tables.
The mappings in the hbm file is
<id name="a_id" column="A_ID" />

<property name="b_model" column="B_model"/>

When i ran the hibernate query generated. I got the following output in MySql
A_Id    B_model other columns
111     3131
222     2121
222     4141
333     5151

But the list returned when the query is executed is
list(0) = 111 and 3131
list(1) = 222 and 2121
list(2) = 222 and **2121**
list(3) = 333 and 5151.

My question is why didnt list(2) didnt have 4141 instead of 2121.
And please let me know what i should to get the same (i.e) i need 4141 in list(2).
Thanks in advance.

A: As i guessed the tuples are returned as objects. Hence for A-Id 222 the B_mod is set as 2121. I used row_num() function to get distinct row nums for each row and used it as a primary key column to get all the rows. This may not be an exact solution but still it worked :-)


text:
Q: RepositoryException: Unable to auto-create value I'm new to Jackrabbit Oak, I'm trying to create nodes for storing files (pdf, word, excel, etc). When I try to create the node by specifying a type similar to this exceptions they are thrown.

javax.jcr.RepositoryException: Unable to auto-create value for / e0a02fd0-d328-48f7-8874-685c591afe9a / jcr: createdBy.

Example code:


text:
Q: how to compare listbox values and table values in javascript? In my scenario just select the list box options, that values and text going to append to the table rows, but im facing small issues, user not allow to select same options (already selected options) and user not allow to append same values in the table.. if user select same option show alert messages like, 'you are already selected, select another option' like that..
here is my sample code fiddle..
Fiddle
Sample snippet here..

$("#excist_supp").on("change", function() {
  $(".indexDrop").hide();

  var newText = $("#excist_supp option:selected").text();
  var newValue = $("#excist_supp option:selected").val();

  $("#letterTable tbody").append('
<input type="text" id="sm_supp" value="' + newText + '" class="form-control newStyle1" name="sm_supp" readonly>	<input type="text" id="sm_code" value="' + newValue + '" class="form-control newStyle2" name="sm_code" readonly>	<button type="button" class="adRow ibtnDel newExcist" style="width:30%;position: relative;right: 25%; margin-bottom:0px">x</button>
');

  $("#letterTable tr").each(function(i) {

    var count = (i) - 1;
    if (i === 0) return;
    var input1 = $(this).find('.newStyle1');
    var input2 = $(this).find('.newStyle2');

    // id
    input1.eq(0).attr("id", "sm_supp" + count); // Text fields
    input2.eq(0).attr("id", "sm_code" + count);

    // name
    input1.eq(0).attr("name", "sm_supp[" + count + "]"); // Text fields
    input2.eq(0).attr("name", "sm_code[" + count + "]");
  });

});

/* compare two fields */

$('#excist_supp').change(function() {
  $("#letterTable tr").each(function(i) {

    var listVal = $('#excist_supp').val();
    var tableVal = $('.newStyle2').val();
    var nawTab = JSON.stringify(tableVal);

    if (listVal == nawTab) {
      alert('Matching!');
      return true;
    } else {
      alert('Not matching!');
      return false;
    }
  });
});
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">

          <input class="form-control serch" id="supSearch" type="search" placeholder="Search Existing Suppliers..">

            <select class="col-12 listbox newBox" name="List_0" size="20" id="excist_supp" style="height: 125px !important;">
              <option class="indexDrop">Choose Existing Suppliers</option>
              <option value="0000">Komal </option>
              <option value="0001">Ranjeet</option>
              <option value="0002">Vishal </option>
              <option value="0003">Gaurav</option>
              <option value="0004">Dhanpat</option>
              <option value="0005">Joe</option>
              <option value="0006">Gowri</option>
              <option value="0007">shankar</option>
              <option value="0008">Dhanpat</option>
            </select>

                  Supplier Name
                  Supplier Code
                  Action

A: With $("#excist_supp").on("change".... and $('#excist_supp').change(function()... you are attaching the same event to the same element twice.
You can create a temporary array of all the used list values and create a function to check if the current value is exist in that array or not using Array.prototype.includes().
Try the following way:

$("#excist_supp").on("change", function() {

  if(!checkValue()){
    $(".indexDrop").hide();
    var newText = $("#excist_supp option:selected").text();
    var newValue = $("#excist_supp option:selected").val();

    $("#letterTable tbody").append('
<input type="text" id="sm_supp" value="' + newText + '" class="form-control newStyle1" name="sm_supp" readonly>	<input type="text" id="sm_code" value="' + newValue + '" class="form-control newStyle2" name="sm_code" readonly>	<button type="button" class="adRow ibtnDel newExcist" style="width:30%;position: relative;right: 25%; margin-bottom:0px">x</button>
');

    $("#letterTable tr").each(function(i) {

      var count = (i) - 1;
      if (i === 0) return;
      var input1 = $(this).find('.newStyle1');
      var input2 = $(this).find('.newStyle2');

      // id
      input1.eq(0).attr("id", "sm_supp" + count); // Text fields
      input2.eq(0).attr("id", "sm_code" + count);

      // name
      input1.eq(0).attr("name", "sm_supp[" + count + "]"); // Text fields
      input2.eq(0).attr("name", "sm_code[" + count + "]");
    });
  }

});

/* compare two fields */
var temp = [];
function checkValue() {
  var listVal = $('#excist_supp').val();
  var tableVal = $('.newStyle2').val();
  var nawTab = JSON.stringify(tableVal);
  if (temp.includes(listVal)) {
    alert('Matching!');
    return true;
  } else {
    alert('Not matching!');
    temp.push(listVal)
    return false;
  }
}

<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">

          <input class="form-control serch" id="supSearch" type="search" placeholder="Search Existing Suppliers..">

            <select class="col-12 listbox newBox" name="List_0" size="20" id="excist_supp" style="height: 125px !important;">
              <option class="indexDrop">Choose Existing Suppliers</option>
              <option value="0000">Komal </option>
              <option value="0001">Ranjeet</option>
              <option value="0002">Vishal </option>
              <option value="0003">Gaurav</option>
              <option value="0004">Dhanpat</option>
              <option value="0005">Joe</option>
              <option value="0006">Gowri</option>
              <option value="0007">shankar</option>
              <option value="0008">Dhanpat</option>
            </select>

                  Supplier Name
                  Supplier Code
                  Action


text:
Q: What is causing this error: "Failed to retrieve package sources for XML" What is causing this error: "Failed to retrieve package sources for XML"? I'm trying to publish an example dashboard to R Connect.
[Connect] 2020/12/10 16:40:00.827991448 Error in getSourceForPkgRecord(pkgRecord, srcDir(project), availablePackagesSource(repos = repos), : Failed to retrieve package sources for XML 3.99-0.5 from CRAN (internet connectivity issue?) [3.99-0.3 is current]

[Connect] Build error: A required R package was found in the package repository, but the specified version is not available. (r-package-version-not-available)
Application deployment failed with error: A required R package was found in the package repository, but the specified version is not available. (r-package-version-not-available)

I tried removing and then reinstalling XLM and recently updated my R to version 4.0.3. Wondering if that means I need to deprecate down to 3.99 for XML?
Repo info
> options('repos')
$repos
                       CRAN
"https://cran.rstudio.com/"
attr(,"RStudio")
[1] TRUE

Session info
> sessionInfo()
R version 4.0.3 (2020-10-10)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows >= 8 x64 (build 9200)

Matrix products: default

Random number generation:
 RNG:     Mersenne-Twister
 Normal:  Inversion
 Sample:  Rounding

locale:
[1] LC_COLLATE=English_United States.1252  LC_CTYPE=English_United States.1252
[3] LC_MONETARY=English_United States.1252 LC_NUMERIC=C
[5] LC_TIME=English_United States.1252

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base

other attached packages:
[1] shinydashboard_0.7.1       PerformanceAnalytics_2.0.4 xts_0.12.1
[4] zoo_1.8-8                  highcharter_0.8.2          ggplot2_3.3.2
[7] dygraphs_1.1.1.6           dplyr_1.0.2                shiny_1.5.0

loaded via a namespace (and not attached):
 [1] tidyselect_1.1.0  purrr_0.3.4       lattice_0.20-41   colorspace_2.0-0  vctrs_0.3.5
 [6] generics_0.1.0    htmltools_0.5.0   yaml_2.2.1        rlang_0.4.9       later_1.1.0.1
[11] pillar_1.4.7      glue_1.4.2        withr_2.3.0       TTR_0.24.2        lifecycle_0.2.0
[16] quantmod_0.4.18   stringr_1.4.0     munsell_0.5.0     gtable_0.3.0      htmlwidgets_1.5.2
[21] labeling_0.4.2    fastmap_1.0.1     Cairo_1.5-12.2    httpuv_1.5.4      curl_4.3
[26] broom_0.7.2       Rcpp_1.0.5        xtable_1.8-4      openssl_1.4.3     promises_1.1.1
[31] scales_1.1.1      backports_1.2.0   jsonlite_1.7.1    farver_2.0.3      mime_0.9
[36] askpass_1.1       digest_0.6.27     stringi_1.5.3     rlist_0.4.6.1     grid_4.0.3
[41] quadprog_1.5-8    tools_4.0.3       magrittr_2.0.1    tibble_3.0.4      crayon_1.3.4
[46] tidyr_1.1.2       pkgconfig_2.0.3   ellipsis_0.3.1    rsconnect_0.8.16  data.table_1.13.4
[51] lubridate_1.7.9.2 assertthat_0.2.1  rstudioapi_0.13   R6_2.5.0          igraph_1.2.6
[56] compiler_4.0.3


text:
Q: Exchange Hybrid message size restriction I'm migrating mailbox to Office 365 and got stuck with Large Items Exception.
I read about default message size restrictions. And set 100MB limit in Exchange Online.
Then migration failed again. I checked large item. It is around 40MB. So just above previous size restriction.
Since then I've tried to find any place where 35MB old limit is applied. Either on-premise or in cloud. And the only place I found is Mailuser in cloud. It's Mailuser because mailbox is still on-premise
The command run in Exchange Online.

I've confirmed that. After migration large item was skipped. And cloud mailbox MaxSendSize and MaxReceiveSize were 35 and 36 respectfully. Where they should have been 100MB as default message size restriction.
Could you please help? Maybe you know where this numbers are coming from. Or some policy for migration message size. I'd appreciate any thoughts.
Update 12.02.20. It seems to work after disabling data-loss prevention policy. We had Office 365 Security and Compliance DLP scanning Exchange mail. After deleting this, migration works, and message size restriction is back to default setting of 100MB for newly migrated mailbox. Maybe DLP freezes this restriction, I don't know.

A: Office 365 Exchange Online message size onboarding limit increase — We are making a change to allow customers to migrate larger mail messages to Exchange Online. We now allow messages up to 150MB to be migrated to the service. We are not changing other limits such as mailbox size or maximum send/receive limit for messages.
So you need to change the maximum send/receive limit manually.


text:
Q: How to bind Listview to Observablecollection in a static class of another namespace I reed a lot about namespace but still facing a problem / misunderstanding.
I would like to bind a Listview to an Observablecollection which resides in a static class in another namespace. It works but I can't succeed without code. I'm sure there is a better way to do this entirely in the XAML file.
So, this is my XAML file (...a part of - I delete a lot to be clear ...) :
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:local="clr-namespace:ToolBox"
             x:Class="ToolBox.MainPage">

    <StackLayout>

        <ListView x:Name="listToolBox">
            <ListView.ItemTemplate>
                <DataTemplate>
                    <TextCell   Text="{Binding  Name}"
                                Detail="{Binding CreateDate}"/>
                </DataTemplate>
            </ListView.ItemTemplate>
        </ListView>

    </StackLayout>

I set up the binding context of the "listToolBox" in the code behind:
...
using ToolBox.Model;

namespace ToolBox
{
    public partial class MainPage : ContentPage
    {
        public MainPage()
        {
            InitializeComponent();
            listToolBox.ItemsSource = ToolBox.Model.EBis.ToolBoxList;
        }
        ...

It refers to a member of a static class:
namespace ToolBox.Model
{

    public static class EBis
    {
        public static ObservableCollection<cDocuments> ToolBoxList = new ObservableCollection<cDocuments>
        {
            new cDocuments{ Id = -1, Name = "Pas (encore) de connection aux serveurs ..."}
        };
    ...

MY QUESTION:
What are the binding instructions I have to write in the XAML elements in order to delete this line of code behind
listToolBox.ItemsSource = ToolBox.Model.EBis.ToolBoxList;

To be complete, the structure of my "Toolbox" APP is here:

Thanks a lot for your advice

A: Use the x:Static markup extension:
<ListView ItemsSource="{x:Static local:Model.EBis.ToolBoxList}">


text:
Q: Single word for "thin slice" I thought of slither, but I ruled it out as it has negative connotations that I wish to avoid in the context.
I would use the word in a phrase like "a thin slice of bread" or "thinly sliced carrots."

A: A shave is another possibility.
Century Dictionary: A shaving; a thin paring.
American Heritage Dictionary: A thin slice or scraping; a shaving.

A: Wafer, perhaps? If you can get past the image of the final scene of Meaning of Life, that is.

A: Well, "sliver" immediately sprang to mind. Don't know the connotations are that negative?


text:
Q: Adding contacts and leads to a DE and receive a Violation of PRIMARY KEY constraint error message when running query I'm attempting to add leads and contacts into a DE from a synced data extension that receives  contacts and leads when a quiz is completed. The quiz can be taken multiple times which is why there is a violation of the primary key. I'm a SQL newbie and am having difficulty finding a solution. Here's the SQL:
SELECT CON.Id AS Id, QU.Email_Address__c AS Email_Address, QU.Quiz_Name__c AS Quiz
FROM Quiz__c_Salesforce QU
INNER JOIN Contact_Salesforce CON
ON QU.Email_Address__c = CON.Email
WHERE Quiz_Name__c = 'Intro to IT: Cybersecurity'
UNION
SELECT LEAD.Id AS Id, QU.Email_Address__c AS Email_Address, QU.Quiz_Name__c AS Quiz
FROM Quiz__c_Salesforce QU
INNER JOIN Lead_Salesforce LEAD
ON QU.Email_Address__c = LEAD.Email
WHERE Quiz_Name__c = 'Intro to IT: Cybersecurity'

A: I would suggest to add a timestamp field so you have some sort of control over which record you pick per person (say, the most recent).
Then you can work with SQL to achieve a deduplication using ROW_NUMBER to assign a rownumber, and partition by / order by to get the desired record.
Here is an example with "get the newest order", which similar to your usecase, e.g. get one (e.g. newest) quiz answer record:
SELECT o.SubscriberKey, o.Product, o.orderTimestamp
FROM (
  SELECT SubscriberKey, Product, orderTimestamp, ROW_NUMBER() OVER(Partition by SubscriberKey ORDER BY orderTimestamp DESC) AS Row_Number
  FROM Orders) o
WHERE b.Row_Number = 1


text:
Q: Public variable is undefined I have the following code:
setGlobalReceiverData(id) {

    switch (id) {
      case 'role':
        for (let i = 0; i < this.roleData.length; i++) {
          if (this.roleData[i]['Id'] == this.role) {
            this.DataService.receiverRoleValue = this.roleData[i]['role'];
          }
        }
        break;
      case 'salutation':
        for (let i = 0; i < this.salutationData.length; i++) {
          if (this.salutationData[i]['Id'] == this.salutation) {
            this.DataService.receiverSalutationValue = this.salutationData[i]['salutation'];
          }
        }
        break;
        case 'firstname':
          this.DataService.receiverFirstnameValue = this.firstname;
          break;
        case 'street':
          this.DataService.receiverStreetValue = this.street;
          break;
        case 'zip':
          this.DataService.receiverZipValue = this.zip;
          break;
        case 'location':
          this.DataService.receiverLocationValue = this.location;
          break;
        case 'title':
          for (let i = 0; i < this.titleData.length; i++) {
            if (this.titleData[i]['Id'] == this.title) {
              this.DataService.receiverTitleValue = this.titleData[i]['title'];
            }
          }
          break;
        case 'lastname':
          this.DataService.receiverLastnameValue = this.lastname;
          break;
        case 'inbox':
          this.DataService.receiverInboxValue = this.inbox;
          break;
        case 'co':
          this.DataService.receiverCoValue = this.additional_location;
          break;
    }
  }

First of all, does the Case 'Salutation' make sense in the first place?
My main problem is however that the variable this.DataService.receiverSalutationValue is undefined, even though FirstName and LastName is defined and working properly
I have another function:
public getGlobalReceiverData(): void
  {
    console.log('Salutation:', this.DataService.receiverSalutationValue);
    console.log('FirstName:', this.DataService.receiverFirstnameValue);
    console.log('Lastname', this.DataService.receiverLastnameValue);

    this.salutation = this.DataService.receiverSalutationValue;
    this.firstname = this.DataService.receiverFirstnameValue;
    this.lastname = this.DataService.receiverLastnameValue;
    this.street = this.DataService.receiverStreetValue;
    this.zip = this.DataService.receiverZipValue;
    this.location = this.DataService.receiverLocationValue;
    this.additional_location = this.DataService.receiverCoValue;
    this.inbox = this.DataService.receiverInboxValue;
  }

As you can see receiver salutation is included here. However, when I start the app the salutation variable gets console logged as undefined... In my globaldata Service the global/public variables are set as they're supposed to:
 public receiverRoleValue;
  public receiverSalutationValue;
  public receiverFirstnameValue: string;
  public receiverLastnameValue: string;
  public receiverStreetValue: string;
  public receiverInboxValue: string;
  public receiverZipValue: string;
  public receiverLocationValue: string;
  public receiverCoValue: string;
  public receiverTitleValue;

I also have a prefill function:
public prefillSenderData() {
    return this.http.get(this.get_sender_url)
    .subscribe(
      senderResponse => {
        this.senderSalutationValue = senderResponse[0]['Salutation'];
        this.senderFirstnameValue = senderResponse[0]['FirstName'];
        this.senderLastnameValue = senderResponse[0]['LastName'];
        this.senderPhonenumberValue = senderResponse[0]['PhoneNumber'];
        this.senderPhoneValue = senderResponse[0]['Phone'];
        this.senderNameValue = senderResponse[0]['Name'];
        this.senderAddressValue = senderResponse[0]['Address'];
        this.senderLocationValue = senderResponse[0]['Location'];
        this.senderNameLeftValue = senderResponse[0]['NameLeft'];
        this.senderNameRightValue = senderResponse[0]['NameRight'];
        this.senderFaksimilieLeftValue = senderResponse[0]['FaksimileLeft'];
        this.senderFaksimilieRightValue = senderResponse[0]['FaksimileRight'];

        console.log("Sender-Object: ", senderResponse);

        this.bool_senderSharedDataLoaded = true;
       },
  error => console.log('There was an error: ', error));
  }

The salutation data array gets created and its data is mapped:
// data
    public salutationData: { [salutation: string]: Object }[] = [ {salutation: "Mr.", Id: 1 }, {salutation: "Mrs.", Id: 2 } ];
    public roleData: { [role: string]: Object }[] = [ {role: "Contract customer", Id: 1 }, {role: "Insurance user", Id: 2 } ];
    public titleData: { [title: string]: Object }[] = [ {title: "Dr.", Id: 1 }, {title: "Prof.", Id: 2 } ];

    // mapping
    public salutation: Object = { text: 'salutation', value: 'Id' };
    public role: Object = { text: 'role', value: 'Id' };
    public title: Object = { text: 'title', value: 'Id' };


text:
Q: How can I erase my objects in the drawing application without changing the Background Image? I want to erase my bitmap but I don't want to erase background image. When I try to erase is white and it draw very hard in frames.
this is my MainActivity code
    private final String tag = "MainActivity";

    private ImageView eraser;
    private Button btnChooseImage;
    private ImageButton btnClear, btnSave, btnShare, btnCamera;

    private DrawingView drawingView;

    private static final int SELECT_PHOTO = 100;
    private static final int CAMERA_REQUEST = 1888;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        if (savedInstanceState == null) {

            setContentView(R.layout.activity_main);

            drawingView = (DrawingView) findViewById(R.id.drawing);

            btnChooseImage = (Button) findViewById(R.id.btnChooseImage);
            btnChooseImage.setOnClickListener(this);

            btnClear = (ImageButton) findViewById(R.id.btnClear);
            btnClear.setOnClickListener(this);

            btnSave = (ImageButton) findViewById(R.id.btnSave);
            btnSave.setOnClickListener(this);

            btnShare = (ImageButton) findViewById(R.id.btnShare);
            btnShare.setOnClickListener(this);

            btnCamera = (ImageButton) findViewById(R.id.btnCamera);
            btnCamera.setOnClickListener(this);

            eraser = (ImageView) findViewById(R.id.eraser);
            eraser.setOnClickListener(this);
        }
    }

    @SuppressLint("NewApi") @Override
    public void onClick(View v) {

        if (v == eraser) {

            if (drawingView.isEraserActive()) {

                drawingView.deactivateEraser();

                eraser.setImageResource(R.drawable.eraser);

            } else {

                drawingView.activateEraser();

                eraser.setImageResource(R.drawable.pencil);
            }

        } else if (v == btnClear) {

            drawingView.reset();
            drawingView.setBackground(null);

        } else if (v == btnSave) {

            saveImage();

        } else if (v == btnCamera) {

            Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
            startActivityForResult(cameraIntent, CAMERA_REQUEST);

        } else if (v == btnShare) {

            Intent share = new Intent(Intent.ACTION_SEND);
            share.setType("image/png");

            share.putExtra(Intent.EXTRA_STREAM, Uri.parse(saveImage().getAbsolutePath())); //"file:///sdcard/temporary_file.jpg"
            startActivity(Intent.createChooser(share, "Share Image"));

        } else if (v == btnChooseImage) {

            Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
            photoPickerIntent.setType("image/*");
            startActivityForResult(photoPickerIntent, SELECT_PHOTO);

        }

    }

    public File saveImage() {
        drawingView.setDrawingCacheEnabled(true);
        Bitmap bm = drawingView.getDrawingCache();

        File fPath = Environment.getExternalStorageDirectory();

        File f = null;

        f = new File(fPath, UUID.randomUUID().toString() + ".png");

        try {
            FileOutputStream strm = new FileOutputStream(f);
            bm.compress(Bitmap.CompressFormat.PNG, 80, strm);
            strm.close();

            Toast.makeText(getApplicationContext(), "Image is saved successfully.", Toast.LENGTH_SHORT).show();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return f;
    }

    @SuppressLint("NewApi") @SuppressWarnings("deprecation")
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent imageReturnedIntent) {
        super.onActivityResult(requestCode, resultCode, imageReturnedIntent);

        switch (requestCode) {

            case SELECT_PHOTO:
                if (resultCode == RESULT_OK) {
                    Uri selectedImage = imageReturnedIntent.getData();
                    InputStream imageStream = null;
                    try {
                        imageStream = getContentResolver().openInputStream(selectedImage);
                        Bitmap bitmap = BitmapFactory.decodeStream(imageStream);

                        BitmapDrawable ob = new BitmapDrawable(getResources(), bitmap);

                        if(Build.VERSION.SDK_INT >= 16)
                        {
                            drawingView.setBackground(ob);
                        }else {
                            drawingView.setBackgroundDrawable(ob);
                        }

                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    }
                }
                break;
            case CAMERA_REQUEST:
                if (resultCode == RESULT_OK) {

                    Bitmap photo = (Bitmap) imageReturnedIntent.getExtras().get("data");

                    BitmapDrawable ob = new BitmapDrawable(getResources(), photo);

                    if(Build.VERSION.SDK_INT >= 16)
                    {
                        drawingView.setBackground(ob);
                    }else {
                        drawingView.setBackgroundDrawable(ob);
                    }
                }
        }
    }

}

and here is the DrawingView code
private Canvas m_Canvas;

    private Path m_Path;

    private Paint m_Paint;

    private ArrayList<Pair<Path, Paint>> paths = new ArrayList<Pair<Path, Paint>>();

    private ArrayList<Pair<Path, Paint>> undonePaths = new ArrayList<Pair<Path, Paint>>();

    private float mX, mY;

    private static final float TOUCH_TOLERANCE = 0.001f;

    private boolean isEraserActive = false;

    public DrawingView(Context context, AttributeSet attr) {
        super(context, attr);

        setFocusable(true);

        setFocusableInTouchMode(true);

        setBackgroundColor(Color.WHITE);

        this.setOnTouchListener(this);

        onCanvasInitialization();
    }

    public void onCanvasInitialization() {

        m_Paint = new Paint();
        m_Paint.setAntiAlias(true);
        m_Paint.setDither(true);
        m_Paint.setColor(Color.parseColor("#000000"));
        m_Paint.setStyle(Paint.Style.STROKE);
        m_Paint.setStrokeJoin(Paint.Join.ROUND);
        m_Paint.setStrokeCap(Paint.Cap.ROUND);
        m_Paint.setStrokeWidth(2);

        m_Canvas = new Canvas();

        m_Path = new Path();
        Paint newPaint = new Paint(m_Paint);
        paths.add(new Pair<Path, Paint>(m_Path, newPaint));

    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
    }

    public boolean onTouch(View arg0, MotionEvent event) {
        float x = event.getX();
        float y = event.getY();

        switch (event.getAction()) {
        case MotionEvent.ACTION_DOWN:
            touch_start(x, y);
            invalidate();
            break;
        case MotionEvent.ACTION_MOVE:
            touch_move(x, y);
            invalidate();
            break;
        case MotionEvent.ACTION_UP:
            touch_up();
            invalidate();
            break;
        }
        return true;
    }

    @Override
    protected void onDraw(Canvas canvas) {
        for (Pair<Path, Paint> p : paths) {
            canvas.drawPath(p.first, p.second);
        }
    }

    private void touch_start(float x, float y) {

        if (isEraserActive) {
            m_Paint.setColor(Color.WHITE);
            m_Paint.setStrokeWidth(10);
            Paint newPaint = new Paint(m_Paint); // Clones the mPaint object
            paths.add(new Pair<Path, Paint>(m_Path, newPaint));

        } else {
            m_Paint.setColor(Color.BLACK);
            m_Paint.setStrokeWidth(2);
            Paint newPaint = new Paint(m_Paint); // Clones the mPaint object
            paths.add(new Pair<Path, Paint>(m_Path, newPaint));

        }

        m_Path.reset();
        m_Path.moveTo(x, y);
        mX = x;
        mY = y;
    }

    private void touch_move(float x, float y) {
        float dx = Math.abs(x - mX);
        float dy = Math.abs(y - mY);
        if (dx >= TOUCH_TOLERANCE || dy >= TOUCH_TOLERANCE) {
            m_Path.quadTo(mX, mY, (x + mX) / 2, (y + mY) / 2);
            mX = x;
            mY = y;
        }
    }

    private void touch_up() {
        m_Path.lineTo(mX, mY);

        // commit the path to our offscreen
        m_Canvas.drawPath(m_Path, m_Paint);

        // kill this so we don't double draw
        m_Path = new Path();
        Paint newPaint = new Paint(m_Paint); // Clones the mPaint object
        paths.add(new Pair<Path, Paint>(m_Path, newPaint));
    }

    public void activateEraser()
    {
        isEraserActive = true;
    }

    public void deactivateEraser()
    {
        isEraserActive = false;
    }

    public boolean isEraserActive()
    {
        return isEraserActive;
    }

    public void reset()
    {
        paths.clear();

        invalidate();
}
}

I wanted to erase the drawing view without changing the background image which is imported from gallery

A: make one function in your View class and clear all list views you have saved before and redraw the view like:
public void clearDrawing()
{
  paths.clear();
  invalidate();
}

invalidate() whill refresh the view. Call this method from your view object on click event in activity. Hope it will help.


text:
Q: WebRequest timeout I have the following error:

((MS.Internal.InternalWebRequestStream)requestStream).ReadTimeout (and WriteTimeout) has thrown an exception of type System.InvalidOperationException

On MSDN it's said:

The WriteTimeout property should be overridden to provide the appropriate behavior for the stream. If the stream does not support timing out, this property should raise an InvalidOperationException.

So i would like to understand exactly what i should do in order to avoid this exception
Here is my code. On a click event i have:
DispatcherHelper.CheckBeginInvokeOnUI(() =>
{
    th = new Thread(StartSaveDataSource);
    th.Start();
});

Here is my function sending data in xml to php
private void StartSaveDataSource()
{
    Uri uri;
    String str = String.Empty;
    str = @"http://example.com/new/index.php?action=getmongopod";

    DispatcherHelper.CheckBeginInvokeOnUI(() =>
        {
            try
            {
                XmlSerializer serializer = new XmlSerializer(typeof(Model));
                using (StringWriter writer = new StringWriter())
                {
                    serializer.Serialize(writer, dataSource);
                }

                using (StringWriter stringWriter = new StringWriter())
                {
                    serializer.Serialize(stringWriter, dataSource);
                    xmlString = stringWriter.GetStringBuilder().ToString().Replace(@"encoding=""utf-16""", @"encoding=""utf-8""");
                }
                Uri strReq;
                bool isStrReqGained = false;
                if (Application.Current.IsRunningOutOfBrowser)
                {
                    strReq = new Uri(str, UriKind.Absolute);
                    isStrReqGained = true;
                }
                else
                {
                    Uri docUri = HtmlPage.Document.DocumentUri;
                    if (docUri == null || String.IsNullOrWhiteSpace(docUri.AbsolutePath))
                    {
                        strReq = null;
                    }
                    else
                    {
                        strReq = new Uri(docUri, SilverlightApplication2.Resources.Urls.GetMongoPod);
                        isStrReqGained = true;
                    }

                }

                if (isStrReqGained)
                {
                    WebRequest webRequest = WebRequest.Create(strReq);
                    webRequest.Method = "POST";
                    webRequest.ContentType = "application/x-www-form-urlencoded";
                    webRequest.BeginGetRequestStream(CreateCustomRequest, webRequest);
            }catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        });
}

Here is the asyncCallback Action
private void CreateCustomRequest(IAsyncResult asyncResult)
{
    try
    {
        WebRequest request = (WebRequest) asyncResult.AsyncState;
        Stream requesStream = null;
        try
        {
            requesStream = request.EndGetRequestStream(asyncResult);
            using (StreamWriter writer = new StreamWriter(requesStream))
            {
                requesStream = null;
                writer.Write("xmlstring=" + HttpUtility.UrlEncode(xmlString));
            }
        }
        catch(Exception ex)
        {
            DispatcherHelper.CheckBeginInvokeOnUI(() => MessageBox.Show(ex.ToString()));
        }
        finally
        {
            if (requesStream != null)
            {
                requesStream.Close();
            }
        }
        request.BeginGetResponse(ReadResponse, request);
    }
    catch (Exception ex)
    {
        DispatcherHelper.CheckBeginInvokeOnUI(() => MessageBox.Show(ex.Message));
    }
}


text:
Q: Is $f(x)$ is more curvature than $g(x)$ then length of $f(x)$ seem longer than length of $g(x)$? In my obsevation:
If $f(x)$ and $g(x)$ be two continuous funcions, and they have derivative and second derivative are also continuous in interval $[a, b]$. If $f(x)$ is more curvature than $g(x)$ in interval $[a, b]$ and $f(a)=g(a)$, $f(b)=g(b)$ then length of $f(x)$ from $a$ to $b$ seem longer than length of $g(x)$ from $a$ to $b$ ?
Example: Length of any curve (curve is not a line) is longer than a line in every interval.
This observation can fomulate that:
$$\frac{|f''(x)|}{(1+f'(x)^2)^{\frac{3}{2}}} \ge \frac{|g''(x)|}{(1+g'(x)^2)^{\frac{3}{2}}}$$ for all $x \in [a, b]$ and $f(a)=g(a)$, $f(b)=g(b)$
then $$\int_{a}^{b}{ \sqrt{1+f'(x)^2}}dx \ge \int_{a}^{b}{ \sqrt{1+g'(x)^2}}dx$$

My question: I think this is true and well-known, can you share me a reference. If this result is not known can you give a proof or a comment? Thank You very much.

A: The answer is no. Indeed, if this conjecture were true, then the conditions $f(a)=g(a)$, $f(b)=g(b)$, and
\begin{equation}
 k_f(x):=\frac{|f''(x)|}{(1+f'(x)^2)^{3/2}}=k_g(x)
\end{equation}
for all $x \in [a, b]$ would imply that
\begin{equation}
 \ell_f:=\int_a^b\sqrt{1+f'(x)^2}\,dx=\ell_g;
\end{equation}
that is, we would have that the length of the graph of a smooth enough function $f$ over $[a,b]$ would be determined by the curvature of the graph and the values of $f$ at $a,b$.
Let us show that this is not so. Indeed, let
\begin{equation}
 h(x):=\frac12 \sqrt{\frac{(1+4 x^2)^{3/2}-3 x-8 x^3}{x+3 x^3}}.
\end{equation}
Everywhere here $x>0$, unless otherwise specified.
It is not hard to see that the expression under the square root is $>0$, so that the definition of $h$ is correct.
Let now
\begin{equation}
 f(x):=\int_a^x h(u)\,du
\end{equation}
and
\begin{equation}
 g(x):=x^2-a^2,
\end{equation}
where $a:=1/100$.
Then
\begin{equation}
 \frac{f''(x)}{(1+f'(x)^2)^{3/2}}=\frac{-2}{(1+4x^2)^{3/2}}=-\frac{g''(x)}{(1+g'(x)^2)^{3/2}}.
\end{equation}
So, the function $f$ is concave, the function $g$ is convex, $f(a)=g(a)$, and
\begin{equation}
 k_f=k_g.
\end{equation}
Moreover, $f'(a)>g'(a)$. So, there is a unique real $b>a$ such that $f(b)=g(b)$; in fact, $b=0.710526\ldots\;$.
However,
\begin{equation}
 \ell_f=0.920463\ldots\ne0.894858\ldots=\ell_g,
\end{equation}
which does disprove the conjecture.
This counterexample is illustrated here:


text:
Q: How to round the corners of an image inside of a hdc? I'm capturing a window using the winapi PrintWindow, and cropping only the desired region using BitBlt, but the region I'm trying to capture is a rounded rect, how I could round the corners of the image inside of the hdc?
I know about the method Graphics::FromHDC(HDC) but I'm not sure how to "round" the image got from the graphics.
RECT rc;
HWND hwnd = FindWindow(TEXT("Test"), NULL);
if (hwnd == NULL)
{
    cout << "Can't find the given window" << endl;
    return 0;
}
GetClientRect(hwnd, &rc);

// Capture the window screen.
HDC hdcScreen = GetDC(NULL);
HDC hdcSrc = CreateCompatibleDC(hdcScreen);
HBITMAP hbmp = CreateCompatibleBitmap(hdcScreen,
    rc.right - rc.left, rc.bottom - rc.top);
SelectObject(hdcSrc , hbmp);

//Print to memory hdc
PrintWindow(hwnd, hdcSrc, PW_CLIENTONLY);

// Copy only the desired area.
HDC hdcScreen2 = GetDC(NULL);
HDC hdcDest = CreateCompatibleDC(hdcScreen2);
HBITMAP hbmp2 = CreateCompatibleBitmap(hdcScreen2,
    300, 200);
SelectObject(hdcDest, hbmp2);

BitBlt(hdcDest, X, Y, W, H, hdcSrc, 0, 0, SRCCOPY);

A: (I wrote this answer and thought the OP wanted Gdiplus for some reason ... regular GDI is pretty much the same thing although there actually is a CreatRoundRectRgn(...) in that case)
You can set the clipping region of a Gdiplus::Graphics object with its SetClip member function which takes a Region. You can create a Region from a Path but there is apparently no out-of-the-box way in Gdi+ of creating a round rectangle shaped path so you have to do it manually. There is an answer on StackOverflow about doing this in C#, and another one that ports it to C++/Win32 here.
Code below:
#include <windows.h>
#include <objidl.h>
#include <gdiplus.h>
namespace gdi = Gdiplus;
#pragma comment (lib,"Gdiplus.lib")

void GetRoundRectPath(gdi::GraphicsPath* pPath, gdi::Rect r, int dia)
{
    // diameter can't exceed width or height
    if (dia > r.Width)    dia = r.Width;
    if (dia > r.Height)    dia = r.Height;

    // define a corner
    gdi::Rect Corner(r.X, r.Y, dia, dia);

    // begin path
    pPath->Reset();

    // top left
    pPath->AddArc(Corner, 180, 90);

    // tweak needed for radius of 10 (dia of 20)
    if (dia == 20)
    {
        Corner.Width += 1;
        Corner.Height += 1;
        r.Width -= 1; r.Height -= 1;
    }

    // top right
    Corner.X += (r.Width - dia - 1);
    pPath->AddArc(Corner, 270, 90);

    // bottom right
    Corner.Y += (r.Height - dia - 1);
    pPath->AddArc(Corner, 0, 90);

    // bottom left
    Corner.X -= (r.Width - dia - 1);
    pPath->AddArc(Corner, 90, 90);

    // end path
    pPath->CloseFigure();
}

VOID OnPaint(HDC hdc, gdi::Image* img)
{
    gdi::Graphics g(hdc);
    gdi::GraphicsPath path;
    GetRoundRectPath(&path, { 10,10,512,512 }, 50);
    gdi::Region rgn(&path);
    g.SetClip(&rgn);
    g.DrawImage(img, 10, 10);
}

LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);

INT WINAPI WinMain(HINSTANCE hInstance, HINSTANCE, PSTR, INT iCmdShow)
{
    HWND                hWnd;
    MSG                 msg;
    WNDCLASS            wndClass;
    gdi::GdiplusStartupInput gdiplusStartupInput;
    ULONG_PTR           gdiplusToken;

    // Initialize GDI+.
    gdi::GdiplusStartup(&gdiplusToken, &gdiplusStartupInput, NULL);

    {
        // nest everything in a scope so that the image doesnt
        // get destroyed after Gdiplus has been shut down.

        wndClass.style = CS_HREDRAW | CS_VREDRAW;
        wndClass.lpfnWndProc = WndProc;
        wndClass.cbClsExtra = 0;
        wndClass.cbWndExtra = 0;
        wndClass.hInstance = hInstance;
        wndClass.hIcon = LoadIcon(NULL, IDI_APPLICATION);
        wndClass.hCursor = LoadCursor(NULL, IDC_ARROW);
        wndClass.hbrBackground = (HBRUSH)GetStockObject(WHITE_BRUSH);
        wndClass.lpszMenuName = NULL;
        wndClass.lpszClassName = TEXT("cliptorrect");

        RegisterClass(&wndClass);

        gdi::Image img(TEXT("C:\\test\\lenna.png"));

        hWnd = CreateWindow(
            TEXT("cliptorrect"),
            TEXT("clip to round rect"),
            WS_OVERLAPPEDWINDOW,
            CW_USEDEFAULT,
            CW_USEDEFAULT,
            548,
            572,
            NULL,
            NULL,
            hInstance,
            &img
        );

        ShowWindow(hWnd, iCmdShow);
        UpdateWindow(hWnd);

        while (GetMessage(&msg, NULL, 0, 0))
        {
            TranslateMessage(&msg);
            DispatchMessage(&msg);
        }
    }

    gdi::GdiplusShutdown(gdiplusToken);
    return msg.wParam;
}  // WinMain

LRESULT CALLBACK WndProc(HWND hWnd, UINT message,
    WPARAM wParam, LPARAM lParam)
{
    HDC          hdc;
    PAINTSTRUCT  ps;

    switch (message)
    {
    case WM_CREATE: {
        CREATESTRUCT* cs = reinterpret_cast<CREATESTRUCT*>(lParam);
        SetWindowLongPtr(hWnd, GWLP_USERDATA, reinterpret_cast<LONG>(cs->lpCreateParams));
    } return 0;

    case WM_PAINT:
        hdc = BeginPaint(hWnd, &ps);
        OnPaint(hdc, reinterpret_cast<gdi::Image*>(GetWindowLongPtr(hWnd, GWLP_USERDATA)));
        EndPaint(hWnd, &ps);
        return 0;
    case WM_DESTROY:
        PostQuitMessage(0);
        return 0;
    default:
        return DefWindowProc(hWnd, message, wParam, lParam);
    }
}

The output of the above looks like

I'm not sure if there is a way in GDi+ to get that anti-aliased or not, however.


text:
Q: Equation of parabola from 2 points and an angle at the first point A parabola starts at a coordinate A and ends at coordinate B. Angel of tangent through A is given 'theta'. With these data (A,B,theta) how can I get an equation of a parabola?

A: You have to construct a system of simultaneous equations. Let $A(x_1,y_1)$ and $B(x_2,y_2)$ the equation of parabola is polynomial of degree $2$ say $y=ax^2+bx+c$ so you can substitute at first $x=x_1 , y=y_1$ then $x=x_2 , y=y_2$ now you have tow equation the third equation will be find from $\tan \theta=y'=2ax+b$


text:
Q: probability of getting 5 calls in 5 minutes Phone calls arrive at the rate of 48 per hour at the reservation desk for Regional Airways.
1
a. Compute the probability of receiving three calls in a 5-minute interval of time.
b. Compute the probability of receiving exactly 10 calls in 15 minutes.

A: Hint: use Poisson distribution with $\lambda_1 = 4, \lambda_2 = 12$.


text:
Q: Logger not working inside AsyncCallback I have a problem with logging with GWT Unit testing:
logInfo("Creating Stuff: " + stuffAutoBeanSerializer.encodeData(stuff)); // Logging works and showing in the IntelliJ console

myService.createStuff(stuff, new AsyncCallback<Stuff>() {
            @Override
            public void onFailure(Throwable throwable) {
                logSevere(throwable.getMessage()); // Not showing in the console
            }
            @Override
            public void onSuccess(Stuff stuff) {
                logInfo("Created Stuff: " + stuffAutoBeanSerializer.encodeData(stuff)); // not showing in the console
            }
});

Even though the request is an onSuccess since data is stored in the database. What could be the problem here?

A: The rest of your test method is missing, but the problem is almost certainly that you didn't tell the test case that it was async, so when the method returned without an exception, the test infrastructure assumed that the test passed.
In an async GWTTestCase, you must use delayTestFinish(millis) to indicate that the test won't be done when it returns, and then finishTest() (probably in your onSuccess) to indicate that the test passed. If finishTest() is not called in time (or at all), the test will be assumed to have failed.


text:
Q: php combinatoric Здравствуйте, нужна помощь в php. Нашел такой код:
    <?php

function pc_permute($items, $perms = array( )) {
    if (empty($items)) {
        print join(' ', $perms) . "<br>";
    }  else {
        for ($i = count($items) - 1; $i >= 0; --$i) {
             $newitems = $items;
             $newperms = $perms;
             list($foo) = array_splice($newitems, $i, 1);
             array_unshift($newperms, $foo);
             pc_permute($newitems, $newperms);
         }
    }
}
print_r(pc_permute(array('1', '2', '3', '4', '5', '6', '7', '8', '9', '0')));

?>

помогите пожалуйста допилить чтобы, можно было выставить ограничение например в 3 знака(чтобы примерно так 123 / 567/ 739) и чтобы например  могло сохранить в файл.txt а то комп долго думает временами и памяти мало.
Заранее спасибо.

A: Сохранить можно вот так.
        $file = fopen("Путь_к_файлу.txt", w);
        fwrite($file, "Текст_который_нужно_записать");
        fclose($file);


text:
Q: ¿Es posible visualizar un " print 'Mensaje' " que existe dentro de un Store Procedure y mostrarlo en un metodo o alguna clase que lo capture en c#? create proc Proceso
as
begin

print 'Inicia Proceso'

--Realizo proceso 1, este proceso puede tardar algun tiempo determinado

print 'Proceso 1 Realizado'

--Realizo proceso 2,

print 'Proceso 2 Realizado'

SELECT * FROM Orden

--Muestra Data

print 'Fin del proceso'

end


text:
Q: How to speed up HKStatisticsCollectionQuery in iOS 9.3? It seems HKStatisticsCollectionQuery is incredibly slow in iOS 9.3. It can take upwards of 40 seconds to return hourly statistics for a year for active calories where it took 1 or less before.
let predicate = HKQuery.predicateForSamplesWithStartDate(anchorDate, endDate: endDate, options: [])
    let query = HKStatisticsCollectionQuery(quantityType: quantityType,
        quantitySamplePredicate: predicate,
        options: statisticOptions,
        anchorDate: anchorDate,
        intervalComponents: interval)

A: If someone has troubles with long HKStatisticsCollectionQuery request performing (dozens of seconds or minutes) please consider you have set proper dates for your predicate and anchor. The problem is a lot of data that HealthKit should calculate.
For example your goal is gathering data for today:
let predicate = HKQuery.predicateForSamples(withStart: startDate, end: endDate)
    let query = HKStatisticsCollectionQuery(quantityType: quantityType,
                                            quantitySamplePredicate: predicate,
                                            options: .cumulativeSum,
                                            anchorDate: anchorDate,
                                            intervalComponents: interval)

Here startDate is today's beginning, endDate is beginning for tomorrow, anchorDate is some day's beginning - in my case it's equal to endDate.
Important notice: if you pass nil instead of predicate, HealthKit will gather all data since the beginning and waste your time as a result.
Why tomorrow's beginning is necessary as endDate? The reason is statisticsUpdateHandler. Since you have decided to listen to data updates in HealthKit, predicate's end date should be in a future, not Date(). If you don't want to use statisticsUpdateHandler you can set endDate as now.

A: After many hours of trial and error I have found that HKStatisticsCollectionQuery is not thread friendly. In order to solve the problem I used this async NSOperation:
https://gist.github.com/calebd/93fa347397cec5f88233
And of course an NSOperationQueue in order to force the HKStatisticsCollectionQuerys to be performed synchronously. Once I did that each query took less than half a second.


text:
Q: Adding individual test cases to a suite in utPLSQL I have a test package containing 6 test cases. I want to build 2 suites:
1st containing test1, test2
2nd containing test3, test4, test 5
As per documentation we can add only entire test package to a suite, but not individual test cases. Also, I dont want to segregate packages based on suite requirement as they are for same group, but different functionality.
Any suggestions on this will be greatly appreciated. And, do feel free to let me know if my current understanding is wrong. Thanks in advance. Adding some sample code:
CREATE PACKAGE ut_test_pkg
IS BEGIN
PROCEDURE ut_test1;
   PROCEDURE ut_test2;
   PROCEDURE ut_test3;
   PROCEDURE ut_test4;
   PROCEDURE ut_test5;
END;
 /

Now test1 and test2 are logically 1 test case and test3-5 another. I can do like :
begin
utplsql.test ('test_pkg', recompile_in => FALSE, subprogram_in => 'test1');         utplsql.test ('test_pkg', recompile_in => FALSE, subprogram_in => 'test2');
end;
/

But adding it to suite adds to simplicity. And it can simply run that suite for clubbing test1,test2 and test3-5.
On running individually, I get output like::
Success
test 1 <50 more lines>
Failure
test 2 <50 more lines>
I have close to 100 checks so gap between test result is quite large, and user have to scroll a lot. I am looking to add a heading which says final result at the top, like in test suites they do, where out put is like
SUITE FAILURE
Success
test 1 <50 more lines>
Failure
test 2 <50 more lines>

A: Looks like I found a viable and pretty straight forward solution solution for my query. I simply need need to properly specify the subprogram section during test run.
So, first all test cases which I need to club must contain a common string which I can use to search::
CREATE PACKAGE ut_test_pkg
IS BEGIN
   PROCEDURE ut_abc_test1;
   PROCEDURE ut_abc_test2;
   PROCEDURE ut_def_test3;
   PROCEDURE ut_def_test4;
   PROCEDURE ut_def_test5;
END;
 /

While executing I do it like::
begin
  utplsql.test ('test_pkg', recompile_in => FALSE, subprogram_in => '%abc%');
end
/
begin
  utplsql.test ('test_pkg', recompile_in => FALSE, subprogram_in => '%def%');
end;
/

This will run test case containing abc in first case and consolidated result [Success/Failue] is shown at the top of the dbms_output. So, user will not have to scroll for checking test case of each and every test. Similarly, for def in 2nd run.
Thanks all for your help on this.


text:
Q: How to retrieve awareness timezone datetime objects with PyMongo I'm facing a problem with PyMongo 3.9 and datetime objects. In my MongoDB 4.x server I have a document like this one:
{
    "_id" : 2,
    "status" : "Running",
    "start_date" : ISODate("2020-11-19T05:03:54.576Z")
}

As you see, the start_date is in UTC zone, but the timezone is lost when I retrieve the document with PyMongo:
db.get_collection('my_collection').find_one({'_id': {'$eq': 2}})

I have read here https://pymongo.readthedocs.io/en/stable/api/bson/codec_options.html that Mongo returns by default a naive timezone datetime and, in order to get an awareness timezone datetime, I should add this option to the query:
opts=CodecOptions(tz_aware=True)
db.get_collection('my_collection', codec_options=opts).find_one({'_id': {'$eq': 99}})

But this means relying on the developer's memory to remember to add this option to each query. So my question is: Is there any way to configure MongoDB, PyMongo or whatever to always return awareness timezone datetime objects?
Thank you so much!

A: You can do it at the MongoClient level with the tz_aware parameter.
client = pymongo.MongoClient(tz_aware=True)


text:
Q: How to read bytes at an address in C? I am working with some page table entries and have a virtual address. Each page has data on it and the virtual address is mapped to that page.
If I have a 32 bit virtual address, how can I "grab" the first byte at a specific virtual address?
int *virtualAddress = someaddress;
int byteAtAddress = *(virtualAddress);
int secondByte = *(virtualAddress + 4);

Obviously I am getting 4 bytes instead of getting one byte. What trick can I use here to only get one byte?

A: The C standard permits you to cast an address of memory that you own to an unsigned char*:
unsigned char* p = (unsigned_char*)someaddress;
You can then extract the memory one byte at a time using pointer arithmetic on p. Be careful not to go beyond the memory that you own - bear in mind that and int could be as small as 16 bits.

A: I don't understand why you ask, but still is apparently a valid question. I say "I don't understand", because you say "Obviously I am getting 4 bytes"
unsigned char *virtualAddress = comeaddress;
unsigned char byteAtAddress = virtualAddress[0];

Note, that pointer arithmetic takes consideration of the pointer type so *(virtualAddress + 4) is1 actually adding 16 bytes to the base address.
In fact it is equivalent to
*((unsigned char *) virtualAddress + 4 * sizeof(*virtualAddress))

1Assuming you are on a regular system where sizeof(int) == 4 whichs is not necessarily true.


text:
Q: trouble with labeling axis with strings using ggplot (R) I'm a college student and we have to create some graphs using Rstudio for an assignment. I've managed to do the core objective for this first task, which is to create a simple bar graph with the provided data; however, I'm having trouble with labeling the axes with the desired text.
Here's the code:
library (ggplot2)

Country = as.factor(c("slovakia", "iceland", "lithuania"))
Waste = c(2.0, 3.7, 2.1, 2.3, 1.7, 2.5)
Year = as.factor(c("2004", "2018"))

data = data.frame(Country, Waste, Year)

ggplot(data,
       aes(x = Country,
           y = Waste,
           fill = Year)) +
  geom_bar(stat = "identity",
           position = "dodge")
 xlab("Country")
   ylab("Tons of waste per capita")

This is the output:

But I want the axis labels to have this specific text (made with Word):

Please note that we were specifically asked to use ggplot.

A: With ggplot2, you have to use + at the end of your line of code to add additional layers to your plot. If not, then R just reads those lines of code as standalone lines, which will throw an error. So, in your code, the sign is missing at the end of geom_bar and xlab, which means the x and y label lines are never added to your plot.
library(ggplot2)

ggplot(data,
       aes(x = Country,
           y = Waste,
           fill = Year)) +
  geom_bar(stat = "identity",
           position = "dodge") +
xlab("Country") +
ylab("Tons of waste per capita")

Output

Data
data <- structure(list(Country = structure(c(3L, 1L, 2L, 3L, 1L, 2L), class = "factor", levels = c("iceland",
"lithuania", "slovakia")), Waste = c(2, 3.7, 2.1, 2.3, 1.7, 2.5
), Year = structure(c(1L, 2L, 1L, 2L, 1L, 2L), class = "factor", levels = c("2004",
"2018"))), class = "data.frame", row.names = c(NA, -6L))


text:
Q: How to show a long sentence on character LCD by using bascom? I want to show a long message that going to differ every time and it's 3 lines or less. This message comes from Sim900. I cant show the whole sentence on my 4x20 lcd. how can I print it in several lines?

A: See SPLIT.
You can use e.g. the SPLIT command to split the text in multiple lines (like 0-20 for the first line, 20-39 for the second line, 40-59 for the third line).
However, this is quite a 'crude' way because words will be split in the middle.
To improve this, some smarter algorithm is needed, e.g. checking position 19 if it is a space, if not, go backwards until a space is found, than print index 0 to that position (except the space) to the first line, and do the same for the other two lines. Also it might be there are no spaces at all, or the text will not fit on the three lines (like words of 10 characters each with spaces in between).


text:
Q: How can I "specialize" a polymorphic type in Coq? (Note, my goal is to learn more about Coq, not necessarily solve this particular problem. IRL, I expect I would just refactor to remove the offending type in that situation.)
I have a type defined this way:
Inductive natprod : Type := pair (n1 n2 nat).

I want to make my product type polymorphic, so I now defined
Inductive prod {X Y : Type} : Type := pair (x : X) (y : Y).

However, I can't have both prod and natprod defined in the same module because they both have a constructor pair. But I have a bunch of functions and theorems for natprod, so I don't want to throw away natprod. Instead, I'd like to basically say "When I write natprod, what I mean is prod nat nat."
So I tried this:
Definition natprod := prod nat nat.

However, I get the following error:
Illegal application (Non-functional construction):
The expression "prod" of type "Type" cannot be applied to the term
 "nat" : "Set"

How can I do what I want to do?

A: It turns out the issue was that X and Y were defined to be implicit arguments to prod. We can solve this issue by forcing them to be explicit:
Definition natprod := @prod nat nat.

Alternatively,
Notation natprod := (@prod nat nat).

is more like a macro and does not need to be unfolded in proofs.


text:
Q: Unable to find cordova-3.5.0.jar file I am creating phonegap app for android. For this, I followed all steps from http://phonegap.com/install/
My Project is created but didn't get cordova-3.5.0.jar file which I have to add in /libs folder. Can anybody help me how to get this file. I am stuck at this point. Please help me..!!!

A: Did You Check the jar is added in BuildPath ?

A: There is no need to copy any libraries as the Eclipse project is created during the platform creation.
Please follow this guide step-by-step:
http://cordova.apache.org/docs/en/3.5.0/guide_platforms_android_index.md.html#Android%20Platform%20Guide

A: Try below link.. Then your phonegap should download on phonegap official site only.
http://docs.phonegap.com/en/3.5.0/guide_cli_index.md.html#The%20Command-Line%20Interface

A: Apache Cordova is open source, and the engine powering PhoneGap, the mobile development framework produced by Nitobi and since, purchased by Adobe.
Step for phonegap/cordova setup

*

*Install Node

*npm install -g cordova

*cordova create project com.yourdomain.project

*cordova platform add ios android


text:
Q: Create a separate table for employees work hours? I have a table with employees information:
id, active, first_name, last_name, gender, id_number, address, picture, password, comment

Every employee has an entrance time and an exit time for each day of the week except Saturday. It is possible that an employee has two entrance times and two exit times (when he chooses to take a break).
So, for example, an employee could have the following working time scheme:
         | Sunday  |  Monday  |  Tuesday  |  Wednesday  |  Thursday  |  Friday
---------+-------------------------------------------------------------------
Entrance | 08:00      08:00       07:30        07:30        07:30       07:00
Exit     | 16:00      13:00       12:30        15:30        12:30       15:00
Entrance |   -        13:30       13:00          -          13:00         -
Exit     |   -        16:30       16:00          -          16:00         -

I thought to add this information to the Employee table, so the columns would be like so:
id, active, first_name, last_name, gender, id_number, address, picture, password, comment, 1st_entrance_sunday, 1st_exit_sunday, 1st_entrance_monday, 1st_exit_monday, 1st_entrance_tuesday, 1st_exit_tuesday, 1st_entrance_wednesday, 1st_exit_wednesday, 1st_entrance_thursday, 1st_exit_thursday, 1st_entrance_friday, 1st_exit_friday, 2st_entrance_sunday, 2st_exit_sunday, 2st_entrance_monday, 2st_exit_monday, 2st_entrance_tuesday, 2st_exit_tuesday, 2st_entrance_wednesday, 2st_exit_wednesday, 2st_entrance_thursday, 2st_exit_thursday, 2st_entrance_friday, 2st_exit_friday.

But it just seems... wrong.
So I thought to create another table WorkHours for that, with this columns:
employee_id, day, entrance, exit

Which is way cleaner and simpler, but is it logic? I mean, this is information about the employee, so shouldn't it be inside the Employee table? Do you have a suggestion for a completely different approach?

A: It should not be in the employee table because you will have columns named "entrance_Sunday", "exit_Sunday", "entrance_Monday", etc.
This is a very bad design. Suppose you have another table with a column containing a "day-of-the-week" value. You won't be able to join these tables without some very ugly SQL:
SELECT
  CASE calendar.day_of_week
     WHEN 'Sunday' THEN entrance_Sunday
     WHEN 'Monday' THEN entrance_Monday
     ...

FROM holiday_calendar
INNER JOIN employees

With a separate schedule table it's simple:
SELECT ... FROM calendar
INNER JOIN schedule ON schedule.day_of_week = calendar.day_of_week

A: Database Normalization
First Normal Form (1NF)

*

*Eliminate duplicate columns

*Create separate tables for each group of related data

You should create a table employee_access and each time a employee enters or quits the building record the date and time:
id, employee_id, date_time, operation
operation field should contain IN or OUT
You may ask why not two fields (in_time and out_time) ?

*

*speed

*simplicity

*versatility

If your company is like mine, people use to log several OUTs or INs and not exactly in pairs (sometimes they log IN when they're going OUT, but that's called Managers) ;)


text:
Q: Update multiple divs with AJAX I'm trying to update many divs within an html table.
I grabbed an example code from https://www.easy-coding.de/wiki/Entry/64-Mehrere-DIV-Container-mit-AJAX-aktualisieren/ and in general it is working as it should.
Every div, which needs to be updated has a unique id (e.g. "s-1", "s-2", "s-3", ...) and contains the following script snippet:
<div id="s-<?php echo $contact_array_row['id']; ?>">initial content

This is my modified refresh java script:
/**
 * xxx [..] by http://www.easy-coding.de
 *
 * @param url
 * @param poll
 */
function UpdateManyDivs(url, poll, tab) {
    this.url = url;
    this.poll = poll ? poll : 750;
    this.list = [];
    this.timer = null;
    this.tab = tab;

    /**
     * adds elem
     * @param   id      string as id
     */
    this.push = function(id) {
        this.list.push(id);
    };

    /**
     * sends single request
     * @param loop  boolean
     */
    this.fire = function(loop) {
        ajaxPost(this.url + '?' +this.list.join('&'), 'seed='+ new Date().getTime() + '&tab=' + tab, function(up) {
            return function() {
                if (this.readyState == 4 && this.status == 200) {
                    if(loop) {
                        // start timer
                        up.start();
                    }

                    var data = eval('(' + this.responseText + ')');
                    for(var key in data) {
                        document.getElementById(key).innerHTML = data[key];
                    }
                }
            };
        }(this));
    };

    /**
     * stops auto updater
     */
    this.stop = function() {
        window.clearTimeout(this.timer);
    };

    /**
     * starts auto updater
     */
    this.start = function() {
        this.timer = window.setTimeout(function(up) {
            return function() {
                up.fire(true);
            };
        }(this), this.poll);
    };

}

It is called with the following one-liner:
var up = new UpdateManyDivs('include/callback.php', 1000, event_id);

The problem is, that most of the data is written in the $_GET variable.
If the table containing the divs is too big, it isn't working anymore.
I would like to use the $_POST variable instead, and therefore changed the following line:
ajaxPost(this.url + '?' +this.list.join('&'), 'seed='+ new Date().getTime() + '&tab=' + tab, function(up) {

...to this one:
ajaxPost(this.url, '?' +this.list.join('&') + '&seed='+ new Date().getTime() + '&tab=' + tab, function(up) {

In my callback PHP script I changed the following foreach loop:
foreach(array_keys($_GET) as $identifier) {
    $identifier_array = explode("-", $identifier);
    $data[$identifier] = getStatusMYSQL($identifier_array[1],$identifier_array[0],$_POST['tab']);
}

...to this one:
foreach(array_keys($_POST) as $identifier) {
    $identifier_array = explode("-", $identifier);
    $data[$identifier] = getStatusMYSQL($identifier_array[1],$identifier_array[0],$_POST['tab']);
}

Unfortunately this isn't working and after several hours trying to fix it, I'm out of ideas.
Is there anything, I'm missing?
Thanks,
relkai


text:
Q: Ansible get a dictionary item with a dynamically compiled key name In one Ansible playbook I include a variables file which contains one variable like this:
dictionaries:
  - host1:
    - key1:
      - name: "Foo"
        params:
        - bar: "Baz"
  - host2:
    - key1:
      - name: "Foo2"
        params:
        - bar: "Baz2"
  - host3:
    - key1:
      - name: "Foo3"
        params:
        - bar: "Baz3"

I want to take only the element of the list which key name is the Ansible {{ inventory_hostname }} of the host Ansible is executing the playbook on.
So for example, if I execute the playbook on host2 I want to get the dictionary:
- key1:
  - name: "Foo2"
    params:
    - bar: "Baz2"

I'm trying to use the lookup plugin but I'm not sure how I can use it in this situation.

A: After my comment above, let's try an answer with what I think is the correct data structure. This is how I would change it:
dictionaries:
  host1:
    key1:
      name: "Foo"
      params:
        bar: "Baz"
  host2:
    key1:
      name: "Foo2"
      params:
        bar: "Baz2"
  host3:
    key1:
      name: "Foo3"
      params:
        bar: "Baz3"
    key2:
      name: "toto"
      params:
        titi: "tata"

Now let's say you want to access the name of key2 for host3, your jinja2 template string would be
"{{ dictionnaries.host3.key2.name }}"

You can also use the bracket notation for this, i.e.
"{{ dictionnaries['host3']['key2']['name'] }}"

... or a combination (these are all equivalent, non exhaustive list of examples)
"{{ dictionnaries['host3'].key2.name }}"
"{{ dictionnaries['host3']['key2'].name }}"
"{{ dictionnaries.host3.key2['name'] }}"

Back to your question: you now want to access a hashmap of keys for a specific host while running a playbook. I take for granted that the keys in your dictionnaries variable are named after the host in your inventory. So I use the inventory_hostname magic variable which contains that name when running on a specific host
---
- name: debug vars from my dict
  hosts: whatever_group

  vars:
    dictionaries:
      host1:
        key1:
          name: "Foo"
          params:
            bar: "Baz"
      host2:
        key1:
          name: "Foo2"
          params:
        bar: "Baz2"
      host3:
        key1:
          name: "Foo3"
          params:
            bar: "Baz3"
        key2:
          name: "toto"
          params:
            titi: "tata"

  tasks:
    - name: debug hashmap per host
      debug:
        msg: "{{ dictionaries[inventory_hostname] }}"

All of this being said, this is sort-of reinventing the wheel as ansible already has a mechanism to declare variables per host in your inventory. You could symply declare your hashmaps in a host_vars/<hostname>.yml file for each of your hosts. Then all you have to do is to use those variables as-is.
Have a look at the ansible documentation on inventories and more specifically the chapter on organizing host and group variables


text:
Q: package org.qtproject.qt5.android.bindings does not exist While I'm trying to build Hue Qt example android(https://github.com/BradyBrenot/huestacean), stuck at this error.
I'm new in Qt. My Qt version 5.12.0 and Android studio 3.3.2
error: package org.qtproject.qt5.android.bindings does not exist

What Should I do solve this error?
Thanks in advance.
Addition.
Now I tried with QtCreator.  But build error with Unknown module(s) in QT: androidextras

Addition#2.
After addging Android Kit at preference, error message became as below
The installed SDK tools version (26.1.1) does not include Gradle scripts. The minimum Qt version required for Gradle build to work is 5.9.0/5.6.3

A: try
import org.qtproject.qt.android.bindings.QtService;

https://doc.qt.io/qt-6/android-services.html


text:
Q: PostgreSQL - how to format number into custom time(hours, minutes) i have problem to figure out how to select column as custom time format. I have column let say "time" with row value "70" and i want to format it to
1h 10min

and when the value will be in example "50" then i need such output:
50min

i've read about formating like HH:MI:SS but i want to include that "h" for hours and "min" for minutes.

A: The simplest way is converting to the interval or using divide. Something like this (two options + 1 custom format):
    with t as (select 70 as minutes
               union
               select 210
               union
               select 50
               union
               select 0
               union
               select 10000)
    select
        t.minutes,
        (t.minutes || 'minutes')::interval as full_time,
        make_interval(mins => t.minutes) as full_time2,
        t.minutes/60 || 'h ' || mod(t.minutes,60) || 'min' as custom,
case when t.minutes < 60 then '' else t.minutes/60 || 'h ' end || mod(t.minutes,60) || 'min' as custom2
    from t
    order by t.minutes;


text:
Q: как сделать thumbnails у записей хорошего качества?
Как мне избавиться от мыльных thumbnails в записях wordpress ? чтобы они были хорошего качества ?

A: Сделайте что-то вроде
add_filter('jpeg_quality', create_function('', 'return 100;'));

100 - это максимальное качество, можно поставить меньше
Фильтр будет работать только для новых изображений. Уже загруженные в медиабиблиотеку можно пересоздать при помощи какого-нибудь плагина, например, Regenerate Thumbnails


text:
Q: About Theorem 3.4 Hartshorne: detailed proof. I propose a detailed version of part of the proof of Theorem 3.14 from Hartshorne's book Algebraic Geometry. The questions are inserted from time to time within the proof. Thanks for your patience.
Notation Let $Y\subseteq\mathbb{P}^n$ be a projective variety. Letting $S=k[x_0,\dots, x_n]$ (equipped with the usual grading $S=\oplus_{r\ge 0} S_r$), there is a naturale grading on $S(Y)=S/I(Y)$ which is constructed as follows: for each integer $r\ge 0$ define $$S(Y)_r:=S_r/I(Y)_r:=\{f+I(Y)_r\;:\; f\in S_r\}$$ where $I(Y)_r=I(Y)\cap S_r.$

Theorem. Let $Y\subseteq\mathbb{P}^n$ be a projective variety with homogeneous coordinate ring $S(Y)$. Then we have:
$(a)\quad$ for any point $P\in Y$, let $\mathcal{m}_P\subseteq S(Y)$ denote the ideal generated by the set of all homogeneous elements $f\in S(Y)$ such that $f(P)=0$. Then $\mathcal{O}_P=S(Y)_{(\mathcal{m}_P)}$;
$(b)\quad$ $K(Y)\cong S(Y)_{((0))}$

Proof. Let $U_i\subseteq\mathbb{P}^n$ be the open set defined by $x_i\ne 0$ and set $Y_i:= Y\cap U_i$. We may consider $Y_i$ as an affine variety. We can construct a natural isomorphism $$\varphi_i^*\colon A(Y_i)\to S(Y)_{(x_i)}$$ as $$\varphi_i^*\bigg(f(y_1,\dots, y_{i-i},1, y_i, \dots, y_n)+I(Y_i)\bigg)=\frac{f(x_0,\dots, x_n)+I(Y)_r}{x_i^r+I(Y)_r},$$ where $f\in S_r$.
$(b)\quad$ Let $P\in Y$ and chose any $i$ so that the $i-$th coordinate of $P$ is non-zero. Then $P\in Y\cap U_i$. We may write $P=[a_0:\dots: a_{i-1}:1:a_i:\dots: a_n]$. Set $P_0:=(a_0,\dots, a_{i-1}, a_{i+1},\dots, a_n)=\varphi_i(P)$, the corresponding point in the affine space.
Denote with $\mathcal{m'}_{P_0}$ the maximal ideal of $A(Y_i)$ corresponding to $P_0$. More precisely, $$\mathcal{m'}_{P_0}=\bigg\{g+I(Y_i)\in A(Y_i)\;:\; g(P_0)=0\bigg\}.$$ It's easy to prove that: $$\boxed{\varphi_i^*(\mathcal{m'}_{P_0})=\mathcal{m}_P\cdot S(Y)_{(x_i)}}$$ Recall that the product in the right of the above equation is interpreted in the localization as follows (with the natural induced grading on the quotient ring $S(Y)=S/I(Y))$
$$\mathcal{m}_p\cdot S(Y)_{(x_i)}=\bigg\{\frac{f(x_0\dots, x_n)+I(Y)_r}{x_i^r+I(Y)_r}\;:\; f+I(Y)_r\in\mathcal{m}_P\cap S(Y)_r\;\text{for same}\; r\ge 0\bigg\}.$$
Using this isomorphism, we then have the isomorphism of the localizations $$A(Y_i)_{\mathcal{m'}_{P_0}}\cong \big(S(Y)_{(x_i)}\big)_{\mathcal{m}_P\cdot S(Y)_{(x_i)}}$$

Question 1. I believe that the last isomorphism can be obtained from exercise number 4 on page 44 of Introduction to Commutative Algebra by Atiyay - MacDonald, is that so?

We need to argue that $$\big(S(Y)_{(x_i)}\big)_{\mathcal{m}_P\cdot S(Y)_{(x_i)}}\cong S(Y)_{(\mathcal{m}_P)}\tag1$$

Question2. Why $(1)$ is not usual transitivity of localizations?

A typical element in $\big(S(Y)_{(x_i)}\big)_{\mathcal{m}_P\cdot S(Y)_{(x_i)}}$ is of the form
$$\frac{\frac{f+I(Y)_{s+r}}{x_i^{r+s}+I(Y)_{s+r}}}{\frac{g+I(Y)_r}{x_i^r+I(Y)_r}}\equiv \frac{f+I(Y)_{s+r}}{x_i^sg+I(Y)_{s+r}}$$ where $g+I(Y)_r\notin\mathcal{m}_p\cap S(Y)_r$, and the identification takes place in the quotient field of $S(Y)$. Now since $x_i^s+I(Y)_s\notin \mathcal{m}_p\cap S(Y)_s$ it follows that the product $x_i^sg +I(Y)_{s+r}\notin\mathcal{m}_p\cap S(Y)_{s+r}$. So the element on the right is a degree $0$ element of the localization
$$S(Y)_{\mathcal{m}_P}=\bigoplus_{n\in\mathbb{Z}}\big(S(Y)_{\mathcal{m}_P}\big)_n$$ where
$$\big(S(Y)_{\mathcal{m}_P}\big)_n=\bigg\{\frac{p+I(Y)_{n+r}}{q+I(Y)_r}\;:\; q+I(Y)_r\notin \mathcal{m}_P\cap S(Y)_r\;\text{for same}\; r\ge 0\bigg\}.$$ This proves that $$A(Y_i)_{\mathcal{m'}_{P_0}}\cong (S(Y)_{\mathcal{m}_p})_0=S(Y)_{(\mathcal{m}_P)}$$
$(b)\quad$ Observe that $K(Y)\cong K(Y_i)$. The final part is to show that $$K(Y_i)\cong S(Y)_{((0))}.$$ We have already obtained the isomorphism $\varphi_i^*\colon A(Y_i)\to S(Y)_{(x_i)}$. Extending this isomorpgism to $\tilde{\varphi_i^{*}}$ on the quotient fields fo both the sides we get $$\tilde{\varphi_i^*}\bigg(\frac{f(y_1,\dots, y_{i-1},1, y_i, \dots, y_n)+I(Y_i)}{g(y_1,\dots, y_{i-1},1, y_i, \dots, y_n)+I(Y_i)}\bigg)=\frac{\frac{f(x_0,\dots, x_n)+I(Y)_r}{x_i^r+I(Y)_r}}{\frac{g(x_0,\dots, x_n)+I(Y)_s}{x_i^s+I(Y)_s}}=\frac{x_i^s f(x_0,\dots, x_n)+I(Y)_{r+s}}{x_i^rg(x_0, \dots, x_n)+I(Y)_{r+s}}$$
In the denominator of the last expression above we have $g(x_0,\dots, x_n)+I(Y)_s\ne 0$ So to make sense of this, we need $x_i^r+I(Y)_r\ne 0$ as well. Since $I(Y)$ is a homogeneous prime ideal, this is violated only if $x_i\in I(Y)$. I have proved that $x_i\in I(Y)$ is equivalent to $Y_i=\emptyset$, which is absurd according to our choise of $U_i$.
Finally, notice that the element in the image of $\tilde{\varphi_i^*}$ in above are elements of $S(Y)_{((0))}$.

Question 3 It remains to show that every element of $S(Y)_{((0))}$ is also an image of an element of $K(Y_i)$. How can I show this?

My Solution for question 3.
A typical element in $S(Y)_{((0))}$ is of the form $$\frac{f(x_0,\dots, x_n)+I(Y)_r}{g(x_0,\dots, x_n)+I(Y)_r},$$ where $f+I(Y)_r\in S(Y)_r$ and $g+I(Y)_r\notin S(Y)_r\cap (0)$. Let us consider the dehomogenized of $f$ and $g$: $$f(y_1,\dots, y_{i-1}, 1, y_i,\dots, y_n)\quad\text{and}\quad g(y_1,\dots, y_{i-1}, 1, y_i,\dots, y_n),$$ where $\deg f(y_1,\dots, y_{i-1}, 1, y_i,\dots, y_n)= \deg g(y_1,\dots, y_{i-1}, 1, y_i,\dots, y_n) = r$, results
$$\begin{split}\tilde{\varphi_i^*}\bigg(\frac{f(y_1,\dots, y_{i-1},1, y_i, \dots, y_n)+I(Y_i)}{g(y_1,\dots, y_{i-1},1, y_i, \dots, y_n)+I(Y_i)}\bigg)=&\frac{\frac{f(x_0,\dots, x_n)+I(Y)_r}{x_i^r+I(Y)_r}}{\frac{g(x_0,\dots, x_n)+I(Y)_r}{x_i^r+I(Y)_r}}\\
=\frac{f(x_0,\dots, x_n)+I(Y)_{r}}{g(x_0, \dots, x_n)+I(Y)_{r}}\end{split}$$
The above happens just in case $x_i\nmid f$ and $x_i \nmid g$.
Suppose now that $x_i\mid f(x_0,\dots, x_n)$ and that $x_i\nmid g(x_0,\dots, x_n)$
We denote by $h(x_0,\dots, x_n)$ the homogenized polynomial of $f(y_1,\dots, y_{i-1},1,\,y_i,\dots, y_n)$, then $h\in S_{\deg f}$, then
$$
\begin{split}
\tilde{\varphi_i^*}\bigg(\frac{f(y_1,\dots, y_{i-1},1, y_i, \dots, y_n)+I(Y_i)}{g(y_1,\dots, y_{i-1},1, y_i, \dots, y_n)+I(Y_i)}\bigg)=
\frac{\frac{h(x_0,\dots, x_n)+I(Y)_{\deg f}}{x_i^{\deg f}+I(Y)_{\deg f}}}{\frac{g(x_0,\dots, x_n)+I(Y)_r}{x_i^r+I(Y)_r}}=&\frac{x_i^{r-\deg f} h(x_0,\dots, x_n)+I(Y)_{r}}{g(x_0, \dots, x_n)+I(Y)_{r}}\\
=&\frac{f(x_0,\dots, x_n)+I(Y)_r}{g(x_0,\dots, x_n)+I(Y)_r}
\end{split}
$$


text:
Q: ansible's lvg module isn't idempotent I use following ansible version:
$ ansible --version
ansible 2.9.21
  config file = /home/user/ansible.cfg
  configured module search path = [u'/home/user/.ansible/plugins/modules', u'/usr/share/ansible/plugins/modules']
  ansible python module location = /usr/lib/python2.7/site-packages/ansible
  executable location = /usr/bin/ansible
  python version = 2.7.5 (default, Nov 16 2020, 22:23:17) [GCC 4.8.5 20150623 (Red Hat 4.8.5-44)]

a playbook have such task for VG creation:
  - name: Create volumes group
    lvg:
     vg: "{{volumes_group_name}}"
     pvs: "{{device}}{{partition_number}}"
     pesize: "4"

When I run this playbook for the first time, it creates VG properly, but when I re-run it again it fails on VG creation tasks, though the VG is already there and should do nothing.
TASK [Create volumes group] ************************************************************************************************************************************************
Saturday 22 May 2021  20:05:17 +0200 (0:00:01.335)       0:00:03.976 **********
fatal: [192.168.170.110]: FAILED! => {"changed": false, "err": "  Can't initialize physical volume \"/dev/sdc1\" of volume group \"CCC_VG01\" without -ff\n  /dev/sdc1: physical volume not initialized.\n", "msg": "Creating physical volume '/dev/sdc1' failed", "rc": 5}

I expect it produces no error when VG is created and fine on target system.
Is there any workaround for such behavior?


text:
Q: Filecopy vs name function? Differences? I have found two different ways to copy single files in Excel using VBA. One is file copy:
FileCopy (originalPath), (pathToCopyTo)

The other is name:
Name (originalPath) As (pathToCopyTo)

Any differences in performance/intended use/functionality? I haven't been able to notice anything, but interested to know!

A: They actually do very different things.
FileCopy will actually make a new copy of the file at the location of pathToCopyTo, leaving the original file intact.
Name renames the original file. The effectively moves the file if you supply a different file path. (A copy/paste action.) So, the original file won't be where you found it, it will be in the new location.
For more information see the following MSDN documentation:

*

*Name Statement

*FileCopy Statement
As for performance, Name will preform better because it's not necessary for the OS to physically copy the data on disk. It will just update the file's location in the lookup tables. Incidentally, this is also the reason Cut/Paste file operations are faster than Copy/Paste file operations.


text:
Q: how add react component to a rails application I have a vanilla rails 5 application with no extra gems installed.
I do to do things like this
class HelloMessage extends React.Component {
  render() {
    return
Hello {this.props.name}
;
  }
}

ReactDOM.render(<HelloMessage name="John" />, mountNode);

A: give react-rails gem a try. The doc is simple to follow.


text:
Q: Calcul new coords of camera after a 90 degres rotation in a isometric 2D projection I made a 2D isometric renderer. It works fine but now I want to show my scene from 4 differents point of view (NO NW SE SW) but, on a 90° rotation, my camera cannot keep the center of my scene on screen.
What's working :

*

*I calcul new projection of scene to match the new viewport (x y z in my world).

*I reorganise part of my scene(chunk) to draw them in a correct order

*I reorganise 'tiles' of 'chunks' to draw them in a correct order

*I can keep the correct center with a 180 degres rotation.

What's do not working :

*

*I cannot find a correct translation to apply to my camera after a 90 degres rotation.

What I know :

*

*To keep the same center on a 180° rotation with my camera I have to do this :

camera.Position -= new Vector2(2 * camera.Position.X + camera.Width, 2 * camera.Position.Y + camera.Height);
Illustration

A: If the center of your map is origo (0,0,0), this gets easy:
First you store your default camera position in a Vector3 CameraOffset, then you calculate position using a rotation-matrix. 90* in redians is half a Pi, so we will use PiOverTwo. We will also use an enum to decide what direction to be pointing, so you can say
Camera.Orientation = Orientation.East;
and the camera should fix itself :)
public enum Orientation
{
    North, East, South, West
}

in camera:
public Vector3 Position { get; protected set; }

Vector3 _CameraOffset = new Vector3(0, 20, 20);
public Vector3 CameraOffset
{
    get
    {
        return _Orientation;
    }

    set
    {
        _Orientation = value;
        UpdateOrientation();
    }
}

Orientation _Orientation = Orientation.North;
public Orientation Orientation
{
    get
    {
        return _Orientation;
    }

    set
    {
        _Orientation = value;
        UpdateOrientation();
    }
}

private void UpdateOrientation()
{
    Position = Vector3.Transform(CameraOffset, Matrix.CreateRotationY(MathHelper.PiOverTwo * (int)Orientation));
}

If you want a gliding movement between positions, I think I can help too ;)
If your camera does not focus on Vector3.Zero and should not rotate around it, you just need to change:
Position = Vector3.Transform(CameraOffset, Matrix.CreateRotationY(MathHelper.PiOverTwo * (int)Orientation));

to:
Position = Vector3.Transform(CameraOffset, Matrix.CreateRotationY(MathHelper.PiOverTwo * (int)Orientation) * Matrix.CreateTranslation(FocusPoint));

Here, FocusPoint is the point in 3D that you rotate around (your worlds center). And now you also know how to let your camera move around, if you call UpdateOrientation() in your Camera.Update() ;)
EDIT; So sorry, totally missed the point that you use 2D. I'll be back later to see if I can help :P


text:
Q: Check if  is first child This the code on jsfiddle http://jsfiddle.net/KGDyR/
I need to add class on (each) p inside (each) div
If the p is the first child of div tag, add class .first
If not add .notfirst
So the output will be like this

p is first

p is not first

A: I'd suggest, for simplicity:
$('p').addClass(function(){
    return this.previousElementSibling === null ? 'first' : 'notfirst';
});

JS Fiddle demo.
Or, to work in those browsers that don't support previousElementSibling:
$('p').addClass(function(){
    return !$(this).prev().length ? 'first' : 'notfirst';
});

JS Fiddle demo.
References:

*

*addClass().

*Element.previousElementSibling.

*prev().

A: Use first-child
$("div p:first-child").addClass('first')

then :not
$("div p:not(:first-child)").addClass('notfirst')

Demo: Fiddle

A: The other way.
$('div').each(function(index, obj) {
    var c = $(this).is(':first-child') ? 'first' : 'notfirst';
    $(this).find('p').addClass(c);
})

A: If you're only using the first and notfirst classes for styling, you can target these elements purely with CSS, via p:first-child and * + p (ie. a p element that has a previous sibling and is therefore not a first child).
If you're adding the classes for other reasons (another script?) then you will need Javascript (as per Davis Thomas's answer, say). However, at the point where you add the classes, you've already had to grab those elements with Javascript, so why not do whatever you want to do at that point? In most (possibly not absolutely all, but most) cases it would be unnecessary to use Javascript to add classes that act as Javascript hooks, since you've already had to get the elements in question.
In other words, if you're using the classes for styling, you don't need Javascript; if you're using them as Javascript hooks, you probably don't need those classes.


text:
Q: Handling Undo Delete action in namespace extension I'm trying to process the Ctrl+Z ( Undo Delete ) context menu action in my namespace extension, but I'm having trouble finding a way to do this.
I see in the doc that one needs to implement FM_UNDELETE_PROC, but no details on how to register this callback.
Also tried to set a Shell hook, but no relevant messages arrive there.
Any thoughts?
Also, how would one register a delete operation so the explorer would allow the Undo to take place.
Now it appears if I do this from another location.
Thanks,
David

A: Windows has per process (prior to Vista) or global file operation stack. If you use API functions like SHFileOperation or IFileOperation interface you can pass FOF_ALLOWUNDO flag BUT this flag is ignored if the source file parameter does not contain fully qualified path and file names. It means if you want use system file operation stack your shell extension objects MUST have SFGAO_FILESYSTEM attribute and you MUST return valid file path and name when IShellFolder.GetDisplayNameOf is called with SHGDN_FORPARSING parameter. Also it is necessary to implement ITransferSource and ITransferDestination interfaces. So if objects don`t not have SFGAO_FILESYSTEM attribute you must use your own implementation of operation stack.
Undo Delete command in background context menu of folder or in Edit menu is system command and it has no any relation to your shell extension. And you should not process the Ctrl+Z manually.


text:
Q: Intelligent `\vref` I want to use the package varioref, but using abbreviations ... (p.1) instead
of ... on page 1. Unfortunately, I have also references in
parentheses, where this would lead to unaesthetic/forbidden (?) double closing brackets.
I tried using \@ifnextchar to recognize this case, but this seems not to work.
Here, a minimal example:
\documentclass[]{article}
\usepackage{varioref}
\usepackage{cleveref}
\usepackage[english]{babel}

\makeatletter
\addto\extrasenglish{%
     \def\reftextfaraway#1{\@ifnextchar){on p.~\pageref{#1}}{(p.~\pageref{#1})}}%
}
\makeatother

\begin{document}
In \vref{sec:test}, this is explained.
Other text (cf.\ \vref{sec:test}).

\newpage
\null\newpage
\section{Test}
\label{sec:test}
\end{document}

Intended output:

In chapter 1 (p. 3), this is explained. Other text (cf. chapter 1 on
  p. 3).

Current output:

In chapter 1 (p. 3), this is explained. Other text (cf. chapter 1
  (p. 3)).

A: Here I save the definition of \vref and then redefine it with two arguments.  I check if the second argument is a ) and redefine \reftextfaraway accordingly.  I then call on the saved version of \vref with the first argument and pass freely the 2nd argument.
\documentclass[]{article}
\usepackage{varioref}
\usepackage{cleveref}
%\usepackage[english]{babel}

\let\svvref\vref
\makeatletter
%\addto\extrasenglish{%
     \renewcommand\vref[2]{%
       \ifx)#2%
         \renewcommand*{\reftextfaraway}[1]{on p.~\pageref{#1}}%
       \else
         \renewcommand*{\reftextfaraway}[1]{(p.~\pageref{#1})}%
       \fi
     \svvref{#1}#2%
     }%
%}
\makeatother

\begin{document}
In \vref{sec:test}, this is explained.
Other text (cf.\ \vref{sec:test}).

\newpage
\null\newpage
\section{Test}
\label{sec:test}
\end{document}


text:
Q: Error: $digest already in progress in angularjs when using alert I am just getting the json data from the services in the controller.
And I am using a callback function to print the success message when it got loaded. It is working fine but it is also throwing an error which I mentioned in the question
//JSON file
{
"pc":"name"
}

// angular services
var service = angular.module('Services', ['ngResource']).
factory('Widgets', function($resource){
    return $resource('/json/home.json', {}, {
        query: {method:'GET', params:{}, isArray:false}
    });
});

//controller
function editWidget($scope, Widgets) {
 $scope.data = Widgets.query(function(data) {
    alert("Success Data Loaded ---> " + JSON.stringify(data.pc));
 });
}

A: alert, as well as confirm and prompt will pause the execution of code (blocks the thread), during which timeouts and intervals go all haywire if they should have been triggered during the pause.  The $digest loop is made up of two smaller loops, which process $evalAsync queue and the $watch list.  The $evalAsync queue is used to schedule work which needs to occur outside of current stack frame, but before the browser's view render. This is usually done with setTimeout(0).  Your alert during this time causes the problem.

A: You can use $timeout to execute an alert after the digest cycle is done and this way avoids this error.
$timeout(function () {
    alert('Alert text');
 });

Also don't forget to inject $timeout into your directive

A: if(!confirm('Your message')){
  return false;
}else {
  return false;
}

Return false in both cases.

A: @TheSharpieOne is right, It's work for me.

function delayalert(messagestr){
           setTimeout(function(){
                alert(messagestr);
            },0);
}