text:
Q: android found tag ... where item is expected I'm working on a project that has a custom XML file in the res/values map.
It's not a deep XML:
<resources>
    <accesspoint
    ...

Eclipse is generating an error: found tag accesspoint where item is expected
Now, I've googled this a bit and there are similar problems everywhere. But no solution.
When I change them all to item and give them a name and a type, I still get an error on the closing tags that simply says "Orginally defind here".
I'm out of ideas here, does anyone know what this means? And how I fix it?

A: Right click on the xml file in the package explorer, then Source -> Format.

A: I know this is a 9 years old question. But I got the same error message today. My solution differs from the described answers. Changes in the - here - corresponding file accesspoints.xml were necessary. My corresponding content was:
<resources>
    <accesspoint name="btnOpen">false</accesspoint>
    ...
</resources>

This accesspoint tag is to be replaced by the item tag:
<resources>
    <item type="accesspoint" name="btnOpen">false</item>
    ...
</resources>

A: Tried all of the above solutions. None of them worked. Found the problem in Eclipse:
Copy the xml file from res/values folder to res/xml folder.

A: Something is a bit screwy in Eclipse.  I had the same problem as you no matter what I renamed the tag.
Solution:  delete the tag, and re-write it by hand (DON'T COPY/PASTE).
There must be some kind of strange hidden character that gets in there somehow, because just re-writing the EXACT same thing, and I now have no errors.

A: Running the xml source file through xmllint is a good way to pick up otherwise non-visible special characters. In particular keep an eye out non-breakable space ( / / ) which can cause cryptic errors if they occur where the ADK tools are expecting whitespace.

A: open the xml file with MadEdit or any other Hex File editors, look for "C2 A0" and replace all with normal space.
Or simply in the command line
$sed -i 's/\xc2\xa0/ /g' /the/path/to/the/xml/file

A: There can be many reasons for this error. Probably these issues are arising due to simple mistakes.
Those can be

*

*Invalid characters in the string value. Remove unsupported characters and check.

*When we copy/paste from some other places, there can be possible of having hidden/unnoticed invalid characters, so check for that and remove those.

Advice :
Instead of copying/pasting, type by yourself.

A: Sometimes Eclipse goes crazy.
Paste your code in Notepad and then copy it from Notepad and paste it to Eclipse.


text:
Q: Javascript appendChild isn't working as it should I want to create a Grid with 3 columns and * rows. The problem is something with this row.appendChild(col); element. This work 2 runs or zero runs. There isn't an error, I tried different browsers, I haven't a clue.
Can a buffer overload or a memory got overfilled?

var Jsonstring ='[{"Imgname":"http://localhost:8080/sbin/_DisplayImage/5ee3e2962d3752338c090e67_2020-06-12_1e9b5.jpg"},{"Imgname":"http://localhost:8080/sbin/_DisplayImage/5ee3e2962d3752338c090e67_2020-06-12_21c02.jpg"},{"Imgname":"http://localhost:8080/sbin/_DisplayImage/5ee3e2962d3752338c090e67_2020-06-12_542b9.jpg"},{"Imgname":"http://localhost:8080/sbin/_DisplayImage/5ee3e2962d3752338c090e67_2020-06-12_66721.jpg"},{"Imgname":"http://localhost:8080/sbin/_DisplayImage/5ee3e2962d3752338c090e67_2020-06-12_8bbfd.jpg"}]';

function doShowUploadedPictures() {
  try {

    var obDaten = JSON.parse(Jsonstring);

    //
    var div = document.getElementById("uploaded");
    div.innerHTML = "";
    div.classList.add("pt-3");

    //
    var row = document.createElement("div");
    row.classList.add("row");

    //
    var icount = 1;
    for (var i in obDaten) {
      if (true) {
        var btndiv = document.createElement("div");
        btndiv.classList.add("position-absolute");
        btndiv.style = "display: none";

        var button = document.createElement("button");
        button.classList.add("btn", "btn-danger");
        button.innerHTML = "del";
        btndiv.appendChild(button);

        var img = document.createElement("img");
        if (obDaten[i].Imgname !== null) {
          img.src = obDaten[i].Imgname;
        }
        if (obDaten[i].alt !== null) {
          img.alt = obDaten[i].alt;
        }
        img.classList.add("img-thumbnail", "pt-0", "position-absolute");

        var col = document.createElement("div");
        col.classList.add("col-md-4", "position-relative");
        col.addEventListener('mouseover', function (event) {
          event.target.parentNode.childNodes[1].style = "display: flex";
        });
        col.addEventListener('mouseout', function (event) {
          event.target.parentNode.childNodes[1].style = "display: none";
        });

        //
        col.appendChild(img);
        col.appendChild(btndiv);
        row.appendChild(col);

        //
        if (icount && (icount % 3 === 0)) {
          div.appendChild(row);
          row.innerHTML = "";
        }

        icount++;
      }
    }
    div.appendChild(row);

  } catch (e) {
    console.log("Error " + e);
  }
}
<!DOCTYPE html>

<title>Page Title</title>

<button onclick="doShowUploadedPictures()">click</button>

</id>

A: There was a typo in your HTML as Leandro pointed out, which I fixed. You were also deleting entire rows as cyborg pointed out, and you should add append the row inside of the loop. I also tried to tidy up the code a bit so it is more legible and easy to debug.

var Jsonstring = '[{"Imgname":"http://localhost:8080/sbin/_DisplayImage/5ee3e2962d3752338c090e67_2020-06-12_1e9b5.jpg"},{"Imgname":"http://localhost:8080/sbin/_DisplayImage/5ee3e2962d3752338c090e67_2020-06-12_21c02.jpg"},{"Imgname":"http://localhost:8080/sbin/_DisplayImage/5ee3e2962d3752338c090e67_2020-06-12_542b9.jpg"},{"Imgname":"http://localhost:8080/sbin/_DisplayImage/5ee3e2962d3752338c090e67_2020-06-12_66721.jpg"},{"Imgname":"http://localhost:8080/sbin/_DisplayImage/5ee3e2962d3752338c090e67_2020-06-12_8bbfd.jpg"}]';

function doShowUploadedPictures() {
  var obDaten = JSON.parse(Jsonstring);

  // uploaded DIV
  var uploaded = document.getElementById("uploaded");
  uploaded.classList.add("pt-3");

  // loop
  var icount = 1;
  for (let item of obDaten) {

    // Create elements
    var row = document.createElement("div");
    var btndiv = document.createElement("div");
    var delButton = document.createElement("button");
    var img = document.createElement("img");
    var col = document.createElement("div");

    // Classes
    row.classList.add("row");
    btndiv.classList.add("position-absolute", "btn-div");
    delButton.classList.add("btn", "btn-danger");
    img.classList.add("img-thumbnail", "pt-0", "position-absolute");
    col.classList.add("col-md-4", "position-relative");

    // Styles, content
    btndiv.style.display = "none";
    delButton.innerHTML = "del";

    if (item.Imgname)
      img.src = item.Imgname;

    if (item.alt)
      img.alt = item.alt;

    // Build out tree
    btndiv.appendChild(delButton);
    col.appendChild(btndiv);
    col.appendChild(img);
    row.appendChild(col);

    // Add eventListeners
    col.addEventListener('mouseover', function(event) {
      var target = event.target.parentNode.querySelector('.btn-div');
      if (target)
        target.style.display = "flex";
    });

    col.addEventListener('mouseout', function(event) {
      var target = event.target.parentNode.querySelector('.btn-div');
      if (target)
        target.style.display = "none";
    });

    // DO STUFF WITH MODULUS 3 HERE

    // Append row, increment
    uploaded.appendChild(row);
    icount++;
  }
}
<!DOCTYPE html>

  <title>Page Title</title>

  <button onclick="doShowUploadedPictures()">click</button>

A: Look this up:

var Jsonstring ='[{"Imgname":"http://localhost:8080/sbin/_DisplayImage/5ee3e2962d3752338c090e67_2020-06-12_1e9b5.jpg"},{"Imgname":"http://localhost:8080/sbin/_DisplayImage/5ee3e2962d3752338c090e67_2020-06-12_21c02.jpg"},{"Imgname":"http://localhost:8080/sbin/_DisplayImage/5ee3e2962d3752338c090e67_2020-06-12_542b9.jpg"},{"Imgname":"http://localhost:8080/sbin/_DisplayImage/5ee3e2962d3752338c090e67_2020-06-12_66721.jpg"},{"Imgname":"http://localhost:8080/sbin/_DisplayImage/5ee3e2962d3752338c090e67_2020-06-12_8bbfd.jpg"}]';

function doShowUploadedPictures() {
  try {

    var obDaten = JSON.parse(Jsonstring);

    //
    var div = document.getElementById("uploaded");
    div.innerHTML = "";
    div.classList.add("pt-3");

    //
    var row = document.createElement("div");
    row.classList.add("row");

    //
    var icount = 1;
    for (var i in obDaten) {
      if (true) {
        var btndiv = document.createElement("div");
        btndiv.classList.add("position-absolute");
        btndiv.style = "display: none";

        var button = document.createElement("button");
        button.classList.add("btn", "btn-danger");
        button.innerHTML = "del";
        btndiv.appendChild(button);

        var img = document.createElement("img");
        if (obDaten[i].Imgname !== null) {
          img.src = obDaten[i].Imgname;
        }
        if (obDaten[i].alt !== null) {
          img.alt = obDaten[i].alt;
        }
        img.classList.add("img-thumbnail", "pt-0", "position-absolute");

        var col = document.createElement("div");
        col.classList.add("col-md-4", "position-relative");
        col.addEventListener('mouseover', function (event) {
          event.target.parentNode.childNodes[1].style = "display: flex";
        });
        col.addEventListener('mouseout', function (event) {
          event.target.parentNode.childNodes[1].style = "display: none";
        });

        //
        col.appendChild(img);
        col.appendChild(btndiv);
        row.appendChild(col);

        // This is the correct if for every 3rd round as you explained in post with the grid
        if (icount % 3 === 0) {
          div.appendChild(row);
  // To delete childs do not emtpy the element like this, because you must declare the new div
    var row = document.createElement("div");
    row.classList.add("row");

        }

        icount++;
      }
    }
    div.appendChild(row);

  } catch (e) {
    console.log("Error " + e);
  }
}
<!DOCTYPE html>

<title>Page Title</title>

<button onclick="doShowUploadedPictures()">click</button>

A: On your html code:
Your div element is closed incorrectly, you are putting:

</id>

You should put:

A: You are setting col as a child of row:
row.appendChild(col);

then you remove everything that's inside row, in some cases
if (icount && (icount % 3 === 0)) {
    div.appendChild(row);
    row.innerHTML = ""; // here
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Maxima and minima second derivative Let $f(x) = 2x^{3} - x^{4} - 10$ over $[-1,1]$
I found second derivative as $12x - 12x^2$
After trying values I found that  $f(x)$ gives minimum value at $x=-1$
If I substitute $x=-1$ in second derivative, then I get $-24<0$ so it should be Maxima right
Should we check second derivative only for critical points ? If yes, then why?

A: $$f(x) = 2x^3 - x^4 - 10 $$
It is defined, continuous, and differentiable at every point in $[-1,1]$
$$f'(x)=6x^2-4x^3$$
$$f''(x)=12x-12x^2$$
Let $f'(x)=0$, we find $x=0, \frac{3}{2}$
For $x \in [-1,1]$, we exclude $x=\frac{3}{2}$.
$f''(0)=0$, thus we cannot directly tell if it is max or min. or neither.
Thus we now complete value at $0$ and at boundaries:
$$f(0)=-10, \, f(1)=-9, \,f(-1)=-13$$
Thus max=$-9$, and min=$-13$
Or even better, we could see that:
$$f'(x)=6x^2-4x^3 \ge 0 \text{ over }[-1,1]$$
Thus it is non-decreasing over $[-1,1]$, and we get the result immediately

A: To answer your question: $f''(x_0)<0$ implies $f(x)$ is concave at the point $x_0$. If $x_0$ is a critical point ($f'(x_0)=0$), then it is a relative maximum. In your case $-1$ is not a critical point (it is a border point). Your problem is called a constrained optimization problem. According to the Extreme value theorem, the function is continuous in a closed interval, so it must have max and min. Now its extreme (max/min) values will be at either critical or border points, which is what you calculated. In general, the relative max could be not max of a constrained optimization problem. For example: find max of $f(x)=x^3-3x$ in $[-3,3]$.


text:
Q: Javascript with images I am currently trying to insert image with Javascript attached to it and for some reason it works on Firefox but the images or icons do not display on IE.
I have done the coding like this:

A: You could try:


text:
Q: How to programmatically obtain another device ip on an IOS ad hoc network? I have a DLSR Canon camera connected directly via wiFi ("ad hoc" network) to an iOS device running iOS 10.
How do I programmatically determine the address of the camera?  I want to send PTP ("Picture Transfer Protocol") messages to the device and receive the camera data on the iOS device.
I know I'm connected as WiFi network menu on the iOS device Network menu indicates I'm connected.
I can determine the iOS device IP address from within the app, but not the "other end point" of the network.  (BTW, I'm using Objective-C.)
Is there a method in Bonjour I could use?  Or something in Multipeer Connectivity?  I don't know what the Bonjour service name, hostname or IP address would be for the camera.    I know this is possible as Canon provides an app that does this very thing.


text:
Q: Salesforce Controller Test: getAccounts method not filtering by profile I have a custom controller that is intended to return a results set to a visualforce page for customized viewing.  It works fine in production.  When building my unit test for this controller, however, I set up a dummy sales rep User and try to run that controller as this user and it flags my assertEquals with System.AssertException: Assertion Failed: Expected: (), Actual: (Account:{Name=test1, RecordTypeId=01280000000EqShAAK, Id=001C000001PibPOIAZ}).
Test Code:
@isTest
public without sharing class Test_Sorted_Account_Controller {

//test method for Sorted Account page controller
static testMethod void testAccountController(){

    //Create an instance class so that you can call the getAccounts method from the Sorted_Accounts_Filtered_by_User class
    //This copies the Sorted Account controller as a test controller
    Sorted_Account_Filtered_by_User testController= new Sorted_Account_Filtered_by_User();

//Add a sales rep with which to test the filtered accounts controller.
    User testSalesRep = new User(Alias='SRep', email='sales.email@test.com' ,LastName='Testing'
                                            ,EmailEncodingKey='UTF-8'  ,LocaleSidKey='en_US' ,LanguageLocaleKey='en_US'
                                            ,ProfileID='00e80000000z1QfAAI' ,TimeZoneSidKey='America/los_Angeles'
                                            ,UserName='Sales.email@test.com' ,isActive=true);

    String lastName = 'Testing';
    User aSalesRep = database.query('Select ID from User where LastName=:lastName');
    //Two accounts with 'Customer' record type...
    Account testAcct1 = new Account(Name='test1' ,recordTypeID='01280000000EqShAAK');
    Account testAcct2 = new Account(Name='test2' ,recordTypeID='01280000000EqShAAK');
    //...And one with 'Other' record type.
    //This is relevant because the controller should only return 'Customer' accounts.
    Account testAcct3 = new Account(Name='test3' ,recordTypeID='012C0000000YNSzIAO');

    //Now let's insert the accounts so that the test class can access them.
        List<Account> testAccts = new List<Account> ();
        testAccts.add(testAcct1);
        testAccts.add(testAcct2);
        testAccts.add(testAcct3);
        insert testAccts;
        testAcct1.Owner=aSalesRep;
        update testAcct1;

    //Set up a list of accounts that should appear under the Sales Rep's view
    List<Account> salesAccounts = new List<Account> ();
    salesAccounts.add(testAcct1);
    //And a list that should show up in general view
    List<Account> genAccounts = new List<Account> ();
    genAccounts.add(testAcct2);

    //Start the Sales Rep test
    Test.startTest();
    system.runAs(testSalesRep){
        //This should return the Sales Rep's Accounts (testAcct1 in this case)
        System.assertEquals(testController.getAccounts(),salesAccounts);

    }
}

Relevant Controller Code:
//First let's identify the current user and their profile (which will be used to determine whether they are a regional sales rep).
    id user_profile = UserInfo.getProfileId();
    id current_user_id = UserInfo.getUserId();
    //Now let's set up numRecords which will be used in the getAccounts() method below
    public integer numRecords{get; set;}
    //pageSize will be referenced by the acctList as well as the visualforce page
    public integer pageSize{get; set;}

    /*The StandardSetController below checks to see if it contains values and runs a query (based on the conditional logic we've defined) if
     *no values are found.
     */
    public ApexPages.StandardSetController acctList {
        get{
            if (acctList == null) {

                if(user_profile == '00e80000000z1QfAAI') {
                    pageSize=20;
                    acctList = new ApexPages.StandardSetController(Database.getQueryLocator(
                    //Following is the SOQL query returned for regional sales reps
                                [
                                Select ID, Name, BillingState, BillingCountry, Region__c
                                from account
                                where OwnerId = :current_user_id
                                    and Type in ('Customer','Prospect')
                                Order by BillingState,Name
                                ]));
                    acctList.setPageSize(pageSize);
                    numRecords=acctList.getResultSize();
                }
                Else {
                    pageSize=50;
                    acctList = new ApexPages.StandardSetController(Database.getQueryLocator(
                    //Following is the SOQL query run for all users who are not regional sales reps
                                [
                                Select ID, Name, BillingState, BillingCountry, Region__c
                                from account
                                Where BillingCountry = 'USA'
                                    and Type in ('Customer','Prospect')
                                Order by BillingState, Name
                                ]));
                    acctList.setPageSize(pageSize);
                    numRecords=acctList.getResultSize();
                }
            }
            return acctList;
        }
        set;
    }

    //getAccounts method creates a new list and fills it with all of the records from acctList.  These are then returned later as our result.
    public List<account> getAccounts() {
        List<account> ListOfAccts = new List<account>();
        for(account acct: (list<account>)acctList.getrecords())
            ListOfAccts.add(acct);
        return ListOfAccts;
    }

Can you help me figure out why the controller works in production, but in test it won't ID the test sales rep and correctly fulfill the assertEquals requirement?


text:
Q: Regex to ignore matches that have a specific string in front of it I have this string stored in php:
Keyboard layout codes found here https://msdn.microsoft.com/en-us/library/cc233982.aspx test 123

test https://google.com

test google.com

Link Converted to Image

The img element was made with a prevous regex;
$url = '~(https|http)?(://)((\S)+(png|jpg|gif|jpeg))~';
$output = preg_replace($url, "Link Converted to Image", $output);

My problem is, now I want to convert the regular links to an a element.
I have this regex, which works except for one problem.
$url = '~(https|http)?(://)?((\S)+[.]+(\w*))~';
$output = preg_replace($url, "Link Converted to Image", $output);

This regex ALSO converts the link that has already become an img element, so it puts an a element in the source of the img element. My thinking on avoiding this problem is to ignore a preg match checking if the match starts with src=', but I can't figure out how to actually do this.
Am I doing this incorrectly? What is the most common/effecient way to accomplish this?

A: A good example for (*SKIP)(*FAIL):
<img.+?(*SKIP)(*FAIL) # match  tags and throw them away
|                           # or
\bhttps?\S+\b               # a link starting with http/https

In PHP:

<?php

$string = <<<DATA
Keyboard layout codes found here https://msdn.microsoft.com/en-us/library/cc233982.aspx test 123

test https://google.com

Link Converted to Image
DATA;

$regex = '~<img.+?(*SKIP)(*FAIL)|\bhttps?\S+\b~';

$string = preg_replace($regex, "$0", $string);
echo $string;
?>

A: Adding to @Jan's answer, although there may be some drawbacks with this workaround, it will match URL-like strings:
<img.+?(*SKIP)(*FAIL)|(?:https?\S+|(?:(?!:)(?(1)\S|(\w)))*\.\w{2,5})

Live demo
Breakdown:
(?:             # Open a NCG (a)
    (?!:)       # Next immediate character shouldn't be a colon `:`
    (?(1)\S     # If CG #1 exists match a non-whitespace character
    |           # otherwise
    (\w))       # Match a word character (a URL begins with a word character)
)*              # As much as possbile (this cluster denotes a tempered pattern)
\.\w{2,5}       # Match TLD

Drawbacks:

*

*TLD's character limit

*Partial match of URLs containing a port number


text:
Q: What is a happening with this enumeration In this code, I make list of days and then make an enumerate object from it. When I convert this to a list I get an expected result.
What is happening to the my_enumerate_object when I do
list(my_enumerate_object)
The second time I get an empty list? Is this garbage collection in  operation?
my_list = ["Monday",
       "Tuesday",
       "Wednesday",
       "Thursday",
       "Friday",
       "Saturday",
       "Sunday"]

my_enumerate_object = enumerate(my_list)

# I can make a list from my_enumerate_object
list(my_enumerate_object)
Out[14]:
[(0, 'Monday'),
 (1, 'Tuesday'),
 (2, 'Wednesday'),
 (3, 'Thursday'),
 (4, 'Friday'),
 (5, 'Saturday'),
 (6, 'Sunday')]

# but not again
list(my_enumerate_object)
Out[15]: []

A: Iterating through the enumeration object, as the list constructor does, consumes the enumeration object. Constructing a second list in the same way will require a new enumeration object.


text:
Q: How to change thumbnails creation way in cs-cart When cs-cart creates square thumbnails it fills empty space with some given color. How to make cs-cart crop image to create thumbnails?
 1. The way cs-cart does
 2. The way i would like to do
 1. The way cs-cart does 2. The way i would like to do
Thank you

A: 3 addons exist: [https://marketplace.cs-cart.com/autoimage-lite.html][1] [https://marketplace.cs-cart.com/product-image-uploader.html][1] [https://marketplace.cs-cart.com/cs-cart-smart-image-cropper-add-on.html][2]
If you have question, i can help you. All addons i have.


text:
Q: NativeScript Downloader plugin: Can not open zip file after downloading the file I am working on native script 8 and using ns plugin add @triniwiz/nativescript-downloader plugin to download the zip file from the server.
I get the download response
"status": "completed",
"path": "file:///data/user/0/com.myapp.example/cache/1bbf6484-9c77-4357-9759-1c1a55011a21"

but when the plugin tries to unzip the same downloaded file it gives me this
File does not exist, invalid archive path: file:///data/user/0/com.myapp.example/cache/1bbf6484-9c77-4357-9759-1c1a55011a21

I am using @nativescript/zip for unzipping the downloaded file.
unZipFile(path, unzipPath) {
        let destination = fs.path.join(this.document.path,"/assets/",unzipPath);
        return Zip.unzip({
            archive: path,
            directory: destination,
            onProgress: this.onUnZipProgress
        }).then((res) => {
               console.log(res);
                return destination;
        }).catch((err) => {
            return 'failed-----------------:'+err;
        });
    }

not sure if there is something wrong with the code or the plugin, can someone please help?

A: Check the download directory you're using. You likely should be using only the temp or documents known folders.  See the [NativeScript File System][1] docs for details.
I've seen a problem similar to this where it looks like the file downloaded successfully but in fact failed due to security restrictions.  This is especially true on iOS.
[1]: https://v7.docs.nativescript.org/ns-framework-modules/file-system


text:
Q: Angular2 Ng Date Time picker too huge when opened I am using Ng Date Time picker with Angular2 frontend from:
https://danielykpan.github.io/date-time-picker/?utm_source=recordnotfound.com
I tried to copy&paste the examples from here:
https://stackblitz.com/github/DanielYKPan/owl-examples/tree/date-time-picker?file=src%2Fmain.ts
into my component html file. I am using the ngx-admin template.
However, when I start my component and click inside the input field to open the date picker, the layout is kind of "messed up" and too huge across the window on the left side(see screenshot):

But I don't see any error in my code... heres my template:
 <label class="example-input-wrapper">
    Date Time:
    <input placeholder="Date Time:"
           [(ngModel)]="dateTime"
           [owlDateTimeTrigger]="dt" [owlDateTime]="dt">
    <owl-date-time #dt></owl-date-time>
</label>

component.ts:
public dateTime: Date;

app.module.ts:
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FlexibilitiesComponent } from './flexibilities.component';
import { ThemeModule } from '../../@theme/theme.module';
import { NgxEchartsModule } from "ngx-echarts";
import { NgxChartsModule } from '@swimlane/ngx-charts';
import { DlDateTimePickerDateModule } from 'angular-bootstrap-datetimepicker';
import { AngularDateTimePickerModule } from 'angular2-datetimepicker';
import { NguiDatetimePickerModule } from '@ngui/datetime-picker';
import { OwlDateTimeModule, OwlNativeDateTimeModule } from 'ng-pick-datetime';
import { MomentModule } from 'angular2-moment';

@NgModule({
  imports: [
    CommonModule,
    ThemeModule,
    NgxEchartsModule,
    NgxChartsModule,
    DlDateTimePickerDateModule,
    AngularDateTimePickerModule,
    NguiDatetimePickerModule,
    OwlDateTimeModule,
    OwlNativeDateTimeModule,
    MomentModule,
  ],
  declarations: [FlexibilitiesComponent]
})
export class FlexibilitiesModule { }

At stackblitz, they used more modules, but I don't know if they are app-specific or required to run the datetime picker...:
import { BasicComponent } from './basic/basic.component';
import { StandAloneComponent } from './stand-alone/stand-alone.component';
import { RangeComponent } from './range/range.component';
import { StartViewComponent } from './start-view/start-view.component';
import { ValidationComponent } from './validation/validation.component';
import { RestrictionComponent } from './restriction/restriction.component';
import { LocalizationComponent } from './localization/localization.component';
import { MomentJsComponent } from './moment-js/moment-js.component';

Any ideas how I could fix this?

A: Try this solution:
add @import "~ng-pick-datetime/assets/style/picker.min.css"; in style.scss

A: add @import "~ng-pick-datetime/assets/style/picker.min.css";
in styles.scss in src folder
if you don't have this one, you can define it in angular.json
{
  "$schema": "./node_modules/@angular/cli/lib/config/schema.json",
  "version": 1,
  "newProjectRoot": "projects",
  "projects": {
    ...
      "architect": {
        "build": {
          ...
            "styles": [
              "src/styles.scss",
              "node_modules/bootstrap/dist/css/bootstrap.min.css"
           ]}
            ...
        "test": {
          "builder": "@angular-devkit/build-angular:karma",
          "options": {
            "main": "src/test.ts",
            "polyfills": "src/polyfills.ts",
            "tsConfig": "src/tsconfig.spec.json",
            "karmaConfig": "src/karma.conf.js",
            "styles": [
              "src/styles.scss"
            ],
            ...
}


text:
Q: android issues not converting all fetched phone contacts numbers into json format I have fetched all contacts number from Android phone But not converting all phonenumbers in to json format. In some *android phone* ,it is working but in my phone Samsung Duos ,it is not working.
 It gives output like that:-
{"data":[{"phone":"+9187678965433","name":"Home"},{"phone":"+9178961042","name":"Vikash(bang)"},{"phone":"+91826543748","name":"Chandan(mota)"},{"phone":"+91867868199","name":"Amit Singh"},{"phone":"+9143228811","name":"Jimmi Sinha"},{"phone":"+91989769610","name":"Nagar(Aone)"},{"phone":"+919465436261","name":"Shahi(Biet)"},{"phone":"+917576540555","name":"Pankaj(Biet)"},"name":"P
Some of my code below:-
After it stores in bytearray first it prepares json format.while converting contacts to json format,json breaks as shown above
some of my code below:-
JSONArray postjson=new JSONArray();
          JSONObject json = null;
        Uri uri = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
        String[] projection = new String[] {ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,
                        ContactsContract.CommonDataKinds.Phone.NUMBER};

        Cursor people =getContentResolver().query(uri, projection, null, null, null);

        int indexName = people.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME);
        int indexNumber = people.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);

        people.moveToFirst();
        do {
            String name   =people.getString(indexName);
            String number =people.getString(indexNumber);
            HashMap<String,Object> NamePhoneType = new HashMap<String,Object>();
            NamePhoneType.put("name",name);
            NamePhoneType.put("mobileno",number);
            //test email
    //        NamePhoneType.put("email","asad@test.com");
            //test email ends here
            Log.d("name+---+number",name+"----"+number);
//            userarraylist.add(NamePhoneType);
            json =  new JSONObject().put("contact_no",number.trim());
            postjson.put(json);

            json.put("name",name.trim());
            postjson.put(json);
        } while (people.moveToNext());
         Log.d("json data new query",postjson.toString().trim());
          people.close();

A: Your JSON is correct. It just looks like that your logcat is truncating the output. This is due the maximum length of 4*1024 bytes.
You can increase that but its not recommend due speed and readable outputs.
Where is the error you are getting? It looks like that you have an Array called data which contains jsonobjects with phone and name.
If you cant to modify the logcat in AS go to
file-> Settings-> Editor-> Colors & Font -> Console Font


text:
Q: Create Custom Analyzer after index has been created I am trying to add a custom analyzer.
curl -XPUT 'http://localhost:9200/my_index' -d '{
    "settings" : {
        "analysis" : {
            "filter" : {
                "my_filter" : {
                    "type" : "word_delimiter",
                    "type_table": [": => ALPHA", "/ => ALPHA"]
                }
            },
            "analyzer" : {
                "my_analyzer" : {
                    "type" : "custom",
                    "tokenizer" : "whitespace",
                    "filter" : ["lowercase", "my_filter"]
                }
            }
        }
    }
}'

It works on my local environment when I can recreate the index every time I want, the problem comes when I try to do the same on other environments like qa or prod, where the index has already been created.
{
    "error": "IndexAlreadyExistsException[[my_index] already exists]",
    "status": 400
}

How can I add my custom analyzer through the HTTP API?

A: In the documentation I found that to update index settings I can do this:
curl -XPUT 'localhost:9200/my_index/_settings' -d '
{
    "index" : {
        "number_of_replicas" : 4
    }
}'

And to update analyzer settings the documentation says:
"...it is required to close the index first and open it after the changes are made."
So I ended up doing this:
curl -XPOST 'http://localhost:9200/my_index/_close'

curl -XPUT 'http://localhost:9200/my_index' -d '{
    "settings" : {
        "analysis" : {
            "filter" : {
                "my_filter" : {
                    "type" : "word_delimiter",
                    "type_table": [": => ALPHA", "/ => ALPHA"]
                }
            },
            "analyzer" : {
                "my_analyzer" : {
                    "type" : "custom",
                    "tokenizer" : "whitespace",
                    "filter" : ["lowercase", "my_filter"]
                }
            }
        }
    }
}'

curl -XPOST 'http://localhost:9200/my_index/_open'

Which fixed everything for me.

A: For folks using AWS Elastic-search service, closing and opening is not allowed, They need to follow re-indexing as mentioned here.
Basically create a temp index with all mappings of current original index and add/modify those mappings and settings(where analyzers sit), delete original index and create a new index with that name and copy back all mappings and settings from temp index.


text:
Q: Is it possible to configure a Facebook app to be used across multiple domains? We have a website application that is deployed and customised for multiple customers, across different domains, we are developing a Facebook Connect app within this website, so people can see what their friends are doing through our sites.
I've set the site url and canvas url in my Facebook app to my localhost for debugging, I was wondering, what if I wanted to use this application across multiple domains? Will facebook only allow postback to one domain per application? Is it possible to configure multiple domains?
EDIT If this isn't possible how are large companies managing multiple domains? Will it have to be setup as one domain per application or is there a way to programatically add a new application through code?
EDIT There is further discussion on this issue here

A: Unfortunately, the September 30, 2011 blog post is worded in a misleading way. The relevant section is "Support for Multiple Domains in the Developer App." Reading that paragraph, it would appear that there are no restrictions in terms of which domains can be lumped together under one application.
However, when I tried adding a second domain to an existing application, I received an error message saying that the new domain must be derived from the Site URL. One comment on that blog post described a similar experience. And that restriction was confirmed by a reply to that comment by someone in Developer Relations at Facebook, explaining that "All app domains must be derived from the site URL."
I believe the confusion arises from incorrect wording in the post itself, which says "Your App's URL (Website and/or Mobile Web URL) must be derived from one of the domains listed in the App Domain field."
*Update: Just to clarify what types of domains are allowed, let's say your Site URL is "mywebsite.com". You would be allowed to add "mywebsite.co.uk" as an additional App Domain, but you would not be allowed to add "myalternatewebsite.com".

A: I got a partial solution for this! Using this you can add one more domain that is you can have two different domains(independent of each other).
On the Basic settings tab, look for Mobile web url.
Add a url of your app on different domain and then  try adding this domain in App Domains.
Hope it helps(little bit).


text:
Q: simple update from Cant figure this simple sql out.  crm_contact_id is updated with the same contact id throughout the table.  I'm trying to get it to equal what the from query equals when I do the select.
update events set crm_contact_id = c.id
from events as evts
inner join crm2.crm_retail_lead l on l.lead_number = evts.old_lead_number
inner join crm_contacts c on c.old_contact_id = l.contact_id

Thanks for taking a look.

A: When you do:
UPDATE events... FROM events as evts JOIN [other tables]

you get two unrelated instances of the events table.
That's probably not what you want. A fixed version would look like this:
update events evts set crm_contact_id = c.id
from crm2.crm_retail_lead l
inner join crm_contacts c on c.old_contact_id = l.contact_id
where l.lead_number = evts.old_lead_number

A: You have not placed any WHERE clause in query.....Make query with where clause
update events set crm_contact_id = c.id
from events as evts
inner join crm2.crm_retail_lead l on l.lead_number = evts.old_lead_number
inner join crm_contacts c on c.old_contact_id = l.contact_id
WHERE column_name='value'


text:
Q: Shapefile not loading all points in ArcGIS .net I am trying to load a shapefile into my WPF .Net framework application. I can load the file successfully however it only shows a few points of the shapefile.
For testing I loaded the same shapefile to QGIS and I get the same results from QGIS, same points. It is interesting because if I load the .zip file into QGIS I get all the points in the file.
Essentially I am trying to load this shapefile with all points into my WPF application using ArcGIS runtime WPF.
What am I doing wrong here?
       {
           InitializeComponent();
           MapPoint mapCenterPoint = new MapPoint(-118.805, 34.027, SpatialReferences.Wgs84);
           MainMapView.SetViewpoint(new Viewpoint(mapCenterPoint, 100000));
           Initialize();

       }

   private async void Initialize()
   {
           // Create a new map to display in the map view with a streets basemap
           MainMapView.Map = new Map(BasemapStyle.ArcGISStreets);

           // Get the path to the downloaded shapefile
           string filepath = @"Airports\airports.shp";

       try
       {
           // Open the shapefile
           ShapefileFeatureTable myShapefile = await ShapefileFeatureTable.OpenAsync(filepath);

           // Create a feature layer to display the shapefile
           FeatureLayer newFeatureLayer = new FeatureLayer(myShapefile);

               // Add the feature layer to the map
               MainMapView.Map.OperationalLayers.Add(newFeatureLayer);

           // Zoom the map to the extent of the shapefile
           await MainMapView.SetViewpointGeometryAsync(newFeatureLayer.FullExtent, 50);
       }
       catch (Exception e)
       {
           MessageBox.Show(e.ToString(), "Error");
       }
   }

   }
}


text:
Q: An exception occurred while executing 'UPDATE... ': Integrity constraint violation: 1062 Duplicate entry '' for key 'PRIMARY' DefaultFormHandler.php
  protected function onSuccess($object)
    {
            $artistmember= new ArtistMember();
            $artistmember->setMemberId($object->getManager()->getId());
            $artistmember->setArtistId($object->getId());
            $this->em->merge($artistmember);
            $this->em->flush();
            return $object;
     }

ArtistMember
/**
 * @ORM\Entity
 * @ORM\Table(name="artist_member")
 */
class ArtistMember
{

    /**
     * @ORM\Id
     * @ORM\Column(name="artist_id", type="integer")
     */
    private $artist_id;
    /**
     * @ORM\Column(name="member_id", type="integer")
     */
    private $member_id;

    /**
     * @param mixed $artist_id
     */
    public function setArtistId($artist_id)
    {
        $this->artist_id = $artist_id;
    }
    /**
     * @param mixed $member_id
     */
    public function setMemberId($member_id)
    {
        $this->member_id = $member_id;
    }

}

entity artist get manager()
/**
     * Set manager
     *
     * @param Member $manager
     */
    public function setManager($manager)
    {
        $this->manager = $manager;

        if ( ! $this->members->contains( $manager) ) {
            $this->members->add( $manager );
        }
    }

    /**
     * Get manager
     *
     * @return \MainBundle\Entity\Member
     */
    public function getManager()
    {
        return $this->manager;
    }

I have 2 tables: Artist table  and member table
In artist table I have the id and manager_id and in member table I have member_id and artist_id.
Update query works fine if the member table contains only one artist_id and member_id.
Eg: artist-id=1,manager_id =10.
But I get the above error if I try to update any of the manager id in this case:
eg: artist_id=1
    member_id=10
    artist_id=1
    member_id =20

If I try to update the member id 20 to 30 or 10 to 30 I am getting the error.
The issue is resolved with this solution: But still is there a better way to do it?Also is it possible to check whether the artist_id and member_id are already existing in artist_member table.

A: The error is self explanatory:

An exception occurred while executing 'UPDATE… ': Integrity constraint violation: 1062 Duplicate entry '' for key 'PRIMARY'

The issue is when you try to update the manager id 20 to 30 or 10 to 30, the new value you are trying to update are already present in the column.


text:
Q: Mini-ITX Case that would take ~6 SATA Hard Drives Thinking about maybe building my own NAS. I would go with Raid 5, and would like maybe about 6 SATA drives:

*

*There a mini atx case that can hold this many drives (Non-Rack ideally)

*What sort of power will I need?

*Any way this won't be pretty loud?

A: Have you seen Lian Li's PC-Q08?

A: I doubt it's what you're looking for, but most Mini-ITX boards will fit in a standard ATX case.
Most HD's pull around 10w+ each, so an normal Mini-ITX powersupply probably isn't going to cut it.

A: Even through some time has passed and you most likely already have a case I would recommend a Fractal Design Array R2 which I use for my Network Storage. It takes up to 6 3.5" devices and 1 2.5" device and just looks awesome.

A: If you can do with 4:  Chenbro ES34069.  I've never seen a mini-ITX chassis hold more than 4.
Edit:  I stand corrected.  The Fractal case in the comment above looks awesome.

A: If you are using picoPSU or similar, I recommend using low-power drives. Their performance is within striking distance from their 7200rpm counterparts, and their noise levels and power requirements are more modest. If you look at [table on this article], you can easily find LP drives that take 6.5W or less when seeking, compared to around 10W of 7200rpm drives.


text:
Q: How to iterate rows with known start position and mixed column ordering, exactly as if walking the corresponding index? I have a given, unmodifiable table design which resembles:
create table t (
   c1  varchar(64) not null,
   c2  bigint not null
   -- some more columns which are not relevant here
);
-- The primary key, intentionally not (also) modeled as a constraint.
create unique index on t(c1 asc, c2 desc);

I simply want to iterate rows from this table in the order c1 asc, c2 desc, starting at a known position, e.g., ('foo', 5). The query must be efficient, i.e. the query planner must be able to take advantage of the unique index and do an index scan if the table is large enough. This should require at most log(n) + 2 * limit reads for large tables.
Examples (fixed after edit):
- Given t contains ('a', 1), ('a', 2),
                   ('b', 1), ('b', 3),
                   ('c', 2), ('c', 17)

- When we query for ('', <any>)
- Then we get t

- When we query for ('a', 2)
- Then we get ('a', 1), ('b', 3), ('b', 1), ('c', 17), ('c', 2)

- When we query for ('b', 1)
- Then we get ('c', 17), ('c', 2)

- When we query for ('c', 3)
- Then we get ('c', 2)

- When we query for ('q', <any>)
- Then we get the empty set

You'd think something like this should be trivial, but apparently with SQL this is harder than it should be!? Consider the
following incorrect (!) queries which I'm only listing to avoid getting them as an answer ;)
-- Incorrect: Ordering of row expression is inconsistent with ORDER BY clause.
select * from t where (t.c1, t.c2) > ('foo', 5) order by t.c1 asc, t.c2 desc limit 1000;

-- Incorrect: Ignores coupling between c2 and c1, skips rows that must be included.
select * from t where t.c1 > 'foo' and t.c2 > 5 order by t.c1 asc, t.c2 desc limit 1000;

A: One hacky solution would switch the sign of the second column:
create unique index on t(c1 asc, (- c2) asc);

Then you can use:
select *
from t
where (t.c1, (- t.c2)) > ('foo', -5)
order by t.c1 asc, (- t.c2) asc
limit 1000;

A: I suspect that the trickiest part will stopping it from using the index. Which is to say just walking the index from one end discarding stuff that doesn't match the filter.
SELECT * FROM t1 WHERE (c1 = 'CXB' AND c2 <= 57) OR c1 > 'CXB'
ORDER BY c1 ASC, c2 DESC LIMIT 999;

The planner isn't smart enough (afaict in 2021) to spot that the OR there has a strong correlation on each side. We know that we are actually just trying to get a subset of the table, but the planner - nope.
So - one thing you can do with a tricky OR is to split it into two subqueries and use UNION ALL.
WITH part1 AS (
  SELECT * FROM t1 WHERE (c1 = 'CXB' AND c2 <= 57)
  ORDER BY c1 ASC, c2 DESC LIMIT 999
), part2 AS (
  SELECT * FROM t1 WHERE c1 > 'CXB'
  ORDER BY c1 ASC, c2 DESC LIMIT 999
)
SELECT * FROM part1
UNION ALL
SELECT * FROM part2
ORDER BY c1 ASC, c2 DESC LIMIT 999;

I've written this as a CTE (the WITH clauses) because I think it looks more readable that way. It should be identical to actual subqueries for the planner though.
That gives me (EXPLAIN ANALYSE ...) a plan something like:
 Limit  (cost=110.23..177.47 rows=999 width=16) (actual time=0.232..2.172 rows=999 loops=1)
   ->  Merge Append  (cost=110.23..181.31 rows=1056 width=16) (actual time=0.230..1.872 rows=999 loops=1)
         Sort Key: t1.c1, t1.c2 DESC
         ->  Sort  (cost=109.80..109.94 rows=57 width=16) (actual time=0.141..0.155 rows=57 loops=1)
               Sort Key: t1.c1, t1.c2 DESC
               Sort Method: quicksort  Memory: 29kB
               ->  Limit  (cost=0.42..107.56 rows=57 width=16) (actual time=0.055..0.104 rows=57 loops=1)
                     ->  Index Scan using t1u1 on t1  (cost=0.42..107.56 rows=57 width=16) (actual time=0.055..0.085 rows=57 loops=1)
                           Index Cond: (((c1)::text = 'CXB'::text) AND (c2 <= 57))
         ->  Limit  (cost=0.42..50.81 rows=999 width=16) (actual time=0.085..1.403 rows=942 loops=1)
               ->  Index Scan using t1u1 on t1 t1_1  (cost=0.42..40347.24 rows=799950 width=16) (actual time=0.085..1.143 rows=942 loops=1)
                     Index Cond: ((c1)::text > 'CXB'::text)
 Planning Time: 0.677 ms
 Execution Time: 2.387 ms

You incur an extra sort I'm afraid, but you can't guarantee your ordering otherwise.
Obviously this doesn't give your your odd queries that should be returning true or an empty set. That's because they don't really make any sense in the sense of asking for a subset of the table.
Test data used for above query plan:
CREATE FUNCTION threechars(i int) RETURNS TEXT AS $$ SELECT chr((i / (26*26)) % 26 + 65) || chr((i / 26) % 26 + 65) || chr(i % 26 + 65) $$ LANGUAGE sql IMMUTABLE ;

CREATE TABLE t1 (c1 varchar(64) not null, c2 bigint not null, i int not null);

CREATE UNIQUE INDEX t1u1 ON t1 (c1 ASC, c2 DESC);

INSERT INTO t1 SELECT threechars(i / 99), 99 - (i % 99), i FROM generate_series(0, 999999) i;

ANALYSE t1;


text:
Q: Is there a nice characterization of those posets in which $\vartriangle_P$ is transitive? Whenever $P$ is a poset and $x,y$ are elements of $P$, write $x \vartriangle y$ to mean that $x$ and $y$ have a lower bound. Then $\vartriangle_P$ is always reflexive and symmetric, but it may or may not be transitive.
Transitivity does not hold.
Let $X = \{0,1,2,3\}$. Let $P$ denote the poset of all non-empty subsets of $X$. Then $\vartriangle_P$ is not transitive; since letting $x,y$ and $z$ denote $\{0,1\},\{1,2\}$ and $\{2,3\}$ respectively, we have that $x \vartriangle y$ and $y \vartriangle z,$ but $\neg(x \vartriangle z).$
Transitivity holds.
Let $X$ and $Y$ denote sets, and write $P$ for the poset of all partial functions $X \rightarrow Y$ defined at all but finitely many elements of $X$. Then $\vartriangle_P$ is transitive.

Question. Is there a nice characterization, not mentioning $\vartriangle_P$, of those posets in which $\vartriangle_P$ is transitive?

A: The connected posets where $\vartriangle_P$ is transitive are exactly those where every two elements have a lower bound. So in general a poset has transitive $\vartriangle_P$ exactly if it is the disjoint (i.e. non-related) union of components where in each component every two elements have a lower bound.
It is difficult to see how one could say that without somehow using the notion of elements having a common lower bound.
An example of an order that has this property without (apparently) being "nice" in any other way would be $\mathbb Z\times\mathbb Z$ with the ordering
$$(a,p)\sqsubseteq (b,q) \quad\iff\quad b-a \ge |q-p|$$
Note that this doesn't have greatest lower bounds for all pairs, and there are infinite antichains with no lower bounds at all.


text:
Q: How to change SVG icon in bottom nav bar in Flutter? I am trying to change my SVG icon color when being tapped. I have tried the selectedColor but the icon did not change the color. So I am trying to use shortcut if...else statement but I still did not got to change the color.
Here is the code:
bottomNavigationBar: BottomNavigationBar(
        type: BottomNavigationBarType.fixed,
        items: <BottomNavigationBarItem>[
          BottomNavigationBarItem(
              icon: SvgPicture.asset('assets/dashboard-outline.svg', width: 25),
              label: 'Dashboard'
          ),
          BottomNavigationBarItem(
            icon: SvgPicture.asset('assets/tank-outline.svg', color: Colors.black54, width: 30),
            label: 'Tanks',
          ),
          BottomNavigationBarItem(
              icon: SvgPicture.asset('assets/activity-outline.svg', width: 18),
              label: 'Activity'
          ),
          BottomNavigationBarItem(
              icon: SvgPicture.asset('assets/account-outline.svg', width: 20),
              label: 'Account'
          ),
        ],
        currentIndex: _index,
        onTap: _onItemTapped,
        selectedItemColor: Color.fromRGBO(0,99,183,1)
      ),

I have a different file for SVG picture icon to change it when being tapped.
Here is the code that i was trying:
bool onSelected = true;

  Widget build(BuildContext context) {
    return Scaffold(
      body: _myPages[_index],

      bottomNavigationBar: BottomNavigationBar(
        type: BottomNavigationBarType.fixed,
        items: <BottomNavigationBarItem>[
          BottomNavigationBarItem(
              icon: SvgPicture.asset(onSelected == false ? 'assets/dashboard-outline.svg' : 'assets/dashboard-fill.svg', width: 25),
              label: 'Dashboard'
          ),

Any help would be appreciated.

A: You can just change your items do validate this property to define the correct color:
 SvgPicture.asset(
 'assets/dashboard-outline.svg',
  width: 25),
  color: _currentIndex == 0 ? Colors.red : Colors.black,


text:
Q: Creating a graphic inside another one using and linking them by lines I would like to link a graphic with a another one, both in the same figure, and "connect" the smaller one with the larger one, due to they share X axis, but not Y axis. The problem comes when I use that function, that I really don't know very well how it works.
The function ax2.set_axes_locator(ip) calls another one ip=InsetPosition(ax1,[0.2,0.7,0.5,0.25]), where ax1 represents the bigger graphic. The problem is that function automatically generates lines which links the bigger one with the smaller, but I can't redirect them and I want to, because both graphics don't share Y axis.
I hope someone could understand the problem, definitely my english is not the best.

ax2=plt.axes([0,0,1,1])
ip=InsetPosition(ax1,[0.2,0.7,0.5,0.25])
ax2.set_axes_locator(ip)
mark_inset(ax1,ax2,loc1=3,loc2=4,fc="none",ec='0.5')

A: You cannot use mark_inset because that will show the marker at the same data coordinates as the view limits of the inset axes.
Instead you can create a rectangle and two connectors that will just be positionned arbitrarily on the axes. (The following code will require matplotlib 3.1 or higher)
import matplotlib.pyplot as plt
from  matplotlib.patches import ConnectionPatch

fig, ax = plt.subplots()
ax.plot([1,3,5], [2,4,1])
ax.set_ylim([0, 10])
ax.set_ylabel("Some units")

axins = ax.inset_axes([.2, .7, .4, .25])
axins.plot([100, 200], [5456, 4650])
axins.set_ylabel("Other units")

rect = [2.1, 2.6, 1, 2]
kw = dict(linestyle="--", facecolor="none", edgecolor="k", linewidth=0.8)
ax.add_patch(plt.Rectangle(rect[:2], *rect[2:], **kw))
cp1 = ConnectionPatch((rect[0], rect[1]+rect[3]), (0,0), coordsA="data", axesA=ax,
                      coordsB="axes fraction", axesB=axins, clip_on=False, **kw)
cp2 = ConnectionPatch((rect[0]+rect[2], rect[1]+rect[3]), (1,0), coordsA="data", axesA=ax,
                      coordsB="axes fraction", axesB=axins, clip_on=False, **kw)
ax.add_patch(cp1)
ax.add_patch(cp2)
plt.show()


text:
Q: How would I go about getting frequency of a sound source in Java? I pretty much have no idea how I would go about doing this- I need to find the frequency of a played sine wave at a specific point in time.
I've been doing some research and see that it involves a Fourier transform. I've found a DFT class but am not really sure how to use it.
My questions are these:
How do I save a sound file from a mic at a specific point in time?
What format will this be saved in?
From this, how would I go about using an FFT/DFT to find the frequencies in that sample?
I don't really have a clear understanding of the mathematics behind the FFT (and yes, I've tried to understand it), so am not really sure what outputs/inputs represent.
Alternatively if there are any libraries that support this type of thing, a link would be much appreciated.
Thanks in advance


text:
Q: Convert 2-D matrix into Dataframe in python a = np.array([[5, 6, 7, 8],[5, 6, 7, 8]])

df = pd.DataFrame(a, columns=['a'])

ValueError: Shape of passed values is (2, 4), indices imply (2, 1)
I hope that the final result is:
a
-----------
[5, 6, 7, 8]
[5, 6, 7, 8]

Edit:
    df = pd.DataFrame({"a": [a]})

    a
----------------------------------
0   [[5, 6, 7, 8], [5, 6, 7, 8]]

why?

A: According to https://stackoverflow.com/a/18646275/5405298, you have to turn the array into a list. In your case, you can use
import pandas as pd
import numpy as np

a = np.array([[5, 6, 7, 8], [5, 6, 7, 8]])
df = pd.DataFrame({"a": a.tolist()})
print(df)

this returns:
              a
---------------
0  [5, 6, 7, 8]
1  [5, 6, 7, 8]

A: Convert each sub-array to string, you will have what you want.
>>>a = np.array([[5, 6, 7, 8],[5, 6, 7, 8]])
>>>df = pd.DataFrame([",".join([str(i) for i in j]) for j in a], columns=['a'])
>>>df
         a
0  5,6,7,8
1  5,6,7,8


text:
Q: Microsoft Dynamics Error: Developing SSRS report using Report Data Provider I am trying to create a class coding in AOT in my Microsoft Dynamics AX. What I am doing is to develop a SSRS report in Microsoft DynamicsAX 2012. Hence, for practice purposes I am actually following through this tutorial link: http://www.dynamics101.com/2013/09/developing-ssrs-report-using-report-data-provider-microsoft-dynamics-ax-2012/. Please Help. THank you
However, I am getting a syntax error that says:

Syntax error
  \Classes\CustReportRDPDemoDP\classDeclaration
  classDeclaration
  Err:9999

The error occurs at this code line:

[SRSReportDataSetAttribute(tablestr('CustReportRDPDemoTmp'))]

My following code is as follows:
class CustReportRDPDemoDP extends SRSReportDataProviderBase
{
//Temproaray table buffer
CustReportRDPDemoTmp custReportRDPDemoTmp;

[SRSReportDataSetAttribute(tablestr('CustReportRDPDemoTmp'))]

public CustReportRDPDemoTmp getCustReportRDPDemoTmp()
{

    select * from custReportRDPDemoTmp;
    //return the buffer
    return custReportRDPDemoTmp;
}

///<summary>
/// Processes the SQL Server Reporting Services report business logic
/// </summary>
/// <remarks>
/// This method provides the ability to write the report business   logic. This method will be called by
/// SSRS at runtime. The method should compute data and populate the data tables that will be returned
/// to SSRS.
/// </remarks>
public void processReport(){
    CustTable custTable;
    SalesTable salesTable;

    //select all customers
    while select * from custTable
    {
        //clear the temporary table
        custReportRDPDemoTmp.clear();
        //assign customer account and name
        custReportRDPDemoTmp.CustAccount = custTable.AccountNum;
        custReportRDPDemoTmp.Name = custTable.name();
        //select count of invoiced sales order of customer
        select count(RecId) from salesTable
        where salesTable.CustAccount == custTable.AccountNum
        && salesTable.SalesStatus == SalesStatus::Invoiced;
        custReportRDPDemoTmp.SalesOrderInvoiceCount = int642int(salesTable.RecId);
        //insert in temporary table buffer
        custReportRDPDemoTmp.insert();
       }
 }
}

A: You need to have 3 separate methods, you can't just throw the code in the classDeclaration method.
The classDeclaration should just be:
class CustReportRDPDemoDP extends SRSReportDataProviderBase
{
    //Temporary table buffer
    CustReportRDPDemoTmp custReportRDPDemoTmp;
}

and the two other code blocks should be their own methods.


text:
Q: How can I display these from my arraylist? This is my main class.
I am basing it off another example i had done before and it works jsut fine the same way, this is my first time using an arraylist so maybe it's something to do with that I'm not sure. I just need it to display and the arraylist to work properly I think everything else works fine.
Right now I am getting an error on:
Console.WriteLine("{0,-12} {1,-12} {2,-12} {3,-12} {4,-12} {5,-12} {6,-12}",
    plan[idx].GetCardNumber(), plan[idx].GetCreditBalance(), plan[idx].GetMonthlyPayment(),
    plan[idx].GetAnnualRate(), plan[idx].MonthsToPayOff(), plan[idx].TotalPayment(),
    plan[idx].CompanyProfit());

saying that:

'object' does not contain a definition for ___ eg( .getcreditbalance

full program:
using System;
using System.Collections.Generic;
using System.Collections;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Configuration;

namespace Assignment1
{
    class Program
    {
        static void Main(string[] args)
        {
            ArrayList plan = new ArrayList();
            int count = 0;
            char option;

            Console.WriteLine("--= Credit Card Calculator =-- ");
            Console.WriteLine();

            do
            {
                option = ReadMenuOption();
                switch (option)
                {
                    case 'E':
                        count = count + 1;
                        AddPaymentPlan(count, plan);

                        break;
                    case 'V':
                        Display(count, plan);
                        break;
                    case 'X':
                        Console.WriteLine("Goodybye.");
                        break;
                    default:
                        Console.WriteLine("Invalid option.");
                        break;
                }

            } while (option != 'X');
        }

        static char ReadMenuOption()
        {
            char option;

            Console.WriteLine("Options Menu");
            Console.WriteLine("====================");
            Console.WriteLine("E - Enter calculation information");
            Console.WriteLine("V - View calculation report");
            Console.WriteLine("X - Exit");
            option = Console.ReadLine().ToUpper()[0];

            return option;
        }

        static void Display(int count, ArrayList plan)
        {
            if (count == 0)
            {
                Console.WriteLine("There are no values to show!");
            }
            else
            {
                for (int idx = 0; idx < plan.Count; idx = idx + 1)
                {

                    Console.WriteLine("{0,-12}  {1,-12}  {2,-12}  {3,-12}  {4,-12}  {5,12}  {6,-12}", " Card Number", "Card Balance", "Monthly Payment", "APR", "Months to Pay", "Total Payment", "Company Profit");

                    Console.WriteLine("{0,-12}   {1,-12}  {2,-12}   {3,-12}   {4,-12}   {5,-12}   {6,-12}", plan[idx].GetCardNumber(), plan[idx].GetCreditBalance(), plan[idx].GetMonthlyPayment(), plan[idx].GetAnnualRate(), plan[idx].MonthsToPayOff(), plan[idx].TotalPayment(), plan[idx].CompanyProfit());
                }

            }
        }

        static int AddPaymentPlan(int count, ArrayList plan)

        {
            PaymentPlan p = new PaymentPlan();

                do
                {
                    try
                    {
                        Console.Write("Enter card number: ");
                        p.SetCardNumber(long.Parse(Console.ReadLine()));

                    }
                    catch
                    {
                        Console.WriteLine("Invalid card number");
                    }
                } while (p.GetCardNumber().Equals(""));

                do
                {
                    try
                    {
                        Console.Write("Enter card balance: ");
                        p.SetCreditBalance(double.Parse(Console.ReadLine()));

                    }
                    catch
                    {
                        Console.WriteLine("Invalid card balance.");
                    }
                } while (p.GetCreditBalance().Equals(""));

                do
                {
                    try
                    {
                        Console.Write("Enter payment amount: ");
                        p.SetMonthlyPayment(double.Parse(Console.ReadLine()));

                    }
                    catch
                    {
                        Console.WriteLine("Invalid payment amount.");
                    }
                } while (p.GetMonthlyPayment().Equals(""));

                do
                {
                    try
                    {
                        Console.Write("Enter annual rate: ");
                        p.SetAnnualRate(double.Parse(Console.ReadLine()));

                    }
                    catch
                    {
                        Console.WriteLine("Invalid");
                    }
                } while (p.GetAnnualRate().Equals(""));

                plan.Add(p);

                Console.WriteLine("It will take {0} months to pay off your credit card", p.MonthsToPayOff());
                Console.WriteLine();

            count = count + 1;
            return count;

        }
    }
}

and my Payment plan class :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Assignment1
{
    class PaymentPlan
    {
        private long _cardNumber;
        private double _creditBalance;
        private double _monthlyPayment;
        private double _annualRate;

        public PaymentPlan()
        {
            _cardNumber = 0;
            _creditBalance = 0;
            _monthlyPayment = 0;
            _annualRate = 0;
        }

        public PaymentPlan(long cardNumber, double creditBalance, double monthlyPayment, double annualRate)
        {
            SetCardNumber(cardNumber);
            SetCreditBalance(creditBalance);
            SetMonthlyPayment(monthlyPayment);
            SetAnnualRate(annualRate);
        }

        public long GetCardNumber()
        {
            return _cardNumber;
        }

        public void SetCardNumber(long cardNumber)
        {
            if (cardNumber < 0)
            {
                throw new Exception("Has to be a positive number");
            }
            _cardNumber = cardNumber;
        }

        public double GetCreditBalance()
        {
            return _creditBalance;
        }

        public void SetCreditBalance(double creditBalance)
        {
            if (creditBalance < 0)
            {
                throw new Exception("Has to be a positive number");
            }
            _creditBalance = creditBalance;
        }

        public double GetMonthlyPayment()
        {
            return _monthlyPayment;
        }

        public void SetMonthlyPayment(double monthlyPayment)
        {
            if (monthlyPayment < 0)
            {
                throw new Exception("Has to be a positive number");
            }
            _monthlyPayment = monthlyPayment;
        }
        public double GetAnnualRate()
        {
            return _annualRate;
        }

        public void SetAnnualRate(double annualRate)
        {
            if (annualRate < 0 || annualRate > 1)
            {
                throw new Exception("Has to be a positive number between 0.0 & 1.0");
            }
            _annualRate = annualRate;
        }

        public double MonthsToPayOff()
        {
            double months;
            double daily;
            double monthly;
            double tinycalc;
            double innerbrac;
            double bottom;
            double upperbrac;

            daily = _annualRate / 365;

            //calculates number of months to be returned to main and displayed for user
            monthly = _creditBalance / _monthlyPayment;
            tinycalc = -1.0 / 30;
            innerbrac = Math.Pow(1 + daily, 30);
            bottom = Math.Log(1 + daily);
            upperbrac = Math.Log(1 + (_monthlyPayment * (1 - innerbrac)));

            months = Math.Round(tinycalc * (upperbrac / bottom));

            return months;
        }

        public double TotalPayment()
        {
            return GetCreditBalance() * (MonthsToPayOff() * GetMonthlyPayment());
        }

        public double CompanyProfit()
        {

            return TotalPayment() - _creditBalance;
        }

    }
}

A: An ArrayList is an outdated way of storing a collection.
Every item is stored as an object, and until you cast the item back to the original type, you can't access any properties or methods on the original type.
((PaymentPlan)plan[idx]).GetCardNumber()

Better yet, replace the ArrayList with a List<PaymentPlan>. The List<T> construct is type-safe, so you don't have to recall the original type and cast items each time you want to access use them.
var plans = new List<PaymentPlan>();
plans.Add(new PaymentPlan(12345, ...));
Console.WriteLine(plans[idx].GetCardNumber());


text: Q: parse docx and pdf in hdfs I want to parse/extract content stored in pdf and docx files which are stored in hdfs. The python libraries available (like docx2txt, pdfminer) are not working in the hdfs. These files are giving a binary output if I try to read with the native hdfs libraries.  Are there any python libraries which can do such task? Or a way in which we can convert the binary files to extract the data.


text:
Q: Restricting (Age-Protecting) a UIWebView to avoid 17+ user rating Recent policy changes with iTunes Connect mean that any application which gives "unrestricted" access to the internet (via UIWebView) must have a 17+ rating.
I have such a feature in my app, but it is a very non-critical feature. Rather than removing it all together, I wondered if there is a way to have an age protection around these features to avoid needing the 17+ rating.
For example: could I require Facebook login and check the user's age?
Has anybody had success with techniques like this?

A: I've had to use UIWebView in an app before and the best way around it is to restrict it to what it can do. Do you need to give the users wide access to the web or just your site? I simply made a little 10 minute mobile port and mapped it so there was no external site access.
I doubt a Facebook login would satisfy Apple but unrestricted means giving the UIWebView full access to the web by putting in a URL bar or a search box to Google.


text:
Q: Cómo hacer para mandar un mail con copia oculta desde PHP Bueno, mi problema es que estoy usando un PHP de un template que compré para hacer un formulario, pero no logro descifrar cómo modificarlo para que cuando el usuario envíe su consulta, no solo le llegue al mail recipiente, sino que se envíe una copia a otros correos.
Les dejo el PHP que estoy usando
Desde ya, muchas gracias!
<?php

$to = 'hello@misito.com';

$name = $_POST['name'];
$tel = $_POST['tel'];
$subject = $_POST['subject'];
$email = $_POST['email'];
$message = $_POST['message'];

// Email Submit
// Note: filter_var() requires PHP >= 5.2.0
if ( isset($email) && isset($name) && isset($tel) && isset($subject)
&& isset($message) && filter_var($email, FILTER_VALIDATE_EMAIL) ) {

 // detect & prevent header injections
$test = "/(content-type|bcc:|cc:|to:)/i";
foreach ( $_POST as $key => $val ) {
if ( preg_match( $test, $val ) ) {
  exit;
}
}

$body = <<<EMAIL
ASUNTO : $subject

HOLA MI NOMBRE ES, $name.

$message

DE : $name
TEL : $tel
MAIL : $email

EMAIL;

$header = 'From: ' . $_POST["name"] . '<' . $_POST["email"] . '>' . "\r\n" .
'Reply-To: ' . $_POST["email"] . "\r\n" .
'X-Mailer: PHP/' . phpversion();

//
 // mail( $to , $_POST['subject'], $_POST['message'], $headers );
 mail($to, $subject, $body, $header);
  //      ^
  //  Replace with your email
}?>

A: En la parte de $header que tienes, debes agregarle el CC/BCC, siguiendo tu código:
$header = 'From: ' . $_POST["name"] . '<' . $_POST["email"] . '>' . "\r\n" .
'Reply-To: ' . $_POST["email"] . "\r\n" .
'Cc: tumail@dominio.com' . "\r\n" .  // esto sería copia normal
'Bcc: tumail@dominio.com' . "\r\n" . // esto sería copia oculta
'X-Mailer: PHP/' . phpversion();

Aquí tienes el manual de la función mail y su uso (en el Ejemplo #4 verías lo que necesitas). Igualmente te recomiendo utilizar PHPMailer si vas a trabajar más con correos.

A: Agrega a los headers:
Bcc: email_de_copia.
En este caso:
$header = 'From: ' . $_POST["name"] . '<' . $_POST["email"] . '>' . "\r\n" .
'Reply-To: ' . $_POST["email"] . "\r\n" .'Bcc: ' . $_POST["otro_email"] . "\r\n" .
'X-Mailer: PHP/' . phpversion();

A: Agrega esto
$headers .= "Bcc: $email_copia\r\n";


text:
Q: Drupal 7 force active menu item I got a page where I link to in the menu bar. On this page there is a custom module. On this page there are items from anothor database where the user can click on. When they click on it they go to another page with more information.
When they are on the second page there is no active button in the menu bar. On the second page I also have a custom module.
How can u force a button in the menu bar to have the .active class or in another way so that it haves the active lay-out button.
I use Drupal 7.

A: I used the context module to solve this.


text:
Q: Finding highest reached threshold I have a table that contains 2 columns that store values of certain thresholds that can be reached.
The table columns are: ThresholdValue (INT), Reached (BIT) and the table looks like this:
ThresholdValue | Reached
------------------------
10000          | 0
20000          | 0
30000          | 0
45000          | 0
50000          | 0

I need to update the reached column according to the reached threshold.
For example, when the reached value is 25000 I want the second row to be set to 1 so it looks like this
ThresholdValue | Reached
------------------------
10000          | 0
20000          | 1
30000          | 0
45000          | 0
50000          | 0

What is the easiest way to solve this problem?
Any tips will be strongly appreciated

A: You can use a subquery to identify the row:
update t
    set reached = 1
    from (select top (1) t.*
          from t
          where t.ThresholdValue <= 25000
          order by ThresholdValue desc
         ) t;

Another approach would look at the next value:
update t
    set reached = 1
    from (select t.*, lead(ThresholdValue) over (order by ThresholdValue) as next_tv
          from t
         ) t
     where t.ThresholdValue <= 25000 and
           (t.next_tv > 25000 or t.next_tv is null);


text:
Q: How to get hellstone quickly? I was playing Terraria on iOS and I accidentally deleted a world and lost all my hellstone ingots. Is there a way to get easy hellstone because I already have obsidian, but the time consuming task of collecting it is driving me insane!

A: Craft a lot of Obsidian Skin Potions and go ahead! You need fireblossom, waterleaf, obsidian and water bottle to craft them.They work 4 mins and each one can get you some stacks of hellstone. Hope this help you.

A: Make an inside an obsidian head and equip it. It will let you be immune to fire blocks. Then just find a safe place to mine the hellstone because once you mine it, it will let out lava. An easy way is to mine over it with something in between you and the he llstone then mine it. I got 93 hellstone doing that.

A: Did you know how you can pick up blocks if they're close even though they're behind walls or platforms? Put that advantage to good use. Separate yourself between the Hellstone with Ashblocks around it. Also, get a Imp Staff after you get enough Hellstone so it can guard you while you mine the other Hellstones. You could try to dig a "drain" to dump the lava out so you can safely get the Hellstone blocks if you want. Get a friend to help you out. You may have to share(or not if they're OP) the loot but it makes things go faster.

A: I suggest using a lava charm try making some storage for your hellstone by putting stacks in a chest oh and don't forget obsidian skull and obsidian sheild could be useful. I got unlimited bars from this


text:
Q: no operator << found which takes a right-hand operand of type class Foo despite having one defined [solved] I had some bragging here that was inaccurate, the problem is related to compilation.
My code is:
#include <iostream>
using namespace std;

struct Circle {
    void write(ostream& os) const {
        os<<*this;
    }
};

ostream& operator<<(ostream& os, const Circle& rhs_c) {
    os<<"circle";
    return os;
}

int main() {
    Circle c1;
    c1.write(cout);
    return 0;
}

I get the following error:
C2679 binary'<<': no operator found which takes a right-hand operand of type 'Circle' (or there is no acceptible conversion)

Whereas if the global operator<< actually has something that doesn't match the operands I get:
no operator "<<" matches these operands

I have reasons for having such a twisted print function that may break knowing why the upper code is wrong.

A: When you do:
os<<*this;

the operator overloading hasn't happened yet, and to exact, the compiler is not informed that it will happen later in that code.
Forward declare a prototype of the operator's overloading, which says to the compiler that you, the programmer, promises to provide a definition for this overloading.
Then the compiler will know what to do when it meets this line (os<<*this;).
But it wouldn't know what Circle is, right? So you need to also forward declare the class' declaration too.

Moreover, you probably forgot to return your stream in the operator's overloading.

Putting everything together, and using public scope for simplicity (but please read about friend scope for operator overloading here), you get:
#include <iostream>
using namespace std;

class Circle;
ostream& operator<<(ostream& os, const Circle& rhs_c);

class Circle {
    public:
    void write(ostream& os) const {
        os<<*this;
    }
};

ostream& operator<<(ostream& os, const Circle& rhs_c) {
    // param 'rhs_c' should be used of course
    os<<"circle";
    return os;
}

int main() {
    Circle c1;
    c1.write(cout);
    return 0;
}

A: The problem is that you are trying to call an operator that "doesn't exist yet."  Because you defined your write() function in the header, and declared the operator<< below the class, at the point of invocation, as far as the compiler is concerned, operator<< is not included in the overload set.
To include it in the overload set, you must declare the function first, before your class.  But to declare the function it has to know about the class, so you must also declare that.  It is messy-ish and sounds worse than it is:
// declare that Circle is a class, so the compiler will know what a reference to it means
class Circle;

// declare the operator, but not define it yet, since Circle is incomplete.
ostream& operator<<(ostream& os, const Circle& rhs_c);

class Circle {
    void write(ostream& os) const {
        os<<*this;
    }
};

inline ostream& operator<<(ostream& os, const Circle& rhs_c) {
    os<<"circle";
}

This way, when the operator is called in write(), the compiler knows the operator exists, and then later it is defined and the linker will make the call happen.
There is another way too, and that is to NOT implement write() in the class definition, but after the operator<< is declared.  Perhaps move the definition to a .cpp file, but you could also implement it outside the class for the same effect:
class Circle {
    void write(ostream& os) const;
};

inline ostream& operator<<(ostream& os, const Circle& rhs_c) {
    os <<"circle";
}

inline void Circle::write(ostream& os) const {
    return os << *this;
}

Both ways the same thing is at play here: the definition of write() is physically located after the declaration of the operator it expects to use.
(If placed in the .cpp file, remove inline.)
Personally I recommend moving the implementation to a .cpp file.  Not only do you avoid these kinds of problems, you can also avoid including  in your header, and it's a big file (tens of thousands of lines of code to compile anytime your header is included.)  Instead, you should only use "forward" declarations to iostream classes available from the  header, and then you can get away with this pattern:
// header file
#include <iosfwd>
#pragma once

class Circle {
   void write(std::ostream&) const;
};

std::ostream& operator<<(std::ostream& os, Circle const& circle);

And then
// .cpp file
#include "Circle.hpp"
#include <iostream>

void Circle::write(std::ostream& os) {
   os << *this;
}

std::ostream& operator<<(std::ostream& os, Circle const& circle) {
   return os << "circle";
}

Splitting it this way, you include the much smaller  class in your header, and the heave  only once in your .cpp file.  It also means that all the functions in the .cpp file see all the declarations in the header (so ordering no longer matters).  Then your header is cleaner, easier to read class interface, while the .cpp file contains the heavier implementation detail that is only compiled once (instead of everywhere your header is included.)


text:
Q: How to display the values inside the pie chart of PrimeNG (chart) using JavaScript or Angular I have imported the pie chart from the PRIMENG CHART PLUGIN
i need to display the values inside a pie chart
The below is my code please refer
**In app.component.html**
<div style="display: block">
    <p-chart type="pie" [data]="data"></p-chart>
</div>

**In app.component.ts**
export class PieChartDemo {

    data: any;

    constructor() {
        this.data = {
            labels: ['A', 'B', 'C'],
            datasets: [{
                data: [300, 50, 100],
                backgroundColor: [
                    "#FF6384",
                    "#36A2EB",
                    "#FFCE56"
                ],
                hoverBackgroundColor: [
                    "#FF6384",
                    "#36A2EB",
                    "#FFCE56"
                ]
            }]
        };
    }
}

In the image i have attached the graph without any values displayed
If there is negative  -- 50
and positive -- 50
these values should be displayed inside the graph
Actual result:
As of now the values are not displayed inside the graph
Expected result:
Those values should be displayed inside the graph
The graph UI without the values displayed inside the graph

A: It's late, and i think you already found an answer, but for future people this can be achieved as follows:

*

*Install plugin: npm install chartjs-plugin-datalabels --save

*It would be registred globaly, and we need to unregister it, in order to include only for certain charts; place it, for example, in init method of root component
 import * as Chart from 'chart.js';
 import ChartDataLabels from 'chartjs-plugin-datalabels';
 ...

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})

export class AppComponent implements OnInit {
   chartJs = Chart;
   chartLabelPlugin = ChartDataLabels;

   constructor() {
   }

   ngOnInit(): void {
     this.chartJs.plugins.unregister(this.chartLabelPlugin);
  }
}

*Add plugin for certain chart
import ChartDataLabels from 'chartjs-plugin-datalabels';
...

plugin = ChartDataLabels;
options = {
  plugins: {
   datalabels: {
     /* show value in percents */
     formatter: (value, ctx) => {
       let sum = 0;
       const dataArr = ctx.chart.data.datasets[0].data;
       dataArr.map(data => {
             sum += data;
       });
       const percentage = (value * 100 / sum);
       return percentage !== 0 ? percentage.toFixed(2) + '%' : '';
     },
     color: '#fff',
   }
  }
}

<-- html -->

 <p-chart [options]="options"
          [data]="dataset"
          [plugins]="plugin"
          type="pie">
 </p-chart>

<-- html -->

A: This answer is correct but in app.component.ts you must import chartjs-plugin-datalabels
like this:
import * as ChartDataLabels from 'chartjs-plugin-datalabels';
not like this:
import ChartDataLabels from 'chartjs-plugin-datalabels';
Thank u so much Alexey.S!


text:
Q: FoldList and Compile Let me elaborate my previous question about Foldlist and Composition.
mc[t_]:=Compile[{{x,_Real,1}},{{Cos[t],-Sin[t]},{Sin[t],Cos[t]}}.x,
CompilationTarget->"C", RuntimeAttributes->{Listable}, Parallelization->True]
sc[k2_]:=Compile[{{x,_Real,1}},{x[[1]],x[[2]]-k2 x[[1]]^2},
CompilationTarget->"C", RuntimeAttributes->{Listable}, Parallelization->True]

I use {Listable} and Parallelization to speed-up iterations for many initial points. Now to FoldList. Using @kglr's suggestion from comments to previous question I can write:
FoldList[With[{xx = #2}, RightComposition[mc[0.2+xx], sc[2.]]]@#&,
{{0.01,0.001}, {-0.01,0.001}}, Range[0, 0.1, 0.001]]

Here I'm using just 2 inital points (there are much more in real application, also RightComposition is more complicated), this works, but VERY slow. I suppose it is because Compilation is done at every iteration step. And I have no idea how to fix this. Can someone help me to improve the code to make it work as fast as possible?
ADD
To address @MarcoB comment:
mc=Compile[{{x, _Real, 1},t},{{Cos[t],-Sin[t]},{Sin[t],Cos[t]}}.x,
CompilationTarget->"C", RuntimeAttributes->{Listable}, Parallelization->True]
sc=Compile[{{x,_Real,1},k2},{x[[1]],x[[2]]-k2 x[[1]]^2},
CompilationTarget->"C", RuntimeAttributes->{Listable}, Parallelization->True]

And if I add one more mc to iteration, this gives errors:
FoldList[With[{xx = #2}, RightComposition[mc[#,0.2+xx]&, sc[#,2.]&,
mc[#,0.3+xx]&]], {{0.01,0.001},{-0.01,0.001}}, Range[0,0.1,0.001]]

Errors I see:
Function::slotn: Slot number 2 in mc[#1,0.3 +#2]& cannot be filled from (mc[#1,0.3 +#2]&)[{{0.009602,0.00278236},{-0.00999934,-0.0012066}}].
CompiledFunction::cfta: Argument {{0.009602,0.00278236},{-0.00999934,-0.0012066}} at position 1 should be a rank 1 tensor of machine-size real numbers.
CompiledFunction::cfta: Argument {{0.009602 Cos[0.3 +#2]-0.00278236 Sin[0.3 +#2],0.00278236 Cos[0.3 +#2]+0.009602 Sin[0.3 +#2]},{-0.00999934 Cos[0.3 +#2]+0.0012066 Sin[0.3 +#2],-0.0012066 Cos[0.3 +#2]-0.00999934 Sin[0.3 +#2]}} at position 1 should be a rank 1 tensor of machine-size real numbers.
CompiledFunction::cfta: Argument {{0.979867 (0.009602 Cos[Plus[<<2>>]]-0.00278236 Sin[Plus[<<2>>]])-0.199649 (0.00278236 Cos[Plus[<<2>>]]+0.009602 Sin[Plus[<<2>>]]),0.199649 (0.009602 Cos[Plus[<<2>>]]-0.00278236 Sin[Plus[<<2>>]])+0.979867 (0.00278236 Cos[Plus[<<2>>]]+0.009602 Sin[Plus[<<2>>]])},{-0.199649 (-0.0012066 Cos[Plus[<<2>>]]-0.00999934 Sin[Plus[<<2>>]])+0.979867 (-0.00999934 Cos[Plus[<<2>>]]+<<22>> <<1>>),<<1>>+<<1>>}} at position 1 should be a rank 1 tensor of machine-size real numbers.
General::stop: Further output of CompiledFunction::cfta will be suppressed during this calculation.


text:
Q: $n$ is prime $\Leftrightarrow [a][b]=0\Rightarrow [a]=[b]=0 $ I'm stuck on the following exercise from Herstein's "Topics in Algebra":
"show that ($n$ is prime) $\Leftrightarrow ([a][b]=[0]\Rightarrow [a]=[b]=[0]) $ in $J_n$".

for the rightward implication I have:
$[a][b]=[ab]=[0]\Rightarrow n|ab\Rightarrow n|a$ or $n|b$ (or both) $\Rightarrow [a]=[0]$ or $[b]=[0]$
and I'm stuck on the leftward implication.
Why do I get $[a]=[0]$ OR $[b]=[0]$ and not $[a]=[0]$ AND $[b]=[0]$ in the leftward implication? Where is it that I go wrong?
I'd also appreciate any comment/hint about how to prove the remaining left implication.

A: As I already commented, the problem statement should be:
$n$ is prime if and only if ($[a][b] = [0] \implies [a] = [0]$ or $[b] = [0]$).
For the leftward direction: Prove this by contraposition: this means that if we want to prove $P \implies Q$, then we do so by proving $\text{not } Q \implies \text{not }P$ (these are equivalent). Hence I will prove the following: If $n$ is not a prime, then we have that $[a][b] = [0]$ and $[a] \neq [0] \neq [b]$. (since the we have that $\text{not }(K \implies L)$ is equivalent with ($K$ and $\text{not } L$).
First of all, note that $n$ is prime if and only if its only divisors are $1, n$. Hence $n$ is not prime if it has at least one divisor (and then automatically also a second one) which is neither $1$ nor $n$!
Now for your proof:
Suppose $n$ is not prime, then there exists divisors $a,b$ of $n$ which are by definition different from 1 and different form $n$. Hence we can write $n = ab$. In particular, we have that since $ 1 < a <n$ and $1 < b <n$ that $[a] \neq [0]$ and $[b] \neq [0]$ in $J_n$. However, we have that $$[0] = [n] = [ab] = [a][b]$$ and this concludes the prove.

A: Let us prove the leftward implication. That is, we need to show that
$$(i)\quad [a][b]=[0] \text{ implies either } [a]=[0] \text{ or } [b]=[0]\qquad\implies\qquad (ii)\quad n\text{ is prime}.$$
We prove this by contradiction. Assume that statement $(i)$ holds and suppose statement $(ii)$ is false. This means that $n$ is not prime, that is,  $n$ is composite. Then we write $n=ab$, where $1<a<n$ and $1<b<n$. We know that $$n\equiv 0\pmod n.$$ Thus,
$$ab\equiv 0\pmod n.$$
This implies that $[ab]=[0]$. Thus, $[a][b]=[0]$. By hypothesis, either $[a]=[0]$ or $[b]=[0]$. Hence, either $a\equiv 0\pmod n$ or $b\equiv 0\pmod n$. Hence, either $n|a$ or $n|b$ implying that either $n\leq a$ or $n\leq b$. We obtain a contradiction and this proves the result.


text:
Q: Mysql commands are not getting execute on the User class I have the following classes which are the connect (db) and the users class (User). When trying to run an sql statement from the users class I get the following error:
[09-Aug-2022 10:39:11 Europe/Berlin] PHP Notice:  Trying to get property of non-object in CustomerCare.class.php on line 69
namespace CustomerCare;
class db
{
    public $db_host;
    public $db_usermame;
    public $db_password;
    public $db_database;

    public function __construct()
    {
        $this->db_host      = "...";
        $this->db_username  = "...";
        $this->db_password  = "...";
        $this->db_database  = "...";

        $this->mysqli = new \mysqli($this->db_host, $this->db_username, $this->db_password, $this->db_database);

        if ($this->mysqli->connect_errno) {
            die("error...".$this->mysqli->connect_error);
        }

        $this->mysqli->set_charset('utf8');
        return $this->mysqli;
    }
}

class User
{
    private static $_id;
    private static $_firstname;
    private static $_lastname;
    private static $_email;
    private static $_entityId;

    public function __construct($_mysqli){
        $this->db       = $_mysqli->mysqli;
    }

    public function getId()             {   return self::$_id;          }
    public function getFirstname()      {   return self::$_firstname;   }
    public function getLastname()       {   return self::$_lastname;    }
    public function getEmail()          {   return self::$_email;       }
    public function getEntityId()       {   return self::$_entityId;    }

    public function setId($var)         {   self::$_id          =   $var;   }
    public function setFirstname($var)  {   self::$_firstname   =   $var;   }
    public function setLastname($var)   {   self::$_lastname    =   $var;   }
    public function setEmail($var)      {   self::$_email       =   $var;   }
    public function setEntityId($var)   {   self::$_entityId    =   $var;   }

    public function ComboBoxUsers($ei,$user)
    {
        $key= "blablabla";
        $sql = "call new_getUsers('{$ei}','{$key}');";
        $rs =  $this->db->query($sql);

        $output = ""; $selected = "";
        if ($rs->num_rows >0)
        {
            while ($record = mysqli_fetch_array($rs,MYSQLI_ASSOC))
            {
                if ($record['userEmail'] == $user) {
                    $selected = 'Selected';
                } else {
                    $selected = "";
                }
                $output .=  "<option value='{$record['userEmail']}' {$selected}>";
                $output .=      "{$record['userLastname']} {$record['userFirstname']} {$record['title']}";
                $output .=  "</option>";
            }
        }
        return $output;

    }
}

Do someone have an idea why the mysqli commands and not getting read?

A: changed the database connection using the following class:
    class Dbh
    {
        protected function connect()
        {
            try {
                $username = "....";
                $password = "....";

                $dbh = new PDO('mysql:host=localhost; dbname=....',$username,$password);
                return $dbh;
            }
            catch (PDOException $e) {
                print "Error!: ".$e->getMessage()."<br/>";
                die();
            }
        }
    }

and also changed methods PDO statements.


text:
Q: What is it called when indefinite pronouns are used as determiner? AFAIK it is correct English grammar to say something along the lines of

Familiarize yourself with everything Apple.

What is this use of "everything" called? Is it just a short colloquial form of saying "everything concerning"?
Only thing I could find was

Gretchen enjoys anything sweet.

at the bottom of https://ifioque.com/parts-of-speech/pronouns/indefinite-pronoun but it does not further clarify what this is called.

A:
What is it called when indefinite pronouns are used as determiner? E.g. "Familiarize yourself with everything Apple."

Everything is not a determiner. It is a pronoun.
"Everything Apple" = all things that are associated with Apple.
Apple is operating as a post-positional attributive noun.

A: My view is that in the phrase

Familiarize yourself with everything Apple

the word 'Apple' is used as a modifier. Think of an Apple device, an Apple style, a quintessentially Apple way of doing business etc.
I think that 'everything Apple' is of the same construction as
something/someone + modifier
which is of course common.


text:
Q: Python. Is digit should check for multiple number I write small program on python just to learn how split and isdigit functions works
Program is:
s = input('type something:')
if s.isdigit():
    a = s.split()
    a = list(map(int, a))
    print('What you typed was number and it was converted to integer')
    print('Result is:', a)
else:
    a = s.split()
    print('What you typed was words it was not converted to integer')
    print('Result is:', a)

Question is what... When i type one single number  program works fine. isdigit checks for number. (Is really list contains of number).
When i type 4 (only one number - that's fine)
But when i type 3 6 4 2 6 3 multiple numbers isdigit can not check it
Why?

A: As all the comments already say: A blank is not a digit and therefore the string "3 6 4 2 6 3" will return False.
>>> print("3 6 4 2 6 3".isdigit())
False

You can strip out all spaces by using the replace() function:
>>> print("3 6 4 2 6 3".replace(" ", "").isdigit())
True

A: It is because s is  a variable of string type
If you want to check each symbol from string s whether it is digit you should try something like [x.isdigit() for x in a].


text:
Q: Is it possible to build WinRT applications on Windows 7? Using Visual Studio 11 is it possible to build WinRT applications on Windows 7?

A: No; WinRT is only available on Windows 8 and AFAIK there have been no announcements that they will be made available in Win7.  At BUILD, they specifically said that WinRT was only to be supported on Win8.  By extension, you won't be able to develop against WinRT on a Win7 machine because the support just won't be made available.


text:
Q: CLion: build program won't run in cmd When I try to run my C++ project in Code::Blocks IDE, it'll run the program in Windows CMD without any problem. If I try to run the program via Explorer it'll also run in CMD without any problem.
However, if I try to run the exactly SAME program via CLion, it'll run fine in CLion itself (CLion has a builtin terminal, while Code::Blocks uses Windows CMD). But if I try to run the program via Explorer I get this weird error:

If I press OK:

Anyone knows what the problem is? How do I fix this?
More information:
Code::Blocks comes as a package with MinGW. With CLion I had to manually download a Toolchain. I downloaded and installed MinGW-w64, because I didn't know anything else and that's what Code::Blocks also used.
The weird part about this is that MinGW-w64 is installed in "Program Files (x86)" and not in "Program Files".

A: Add the following to your CMakeLists.txt file in CLion:
set(CMAKE_EXE_LINKER_FLAGS ${CMAKE_EXE_LINKER_FLAGS} "-static")

This will work for gcc, which mingw is based upon.  For other linkers, you would have to search for their particular switch for static linking.


text:
Q: How to run TestNG tests in parallel JVM process (not threads) Is it possible to run tests using TestNG framework in two different java processes (JVM)?
By default TestNG creates one process and all parallel tests run in separate threads inside it. And I need to wrap all static content inside ThreadLocal<> to make it Thread Safe. But if there is a way to run tests in two different processes I can leave everything as it is. I don't want to worry about Thread Safety.

A: TestNG not able to run tests in multiple processes.
However, at least maven (I hope gradle too) has a plugin for do this job.
See, how maven surefire plugin solves this: https://maven.apache.org/surefire/maven-surefire-plugin/examples/fork-options-and-parallel-execution.html.
You may use this config example (add this to pom.xml, build->plugins section):
<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-surefire-plugin</artifactId>
    <version>3.0.0-M5</version>
    <configuration>
        <forkCount>2</forkCount>
        <reuseForks>false</reuseForks>
        <reportsDirectory>target/surefire-reports-${surefire.forkNumber}</reportsDirectory>
        <suiteXmlFiles>
            <suiteXmlFile>src/test/resources/Suite1.xml</suiteXmlFile>
            <suiteXmlFile>src/test/resources/Suite2.xml</suiteXmlFile>
        </suiteXmlFiles>
    </configuration>
</plugin>


text:
Q: Help simplifying expression I have the following set of equations:
1)
$\text{$b_1$} \cos (\text{$\beta_1$} u)-\text{$b_1$} \cosh (\text{$\beta_1$} u)-\text{$b2$} \cos (\text{$\beta_1$} \theta  y)-\text{$d_2$} \cosh (\text{$\beta_1$} \theta  y)\sin (\text{$\beta_1$} u)-\sinh (\text{$\beta_1$} u)=0$
2)
$-\text{$b_1$} \sin (\text{$\beta_1$} u)-\text{$b_1$} \sinh (\text{$\beta_1$} u)+\text{$b_2$} \theta  \sin (\text{$\beta $1} \theta  y)-\text{$d_2$} \theta  \sinh (\text{$\beta_1$} \theta  y)+\cos (\text{$\beta_1$} u)-\cosh (\text{$\beta_1$} u)=0$
3)
$-\text{$b_1$} \cos (\text{$\beta_1$} u)-\text{$b_1$} \cosh (\text{$\beta_1$} u)+\alpha ^4 \text{$b_2$} \theta ^2 \cos (\text{$\beta_1$} \theta  y)-\alpha ^4 \text{$d_2$} \theta ^2 \cosh (\text{$\beta_1$} \theta  y)-\sin (\text{$\beta_1$} u)-\sinh (\text{$\beta_1$} u)=0$
... and I would like to find the constants $b_1$, $b_2$ and $d_2$.
I already know the answers:
$b_1 =\frac{\sin \left(\beta _1 u\right)-\sinh \left(\beta _1 u\right)}{\cosh \left(\beta _1 u\right)-\cos \left(\beta _1
   u\right)}$
$b_2 =\frac{2 \cos \left(\beta _1 u\right) \left(\cos \left(\beta _1 u\right) \cosh \left(\beta _1
   u\right)-1\right)}{\theta  \left(\cosh \left(\beta _1 u\right)-\cos \left(\beta _1 u\right)\right) \left(\cos
   \left(\beta _1 \theta  y\right) \sinh \left(\beta _1 \theta  y\right)+\sin \left(\beta _1 \theta  y\right) \cosh
   \left(\beta _1 \theta  y\right)\right)}$
$d_2 = -b_2 \frac{\cos \left(\beta _1 \theta  y\right)}{\cosh \left(\beta _1 \theta  y\right)}$
I want to find those expressions myself, but so far I only have that (using Mathematica):
Click on it, to see it full-scale...

Any help would be very much appreciated !

A: Writing the system as
$$Ab_1+Bb_2+Cd_2+D=0\tag1$$
$$Eb_1+Fb_2+Gd_2+A=0\tag2$$
$$Hb_1+Ib_2+Jd_2+E=0\tag3$$
should make it easy to solve where
$\qquad\begin{cases}A=\cos (\text{$\beta_1$} u)-\cosh (\text{$\beta_1$} u)&
\\\\B=-\cos (\text{$\beta_1$} \theta  y)&
\\\\C=-\cosh (\text{$\beta_1$} \theta  y)\sin (\text{$\beta_1$} u)&
\\\\D=-\sinh (\text{$\beta_1$} u)&
\\\\E=-\sin (\text{$\beta_1$} u)-\sinh (\text{$\beta_1$} u)\end{cases}$ $\qquad\begin{cases}F=\theta  \sin (\text{$\beta $1} \theta  y)&
\\\\G=-\theta  \sinh (\text{$\beta_1$} \theta  y)&
\\\\H=-\cos (\text{$\beta_1$} u)-\cosh (\text{$\beta_1$} u)&
\\\\I=\alpha ^4 \theta ^2 \cos (\text{$\beta_1$} \theta  y)&
\\\\J=-\alpha ^4 \theta ^2 \cosh (\text{$\beta_1$} \theta  y)\end{cases}$

$E\times (1)-A\times (2)$ gives
$$Kb_2+Ld_2+M=0\tag4$$
$H\times (1)-A\times (3)$ gives
$$Nb_2+Pd_2+Q=0\tag5$$
where
$$K=BE-AF,\quad L=CE-AG,\quad M=DE-A^2$$
$$N=BH-AI,\quad P=CH-AJ,\quad Q=DH-AE$$
$P\times (4)-L\times (5)$ gives
$$(PK-NL)b_2+PM-QL=0,$$
i.e.
$$b_2=\frac{QL-PM}{PK-NL}$$
From $(4)$,
$$d_2=\frac{MN-KQ}{PK-NL}$$
Finally, from $(1)$, we get
$$b_1=\frac{-B(QL-PM)-C(MN-KQ)-D(PK-NL)}{A(PK-NL)}$$