text:
Q: iOS VoiceOver crash (message sent to deallocated instance) I am getting a weird crash when running my app with VoiceOver enabled. The app has a sidebar interface (like Facebook). When tapping on one of the UITableViewCells in the sidebar UITableView, I swap out the view controller (create a new one based on which cell was tapped and deallocate the old one).
While VoiceOver is enabled, I sometimes get a crash when I tap the cell. This crash does not occur every time (it is about once every two or three tries) and this is not the only thing that causes the crash (but in my testing it is the main thing that triggers it).
Keep in mind this crash only happens then VoiceOver is enabled.
I usually get this line in the console when the crash occurs.

*** -[UITableTextAccessibilityElement setAccessibilityLabel:]: message sent to deallocated instance 0x1fdaec10

but I have also seen

* Terminating app due to uncaught exception 'NSRangeException', reason: '* -[__NSArrayM objectAtIndex:]: index 6 beyond bounds [0 .. 4]'
  Note then I see the NSRangeException with exception breakpoints enabled, it does not point me to a place in my code where the error occured.

So I enabled NSZombies and ran the app in Instruments. The object references was never touched by any of my code.

I also tried getting a crash log when running outside of the debugger, but unfortunatly Xcode was not able to symbolicate them.

Last Exception Backtrace:
0   CoreFoundation                    0x2e3c3f46 __exceptionPreprocess + 126
1   libobjc.A.dylib                   0x387536aa objc_exception_throw + 34
2   CoreFoundation                    0x2e2fa52e -[__NSArrayM objectAtIndex:] + 226
3   APP-NAME                      0x000e3726 0x46000 + 644902
4   UIKit                             0x0250462e 0x24c6000 + 255534
5   UIAccessibility                   0x35c029f8 -[NSObject(AXPrivCategory) accessibilityElementCount] + 16
6   UIAccessibility                   0x35bfe66a _appendChildrenToArrayStartingAtIndexWithChildren + 318
7   UIAccessibility                   0x35bfe51e _appendChildrenToArrayStartingAtIndex + 86
8   UIAccessibility                   0x35bfe460 _addAXElementsToArrayFromObject + 1580
9   UIAccessibility                   0x35bfddfc _appendVendedAXElementsFromUIElements + 156
10  UIAccessibility                   0x35bfdbfe _createAXUIElementsFromUIElements + 126
11  UIAccessibility                   0x35bfc218 _copyParameterizedAttributeValueCallback
  + 152
12  AXRuntime                         0x3152395c _AXXMIGCopyParameterizedAttributeValue + 168
13  AXRuntime                         0x3152084e _XCopyParameterizedAttributeValue + 438
14  AXRuntime                         0x31528158 mshMIGPerform + 184
15  CoreFoundation                    0x2e38e9da CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE1_PERFORM_FUNCTION + 30
16  CoreFoundation                    0x2e38e976 __CFRunLoopDoSource1 + 342
17  CoreFoundation                    0x2e38d14a __CFRunLoopRun + 1394
18  CoreFoundation                    0x2e2f7c22 CFRunLoopRunSpecific + 518
19  CoreFoundation                    0x2e2f7a06 CFRunLoopRunInMode + 102
20  GraphicsServices                  0x32fd627e GSEventRunModal + 134
21  UIKit                             0x30b9b044 UIApplicationMain + 1132
22  APP-NAME                          0x000509e2 0x46000 + 43490
23  libdyld.dylib                     0x38c5bab2 tlv_initializer + 2

The crash occurs on iOS 6 and 7. I also tried removing every accessibility call from the entire app, but the app was still crashing.
I have been trying to figure this out all week and do not feel like I am getting any closer. Any ideas on where to proceed from here?

A: I had the same error. I removed the accessibility methods to get rid of tis error.
We need to overwrite few accessibility methods to support reading order by voiceover in iOS 6
- (id)accessibilityElementAtIndex:(NSInteger)index
{
    return [[self accessibleElements] objectAtIndex:index];
}

- (NSInteger)indexOfAccessibilityElement:(id)element
{
    return [[self accessibleElements] indexOfObject:element];
}

If your code is crashing based on the above methods I feel. Try to remove those methods and check. One thing I observed is after removing the above methods Voiceover will not read the elements in order. It will read in some other(random) order.
Hope this will fix your crash.

A: We were able to find the problem by debugging on iOS 6 instead of 7.
In iOS 6,

AX ERROR: Could not find my mock parent, most likely I am stale.

was showing up in the console. That combined with the UITableViewCell error mentioned about, we dug through all of the table code in the sidebar.
We found that we were using reusable UITableViewCells as header views, and that was causing the zombie issue that we were seeing.
So bottom line, don't use UITableViewCells as UITableView header/footer view.

A: You can get this crash if you try to manually focus accessibility on to a UITableViewCell instead of a particular item inside the cell. If your requirement is to treat the tableCell as a whole as an accessibility element then in addition to specifying accessibility label and trait for the cell forget not to set isAccessibilityElement = YES for the cell. If isAccessibilityElement = YES then the iOS will not attempt to call [UITableTextAccessibilityElement setAccessibilityLabel:]method which causes the crash because it knows that tableCell itself is an accessibility element and will not try to examine what is inside the cell.


text:
Q: Is there a way to remove the "chose a file" from an input file type? I want to remove the "No file Chosen" from an input file and then rename the "choose" to another text.
"" $(document).ready(function() {
          var readURL = function(input) {
              if (input.files && input.files[0]) {
                  var reader = new FileReader();

                  reader.onload = function (e) {
                      $('.avatar').attr('src', e.target.result);
                  }

                        reader.readAsDataURL(input.files[0]);
                    }
                }

                $(".file-upload").on('change', function(){
                    readURL(this);
                });
                });""

A: One way to do this, as I have on a couple of occasions, would be to hide the input element and use a label element which is bound to the hidden file field to receive the click events. You can style the label however you see fit within reason so that ought to give sufficient flexibility to accomplish what you want?!
<!DOCTYPE html>

        <meta charset='utf-8' />
        <title></title>

        <form>
                <input type='file' name='photo' id='photo' />

                    Put your Text here

        </form>

a less verbose version of the above to show a minimal example
<!DOCTYPE html>

        <meta charset='utf-8' />
        <title></title>

        <form>
            <input type='file' name='photo' id='photo' />

                Put your Text here

        </form>

redpajama_set_name: RedPajamaStackExchange


text:
Q: Sorting enable for a limited number of columns In a grid with 5 columns, I would like to have the possibility of sorting only for columns 2 and 4.
What is the correct demarch for implement this ?
- declare sortable to true for columns 2 and 4
- what else ?

A: Default value of sortable property is already true (see here). So you have to include
sortable: false

property in the definition of all columns in colModel with exception columns 2 and 4. If you have many columns, then it would be better to change defaults for colModel items:
cmTemplate: { sortable: false }

After that you should include sortable: true in columns 2 and 4. In the way you can change any other defaults for colModel. See the answer for more details.


text:
Q: Training of chess evaluation function I am about to write a chess engine based on reinforcement learning.
I'd like to train an evaluation function and figure out what are the weights of the board's most important features.
I'm not an expert of machine learning, I'm trying to learn from books and tutorials. In each tutorial, the reward is quite straightforward, often 1, 0, maybe -1, but there's no such obvious reward in chess (regardless the check-mate positions).
For instance, assume I have a situation on the board. I make 10 (random) moves and at that point I should calculate the reward, the difference (or error) between the starting position and the current one. How to do such thing, when my only evaluation function is under training?
I'd like to avoid using other engines' scoring system, because I feel that would rather be supervised learning, which is not my goal.

A: You can't really do that directly.
A few approaches that I can suggest:

*

*Using scoring from an external source is not bad to at least kick start your algorithm. Algos to evaluate a given position are pretty limited though and your AI won't achieve master level using that alone.

*Explore the possibility of evaluating the position using another chess playing AI (open source ideally). Say you have a "teacher" AI. You start 2 instances of it and start the game from the position you want to evaluate. Let them play against each other from there until the end of the game. Was this move successful? Reward your own AI given the outcome.

*To add some variability (you don't want to be better than a single AI), do the same against other AIs. Or even, your own AI playing against itself. For the latter to work though, it probably needs to be already decent playing at chess, not playing entirely randomly. You can replay the same move many times and complete the game allowing your AI some random exploration of new moves and strategies (example: trying the 2nd best move down the road).

*Feed your ML using datasets of games between real players. Each move by the winning and losing players can be thus "reinforced"

*Have your AI learn by playing against real players. Reinforce both you AI moves (losing and winning ones) and that of the players.

A: I am not sure of any really good ways to do this, but since I am writing my own chess engine with a tuning function I can tell you how i did it.
I am using a genetic algorithm to tune the evaluation parameters, but the method of tuning is pretty useless if you don't have a way of evaluating the fitness of your model.
The way I do this is by playing around 5-10 games with random opening book moves. This is done such that the model won't over-fit because it analyzes the same kinds of positions. Then i collect the results of the games and the evaluations of all positions that the engine searched. A game result was represented as -1 for a black win, 0 for a draw and +1 for a white win, and therefore some function is needed to scale down the evaluation to be in the -1 to +1 range. Here i used tanh(0.5*Eval(pos)).
Then, for each position, i computed the squared difference between the evaluation and the game result, and added all these up to get the cost of the evaluation.


text:
Q: Google IMA Flash SDK - Flash ads not firing complete event I'm working on adding pre-roll video adverts to a flash video player using the Google IMA Flash SDK (AS3 version).
I'm testing it with different VAST tags to see how it performs. When using a VAST tag (the Google example tag) with ads with type 'VIDEO' on it everything works great, it fires all the events as expected.
However, when I use a VAST tag that has ads with the type 'FLASH' it doesn't fire some events, most importantly the 'COMPLETE' event.
Have other people had these problems, and how did you get around them?
I've done a bit of reading and the documentation states that for Flash ads it doesn't fire the 'COMPLETE' event, but how am I supposed to know when the video advert has finished, so I can start the video content again?


text:
Q: Cannot see a global variable declared by var/let under globalThis In D.Flanagan's 'Javascript the Definite Guide' there's an example:

var x = 1;
console.log(delete globalThis.x)

When I console log this code in node v14.15.1 then instead of false I get true. When console logging globalThis then x is not there. If I declare x without var or let then it becomes a part of global object. Funnily when I ran this code here on Stack Overflow then it behaved as Flanagan explained.
Can somebody please explain to me why global variables declared with var/let won't get a part of globalThis in my environment?  Is this because the version of Node I'm using or something else?


text:
Q: ColdFusion too big to be an integer I am trying to convert a large number going in to Megabytes. I don't want decimals
numeric function formatMB(required numeric num) output="false" {
    return arguments.num \ 1024 \ 1024;
    }

It then throws an error

How do I get around this?

A: You can't change the size of a Long, which is what CF uses for integers. So you'll need to BigInteger instead:
numeric function formatMB(required numeric num) {
    var numberAsBigInteger = createObject("java", "java.math.BigInteger").init(javacast("string", num));
    var mbAsBytes = 1024 ^ 2;
    var mbAsBytesAsBigInteger = createObject("java", "java.math.BigInteger").init(javacast("string", mbAsBytes));
    var numberInMb = numberAsBigInteger.divide(mbAsBytesAsBigInteger);
    return numberInMb.longValue();
}

CLI.writeLn(formatMB(2147483648));

But as Leigh points out... for what you're doing, you're probably better off just doing this:
return floor(arguments.num / (1024 * 1024));

A:
the size of a Long, which is what CF uses for integers

Small correction for those that may not read the comments. CF primarily uses 32 bit signed Integers, not Long (which has a much greater capacity). So as the error message indicates, the size limit here is the capacity of an Integer:

*

*Integer.MAX_VALUE = 2147483647

*Long.MAX_VALUE = 9223372036854775807
It is worth noting that although CF is relatively typeless, some Math and Date functions also have the same limitation. For example, although DateAdd technically supports milliseconds, if you try and use a very large number:
//  getTime() - returns number of milliseconds since January 1, 1970
currentDate = dateAdd("l", now().getTime(), createDate(1970,1,1));

... it will fail with the exact same error because the "number" parameter must be an integer. So take note if the documentation mentions an "Integer" is expected. It does not just mean a "number" or "numeric" ...


text:
Q: VBA, Get count from each sheet using multiple criteria I have 10 sheets in my workbook and the 10th sheet contains names of the first 9 sheets. I was trying to create a FORMULA using VBA to get the count from each sheet.
For example, I have data in sheet1 from range (a1:b500) and the criteria for the count is for every non-blank cell in the Column A there should be a blank cell in Column B.
Is it possible to create a UDF which takes range (a1:a500) as one array and range (b1:b500) as the second array and give the count based on the above criteria? The argument in the function should be only the sheet name – For instance, the function should take the argument as =GetCount(sheet1), where GetCount is the function name and sheet1 is the argument.
I found the solution using loop, but I want to avoid using loop in vba, countif and sum(array) in Excel and tryout with array feature
Function GetCount(Str As String)
    Application.Volatile (True)
    Dim wb As Workbook
    Dim sh As Worksheet
    Dim rng1 As Range
    Dim r As Integer
    Dim strCount As Integer
        Set wb = Workbooks("Integrated Working Tracker")
        Set sh = wb.Sheets(Str)
        Set rng1 = sh.Range("a1:a500")
        For Each c In rng1.Cells
         If c.Value <> "" And c.Offset(0, 1).Value = "" Then
         strCount = strCount + 1
         End If
        Next
    GetCount = strCount
    Set sh = Nothing
    Set wb = Nothing
    Set rng1 = Nothing
End Function

Any help is much appreciated. Thank you in advance

A: You can do this with a sumproduct formula.
In a cell itself, the formula would work like this:
=SUMPRODUCT((A1:A500<>"")*(B1:B500=""))

The individual conditional expressions, if combined in calculations, are converted to 1 or 0, and the row-wise results are then summed up.
In VBA, there is Worksheetfunction.SumProduct, but (as far as I remember, didn't test this now again) this does not support this 'specific' functionality (=converting boolean expressions to 1 or 0). So you have to use Evaluate.
Function GetCount(shName As String)
    Dim wb As Workbook
    Dim sh As Worksheet

    Set wb = Workbooks("Integrated Working Tracker")
    Set sh = wb.Worksheets(shName)
    GetCount = sh.Evaluate("SUMPRODUCT((A1:A500<>"""")*(B1:B500=""""))")
End Function

Edit: Since Str is also an integrated function, I would not use it as a variable name.


text:
Q: C# - YAXLib: Export data to XML file I have two sample classes that are used for de/serializing an XML file in tests.
XmlExampleBasicUnit.cs:
[YAXSerializeAs("Unit")]
public class XmlExampleBasicUnit
{
    [YAXSerializeAs("StringVar")]
    public String StringVar { get; set; }
    [YAXSerializeAs("Int32Var")]
    public Int32 Int32Var { get; set; }
    [YAXSerializeAs("DoubleVar")]
    public Double DoubleVar { get; set; }
    [YAXSerializeAs("DateTimeVar")]
    public String DateTimeVar { get; set; }
    [YAXSerializeAs("CharVar")]
    public String CharVar { get; set; }
}

XmlExampleCollectionOfUnits.cs:
[YAXSerializeAs("CollectionOfUnits")]
public class XmlExampleCollectionOfUnits
{
    [YAXSerializeAs("Units")]
    public List<XmlExampleBasicUnit> Units { get; set; }

    public XmlExampleCollectionOfUnits(List<XmlExampleBasicUnit> units)
    {
        Units = units;
    }

    public XmlExampleCollectionOfUnits()
    {
    }
}

I want to export a variable of XmlExampleCollectionOfUnits into an XML file that would be correctly formatted. This is a current function that is responsible for this:
public void Export<T>(String fileName, T result) where T : class
{
    YAXSerializer serializer = new YAXSerializer(typeof(T));
    using (FileStream fs = File.Create(fileName))
    {
        Byte[] info = new UTF8Encoding(true).GetBytes(serializer.Serialize(result));
        fs.Write(info, 0, info.Length);
    }
}

The problem is that this is using GetBytes() function which add some byte which is unrecognized by function that is responsible for importing data from an XML file. I have been trying to work this out with XmlTextWriter but with no success. I can get the String of a the content that I want to write into a file, but XmlTextWriter can't handle it.

A: The function Serialize of YAXSerializer has an overload for XmlWriter.


text:
Q: Case of side notes? When writing a book, some authors put important short terms they use in the main text also into the margin near the usage position. Assuming that these marginal notes in your book are always short and never constitute full sentences, what's more appropriate: capitalize the first letter of a marginal note or leave it small (assuming it's not a proper noun)?  Why?  In this respect, do the variants of English (AmE, BrE, CanE, AuE) or publishers' styles differ?

A: I think this is a very minor usage case, I can't say I've ever seen keywords put into marginal notes. How you present these is pretty much up to you. Just be consistent.


text:
Q: Where can i find Type Definitions Files (*.d.ts) for Amazon Cognito Identity SDK and how can i used them Where can i find Type Definitions Files (*.d.ts) for Amazon Cognito Identity SDK? and how can i used them.
I'm using TypeScript for Angular2 and i want to have the code assistant ready to use, when i implement "AWS Cognito". I already use import AWS = require("aws-sdk"); for the "aws-sdk" but i cant find a way to import the clases for "amazon Cognito Identity SDK". I already search in definitelytyped
Note: I already know that i can declare a global variable of type "any" but what i want its the utility of the code assistant.
UPDATE: "aws-sdk" and "amazon Cognito Identity SDK" are different and have different classes.
Update 2: I'm trying to implement this code:
AWSCognito.config.region = 'us-east-1';

var poolData = {
    UserPoolId : '...', // your user pool id here
    ClientId : '...' // your app client id here
};
var userPool =
new AWSCognito.CognitoIdentityServiceProvider.CognitoUserPool(poolData);
var userData = {
    Username : '...', // your username here
    Pool : userPool
};

A: I looked in the npm and I find it  npmjs,
you can install it :
npm install @types/aws-sdk


text:
Q: How to add an input textbox in PixiJs? I'm trying to create a login form and I'm using PixiJs v4 to render everything. It would be ideal to have the login form also in PixiJS as well, instead of using HTML.
How to I create a simple inputbox to capture text?

A: Create your input box in HTML and have 2 canvases; one with a z-index higher than the input box (for sprites that cover the input box), and one with a lower z-index (for sprites that go behind the input box).
.higher-canvas {
    position: absolute;
    left: 0px;
    top: 0px;
    z-index: 99;
}

.lower-canvas {
    position: absolute;
    left: 0px;
    top: 0px;
    z-index: -99;
}

If you must absolutely have your input element be a part of the stage, have you taken a look at PIXI.Input?  https://github.com/SebastianNette/PIXI.Input


text:
Q: Why is the first query always skipped and the sorting doesn't work? I have the following PHP to get data from a form with 2 drop downs and a radio button. The idea is that the values from the drop down determine the order by of the query (order by field ASC or DESC). However the second query in the code is the only one executed even when the radio button selects 1 and the ORDER BY parameters are not being correctly passed using the PHP variables. I hope someone cal help me spotting what is wrong, I have tried with isset and without it, so far no joy.
database connect and select is done here...

$sortIn = $_POST['SortOrder'];
$sortBy = $_POST['OrderBy'];
$include = $_POST['Include'];

if (isset($include) && $include = "0")
{
    $myquery = 'SELECT something FROM somewhere ORDER BY "$OrderBy" "$SortOrder"' ;
    $answer=mysql_query($myquery);
    if (!$answer) {
        $message  = 'Invalid query: ' . mysql_error() . "\n";
        $message .= 'Whole query: ' . $myquery;
        die($message);
        }

    echo "some HTML"

    while($result=mysql_fetch_array($answer))
    {
echo "some HTML";
}

elseif (isset($include) && $include = "1")
    {
     $myquerytwo = 'SELECT * FROM Results ORDER BY "$OrderBy" "$SortOrder"' ;
     $answertwo=mysql_query($myquerytwo);
     if (!$answertwo) {
    $message  = 'Invalid query: ' . mysql_error() . "\n";
    $message .= 'Whole query: ' . $myquerytwo;
    die($message);
        }
        echo "some HTML";

    while($resulttwo=mysql_fetch_array($answertwo))
    {
echo "Some HTML";
}

A: Your conditionals are not set right :)
You have:
$include = "0"

Which is just going to set $include to 0 and always return true since the assignment will suceed.
Change it to:
$include == "0"

Do that for your other conditional as well.
I'll also take a moment to let you know that the mysql_* library is deprecated and should no longer be used. I recommend using the mysqli set. It's the most like mysql_*, and easy to switch over to: here is the documentation.
Have some sort order:
"SELECT something FROM somewhere ORDER BY '$OrderBy' $SortOrder"


text:
Q: Integration by Parametric Integration. I have a question that I have no idea how to start:
$$\int_{0}^{1} \frac{x-1}{\ln x}dx$$
So in one of my classes, I learned a technique called parametric integration. But I have no idea how to use the technique with this question.
Any hints/help would be great!

A: The parametric integrand you want is as follows. Put
$$f(p)=\int_0^1\frac{x^p-1}{\ln x}dx$$
Then
$$f'(p) =\int_0^1\frac{\partial}{\partial p}\left(\frac{x^p-1}{\ln x}\right)dx=\int_0^1 x^p\;dx=\left.\frac{x^{p+1}}{p+1}\right|_0^1=\dfrac{1}{p+1}$$
so $f(p)= \ln(p+1)+ C$, where $C$ is to be determined. To find $C$, just note that $f(0)=0$ since the integrand vanishes when $p=0$; this means $C=0$, so
$$f(p)=\ln(p+1).$$
Note: In your specific case, take $p=1$ to get
$\int_0^1\frac{x-1}{\ln x}dx=\boxed{\ln 2}.$


text:
Q: Empty build directory in custom compiled kernel I have a script (found here on github) that custom compiles the 3.8 linux kernel (with Xenomai for real-time). The kernel compiles/installs/runs however when I try to install my graphics driver (fglrx for ATI RADEON 8490), I get the following error:
/lib/modules/3.8.13.20-xenomai-2.6.3/build/include/generated/uapi/linux/version.h cannot be found on this system.

When I look into this directory (/lib/modules/3.8.13.20-xenomai-2.6.3/build/) there is nothing there. I then ran an ls -l in /lib/modules/3.8.13.20-xenomai-2.6.3 and got the following output for the build directory:
build -> /home/yapatel/Dev/rtxi/scripts/linux-3.8.13

The directory that the build directory is pointing to was deleted as a part of the script for compiling/installing the custom kernel so this symbolic link is dead, which make sense as to why I am getting the error.
I am compiling the custom kernel using the following command:
fakeroot make-kpkg --initrd --append-to-version=-xenomai-$xenomai_version kernel-image kernel-headers modules

and then installing the compiled kernel using the following commands:
sudo dpkg -i linux-image-*.deb
sudo dpkg -i linux-headers*.deb
sudo update-initramfs -c -k $linux_version-xenomai-$xenomai_version
sudo update-grub

Now here is my question - I understood it as the above installation commands to take care of all the necessary pieces for installing a custom compiled kernel, however the deadlink to my build directory seems to suggest that I need to manually copy over the files from:
/home/yapatel/Dev/rtxi/scripts/linux-3.8.13

to
/lib/modules/3.8.13.20-xenomai-2.6.3/build/

This seems like a manuall fix rather than the proper fix. Is there a command I am missing in the compile/install process of my custom kernel? I am assuming this means my kernel modules are not being installed?
All advice/help is appreciated!

A: You need to either edit the script so that it does not delete the build directory (proper fix) as you are calling it or copy the files to the system (manual fix).
Neither of these "fixes" has anything to do with the commands used to compile a kernel (make).
You can choose where and how to compile a kernel, usually use use a build directory in your home directory and build as a user, but there is not good reason you could not use a system directory and build as root. You can use any location you wish for building.

A: Try to run make modules -j $number_of_cpus and then make modules_install -j $number_of_cpus to rebuild and install all the modules. Check if this still gives you errors.


text:
Q: ASP Chart Labels to display at the data points on multiple series ASP.NET 4 I have an ASP Chart (v4) which displays the data I need perfectly. I want it to show labels at the top of the data points and I am having some difficulty with it.
Here is my code that works for both series but does not display the labels:
If MySQLReader.HasRows Then
            Chart1.DataSource = MySQLReader
            Chart1.Series("New Customers Created").XValueMember = "Salesperson"
            Chart1.Series("New Customers Created").YValueMembers = "NCC"
            Chart1.Series("Target").XValueMember = "Salesperson"
            Chart1.Series("Target").YValueMembers = "Target"
            Chart1.DataBind()

            Chart1.Height = 500
            Chart1.Width = 750
            Chart1.ChartAreas("ChartArea1").AxisX.MajorGrid.Enabled = False
            Chart1.ChartAreas("ChartArea1").AxisY.MajorGrid.Enabled = True

            LBLError.Text = ""
        Else
            Chart1.Visible = False
            LBLError.Text = "
Your search did not match any records in the database. Please try again
"
        End If
        MySQLReader.Close()
        MyConn.Close()

Now here is my updated code that displays the Labels but only for one series.
If MySQLReader.HasRows Then

            Chart1.Series("New Customers Created").Points.DataBind(MySQLReader, "Salesperson", "NCC", "Label=NCC")
            Chart1.Series("Target").Points.DataBind(MySQLReader, "Salesperson", "Target", "Label=Target")
            Chart1.Height = 500
            Chart1.Width = 750
            Chart1.ChartAreas("ChartArea1").AxisX.MajorGrid.Enabled = False
            Chart1.ChartAreas("ChartArea1").AxisY.MajorGrid.Enabled = True

            Chart1.Series("New Customers Created")("LabelStyle") = "Bottom"
            Chart1.Series("New Customers Created").Font = New Drawing.Font("Arial", 8)
            LBLError.Text = ""
        Else
            Chart1.Visible = False
            LBLError.Text = "
Your search did not match any records in the database. Please try again
"
        End If
        MySQLReader.Close()
        MyConn.Close()

So my question is, please can you help me display both series in the updated code with labels for each series? Thanks!

A: OK, I figured it out.
using the first batch of code is fine. Adding the following IsValueShownAsLabel="True" shows the labels:
<asp:Series Name="New Customers Created" Legend="New Cust" IsValueShownAsLabel="True">
                    </asp:Series>
                    <asp:Series Name="Target" Legend="New Cust" IsValueShownAsLabel="True">
                    </asp:Series>


text:
Q: Enumerate all IPSec filters/policies from an AD Domain We've an AD Domain on Server 2008R2 (objectVersion 47) and running at 2003 functionality. Running commands on PowerShell v5.0.10586.117
IPSec policies and associated IP filter lists are used just for IP filtering (no encryption).
I believe all IPSec filter lists and policies are domain wide, GPOs only handle which single IPSec policy to apply?
I've used whatever google-fu I have on how to enumerate the many IPSec IP filters we have on domain/GPO and cannot get a meaningful result.
Can get Windows Firewall with Advanced Security results successfully using Get-NetFirewallRule and Show-NetFirewallRule.
Tried these commands Get-NetIPsecRule and Show-NetIPsecRule
Using their -PolicyStore argument such as:
# Always results in empty even if the GPO in question has a policy assigned.
# However am looking for all IP filters specified (which are domain wide as far as I can see)
Get-NetIPSecRule -PolicyStore domain.fqdn.com\GPO_Friendly_Name

# Fails as no GPO is specified
Get-NetIPSecRule -PolicyStore domain.fqdn.com

netsh commands so far have been on local machine or a remote machine which doesn't work for this situation.
Please feel to correct my above assumptions if they're wrong.
Any help would be appreciated! Thank you!


text:
Q: How to proper use forloop in ajax can anyone help me with my code in ajax....i have some error in my script code in ajax because of improper use of forloop...can anyone help me with my code please.
my problem is in the ajax script code....the update.php is ok no error it works perfectly.
script code:
<script type="text/javascript">
$(document).ready(function () {
       $('#updates').click(function (e) {

           e.preventDefault();

           var $region = $('#t_region').val();
           var $town = $('#t_town').val();
           var $uniq_id = $('#t_uniq_id').val();
           var $position = $('#t_position').val();
           var $salary_grade = $('#t_salary_grade').val();
           var $salary = $('#t_salary').val();

    for($n=1;$n<=15;$n++)   {
           var $id = $('#id'.$n).val();
           var $aic = $('#aic'.$n).val();
           var $name = $('#name'.$n).val();
           var $optA = $('#optA'.$n).val();
           var $optB = $('#optB'.$n).val();
           var $optC = $('#optC'.$n).val();
           var $optD = $('#optD'.$n).val();
           var $other_qual = $('#other_qual'.$n).val();
           var $interview = $('#interview'.$n).val();
           var $total = $('#total'.$n).val();

    }

           $.ajax({
               type: "POST",
               url: "update.php",
               data: {
                   region_text: $region,
                   town_text: $town,
                   uniq_id_text: $uniq_id,
                   position_text: $position,
                   salary_grade_text: $salary_grade,
                   salary_text: $salary,

              for($x=1;$x<=15;$x++) {

                   id'.$x.'_text: $id,
                   aic'.$x.'_text: $aic,
                   name'.$x.'_text: $name,
                   optA'.$x.'_text: $optA,
                   optB'.$x.'_text: $optB,
                   optC'.$x.'_text: $optC,
                   optD'.$x.'_text: $optD,
                   other_qual'.$x.'_text: $other_qual,
                   interview'.$x.'_text: $interview,
                   total'.$x.'_text: $total,
               }},
               cache: false,
               success: function (data) {

               }

           });

       });
   });
</script>

update.php code:
<?php
    include('../connection.php');
    date_default_timezone_set('Asia/Manila');

    $region        = @$_POST['region_text'];
    $town          = @$_POST['town_text'];
    $uniq_id       = @$_POST['uniq_id_text'];
    $position      = @$_POST['position_text'];
    $salary_grade  = @$_POST['salary_grade_text'];
    $salary        = @$_POST['salary_text'];

$dupesql = "SELECT * FROM afnup_worksheet WHERE funiq_id = '$uniq_id'";
$duperow = mysql_query($dupesql);
if(mysql_num_rows($duperow) > 0){
    exit;
}else{

    for($n=1;$n<=15;$n++)   {

    $id           = @$_POST['id'.$n.'_text'];
    $aic          = @$_POST['aic'.$n.'_text'];
    $name         = @$_POST['name'.$n.'_text'];
    $optA         = @$_POST['optA'.$n.'_text'];
    $optB         = @$_POST['optB'.$n.'_text'];
    $optC         = @$_POST['optC'.$n.'_text'];
    $optD         = @$_POST['optD'.$n.'_text'];
    $other_qual   = @$_POST['other_qual'.$n.'_text'];
    $interview    = @$_POST['interview'.$n.'_text'];
    $total        = @$_POST['total'.$n.'_text'];

if(!empty($name)){
$query = "INSERT INTO afnup_worksheet (faic,fregion,ftown,funiq_id,fposition,fsalary_grade,fsalary,fnl_name,edu_attain,experience,seminars,eligibility,other_qual,interview,ftotal,dateinputed)
VALUES
('$aic','$region','$town','$uniq_id','$position','$salary_grade','$salary','$name','$optA','$optB','$optC','$optD','$other_qual','$interview','$total',CURRENT_TIMESTAMP)";
$resource = mysql_query($query) or die(mysql_error());
        }
    }
}
?>

A: This should work:
<script type="text/javascript">
$(document).ready(function () {
   $('#updates').click(function (e) {
       e.preventDefault();
        var data = {};
        data.region_text = $('#t_region').val();
        data.town_text = $('#t_town').val();
        data.uniq_id_text = $('#t_uniq_id').val();
        data.position_text = $('#t_position').val();
        data.salary_grade_text = $('#t_salary_grade').val();
        data.salary_text = $('#t_salary').val();

        for(var $x=1;$x<=15;$x++) {
            data['id'+$x+'_text'] = $('#id'+$x).val();
            data['aic'+$x+'_text'] = $('#aic'+$x).val();
            data['name'+$x+'_text'] = $('#name'+$x).val();
            data['optA'+$x+'_text'] = $('#optA'+$x).val();
            data['optB'+$x+'_text'] = $('#optB'+$x).val();
            data['optC'+$x+'_text'] = $('#optC'+$x).val();
            data['optD'+$x+'_text'] = $('#optD'+$x).val();
            data['other_qual'+$x+'_text'] = $('#other_qual'+$x).val();
            data['interview'+$x+'_text'] = $('#interview'+$x).val();
            data['total'+$x+'_text'] = $('#total'+$x).val();
        }

        $.ajax({
            type: "POST",
            url: "update.php",
            data: data,
            cache: false,
            success: function (response) {
            // We are using response to distinguish our outer data variable here from the response
            }
        });
    });
});
</script>


text:
Q: Facebook api permission For a couple of website I have a facebook integration with the current JS library. Logging in works as expected.
I use the Facebook C# api with the JS library (v6). When a Facebook user is succesfully authenticated through the JS call it will send an ajax call to a C# method:
FacebookClient facebookClient = new FacebookClient(accessToken);

var fbResult = facebookClient.Get("me");
if (fbResult.GetType().ToString() != "Facebook.JsonObject")
     return null;

IDictionary<String, Object> result = (IDictionary<String, Object>)fbResult;

if (result.ContainsKey("email"))
    email = (String)result["email"];
            else
throw new Exception("E-mail key not found")

Now this works fine, the accessToken is passed, used by the c# library to get the user's information.
But for about 1 in 100 users the Exception is thrown! For some reason the e-mail key is not included in the "api".
On developers.facebook.com I have setup my app in "Auth Dialog" to "Authenticated Referrals": email and user_birthday.
But how is this possible? Am I overlooking something? How come the user can login to my app without the correct permissions?


text:
Q: Python: find exact word in list Set-up
I have the following dictionary,
d={'City':['Paris', 'Berlin','Rome', 'London']}

and the following one-element list,
 address=['Bedford Road, London NW7']

Problem
I want to check if one of the cities is in the address.

Tried so far
(1)
for x in d['City']:
  if x in address:
    print('yes')
  else:
    print('no')

only prints no.
(2)
for x in d['City']:
  r = re.compile(x)
  newlist = list(filter(r.match, address))

gives a TypeError: 'str' object is not callable. Got this one from this answer which seems to be what should solve this, but the error doesn't help.
How do I go about?

A: Your solution #1 was actually quite close, but it doesn't work, because address is a list of string, not a string itself.
So, it will work perfectly fine, if you just take first element of list address i.e. address[0].
Alternatively, you can try this:
>>> any(i in address[0] for i in d['City'] )
True

For code snippet, you can use:
if any(i in address[0] for i in d['City'] ):
    print 'Yes'
else:
    print 'No'

A: Since your address is a one-element list, you should check address[0] instead of address:
for x in d['City']:
    if x in address[0]:
        print('yes')
    else:
        print('no')

A: If you aren't increasing the size of the list:
for x in d['City']:
    if x in address[0]:
        print('yes')
    else:
        print('no')


text:
Q: Check if an object has loaded data or alternative text with javascript I have an object on my page, and I'm trying to check if the data has been loaded or not.
<object id ='pdf_support_checker' data="/dummy.pdf">
Testing
</object>

I've tried the load() function, but it still evaluates to true.  Can't find anything in the html when the alt text is displayed either.
Either Javascript or jquery is fine. Any ideas?

A: Got it!  I used this plugin in my script.
html:
  <object id ='pdf_support_checker' data="/dummys.pdf">
       Testing
  </object>

css:
#pdf_support_checker {
 background: #fff;
 height: 0px;
}
span#pdf_text {
color: #fff;
}

javascript:
window.pdfSupport = 1;
if ($('#pdf_text').visible(true, true)) {
     window.pdfSupport = 0;
};


text:
Q: How to make a function that take a callback which can take multiple arguments I'm developing a project in typescript and want to make a function, in which that function will take a single argument with type of callback, but the callback can have multiple arguments.
I have tried looking in the typescript issue for similiar use case 1, but I got an error of "TS2394: This overload signature is not compatible with its implementation signature."
https://github.com/microsoft/TypeScript/issues/4338#issuecomment-138268291
export interface Subscription {
  (): void
}
export interface xsSubscription {
  unsubscribe(): void
}

const createSubscription = () => {
  return {
    unsubscribe() {}
  }
}

type SyncMethod0 = (callback: () => void) => Subscription
type SyncMethod1<T1> = (callback: (data: T1) => void) => Subscription
type SyncMethod2<T1, T2> = (callback: (data1: T1, data2: T2) => void) => Subscription
type SyncMethod3<T1, T2, T3> = (callback: (data1: T1, data2: T2, data3: T3) => void) => Subscription

// The problem are in the next line, if I comment line 10 the problem are gone
function fromSync(method: SyncMethod0): (method: SyncMethod0) => xsSubscription
function fromSync<T1>(method: SyncMethod1<T1>): (method: SyncMethod1<T1>) => xsSubscription
function fromSync<T1, T2>(method: SyncMethod2<T1, T2>): (method: SyncMethod2<T1, T2>) => xsSubscription
function fromSync<T1, T2, T3>(method: SyncMethod3<T1, T2, T3>): (method: SyncMethod3<T1, T2, T3>) => xsSubscription
function fromSync(method: any) {
  let subscription: Subscription

  // For dummy data
  return createSubscription()

  // The real code are here, it will create an Observable (from xstreamjs)
  // return xs.create({
  //   start(listener) {
  //     subscription = method((...data) => {
  //       listener.next(...data);
  //     });
  //   },
  //   stop() {
  //     subscription();
  //   }
  // });
}

EDIT: Updated code example
Here is a link to typescript playground.


text:
Q: Zerg scouting vs Terran Wall off? I was wondering if anyone can help me with my Zerg scouting especially against a Terran Wall-off?
So I drone with my 12th drone and I almost ALWAYS get blocked with a Rax with 2 supply depots as they're being built. Even if I get lucky and kill the SCV building it. It doesn't help. Almost all the guides I read on zerg scout DEPEND on seeing the terran's gas. That essential factor is blocked from me....
What can I do? Sacrifice the overlord at about 4:30-5:00 ? ... I can only pray that the marines aren't patrolling the borders(Which they have done before).
Thanks.

A: Send your drone earlier - gas is usually built before the second supply depot, otherwise a tech block is hit. For banshees and other gas-heavy openings, the player can't afford waiting until 18+ supply to max gas - you should be able to scout what can be scouted before the second depot.
If you feel a need to keep watch on his base a while longer, you can always take the easy route - plant an extractor on his gas. At that point, he won't have the firepower to take it down quickly, it isn't too expensive for you, and if he's going for double gas, you've either slowed him down immensely or forced him to change his strategy to something gas-light. Really, it would be stupid of him to stick with a gas strategy if he was slowed down and hasn't yet made any irrevocable commitments. Banshees that come a minute later than usual aren't nearly as dangerous and require you to gimp yourself much less to defend against.
Consider keeping a ling near his ramp. Running up at any point would let you see all that you need to see. Siege tanks? Too many marauders in comparison to marines? No medivacs? Too few troops considering how far the game has progressed (aka he's probably cooking up a banshee surprise or something else he needs to keep hidden)? You'll see it all for the price of half a larva and 25 minerals.
As a zerg player, the third thing you do at the start of a match, after assigning miners and queueing up a drone, should be to send your overlord to the enemy base. This isn't 4:30-5:00, this is 0:03.  This will let you know when the enemy barracks are being constructed - at that point, your scout should have left or be on the way, and the overlord should go to a place a ground unit can't reach, or even to your base. It will also allow you detect abnormally early gas.


text:
Q: Query executed twice (by error) in Java with unwanted values I'm using JFreeChart to create a chart in Java and MySQL.
When I try to insert my values in another table the query seems to be executed twice since I end up with the same timestamps multiple times...
Here's a part of my code :
    private JDBCXYDataset createDataset() {
        try {
            Connection conn = DriverManager.getConnection(
                    "jdbc:mysql://localhost:bd?serverTimezone=UTC","MySQL", "MySQL");

            conn.setAutoCommit(false);
            SQLException savedException = null;

            Statement st = conn.createStatement();
            st.execute("DROP TABLE IF EXISTS test ");
            st.execute("create table test(Table timestamp, Table float,Table float)");

            String Date_Debut = "2020-06-25 00:00:00";
            String Date_Fin = "2020-06-26 00:00:00";
            String sql1 = "INSERT INTO test (Table ,Table ,Table ) "
                    + "SELECT Table ,Table ,Table "
                    + "FROM Table "
                    + "WHERE Table BETWEEN ? AND ? ";

           try ( PreparedStatement ps = conn.prepareStatement(sql1)){

            ps.setString(1,Date_Debut);
            ps.setString(2, Date_Fin);

            ps.executeUpdate();
            ps.close();

            JDBCXYDataset jds = new JDBCXYDataset(conn);

            st.close();

            jds.executeQuery("SELECT Table ,Table ,Table FROM test");

            conn.commit();
            return jds;
           } catch (SQLException ex) {
               savedException = ex;
               conn.rollback();
           } finally {
               conn.setAutoCommit(true);
               if(savedException != null) {
                   throw savedException;
               }
           }
       } catch (SQLException ex1) {

       }
        return null;
    }

EDIT : Actually it seems like the errors where comming directly from the database, the moderators can delete this post if they want. However I keep Trashgod's response validated as it was more than helpful.
For everyone that might come here with a similar issue, inspect in detail your database first to see if it isn't comming from there instead of your code.

A: Chasing down anomalies in data is arduous, but JFreeChart can at least make the result easier to visualize. Some heuristics for testing:

*

*To verify that the the presumed duplicates in your tabular listing  are indeed duplicates, format the timestamps to include milliseconds, e.g. add an S to a SimpleDateFormat or A to a DateTimeFormatter.

*For study, temporarily pass the query directly to JDBCXYDataset, and add an ORDER BY clause (untested):
jds.executeQuery(
      "SELECT Date_Heure, PV, SV FROM cmd3 "
    + "WHERE Date_Heure BETWEEN "
    + "2020-06-25 00:00:00 AND 2020-06-26 00:00:00 "
    + "ORDER BY Date_Heure");

*Enable tooltips in your ChartFactory, as you did here, to see data values in situ. This may suggest additional conditions for your WHERE clause, e.g. PV BETWEEN 5.1 AND 5.9.

*Use the interactive JFreeChart pan/zoom controls, discussed here to examine the data; add suitable buttons, shown here, if it will make it easier for colleagues to see your findings.

*By design, JDBCXYDataset executes a query defined by a String. If your design needs to display data from a query defined by a PreparedStatement, you can use the existing implementation as a guide.
public class PreparedDataset extends AbstractXYDataset
    implements XYDataset, TableXYDataset, RangeInfo {

    private final PreparedStatement ps;

    public PreparedDataset(PreparedStatement ps) {
        this.ps = ps;
    }
    …
}


text:
Q: Query based on 2 tables where duplicate id's amounts are calculated I Have 2 tables, table ONE consist of an category_id where each has its own not unique name attribute and each product_id would be unique in this table with no duplicates.
Table TWO consist of unique product_id just like table ONE and rank based on the biggest amount.
Table : ONE
  +--------+---------+------------+--------+
  | brd_id | cat_id  | product_id |  name  |
  +--------+---------+------------+--------+
  |      1 |       1 | 333        |    w   |
  |      2 |       1 | 444        |    w   |
  |      3 |       1 | 555        |    w   |
  |      4 |       2 | 666        |    y   |
  |      5 |       2 | 777        |    y   |
  |      6 |       3 | 888        |    t   |
  +--------+---------+------------+--------+

Table: TWO
  +--------+---------+------------+--------+--------+
  | new_id |  type   | product_id |  rank  | amount |
  +--------+---------+------------+--------+--------+
  |      1 |    all  | 333        |    1   |    80  |
  |      2 |    all  | 444        |    2   |    70  |
  |      3 |    all  | 555        |    3   |    60  |
  |      4 |    all  | 666        |    4   |    50  |
  |      5 |    all  | 777        |    5   |    40  |
  |      6 |    all  | 888        |    6   |    30  |
  +--------+---------+------------+--------+--------+

What i want is to show name from table ONE only once based on the amount from table TWO WHERE in table ONE product_id has the same cat_id.
This i was able to achieve using this query basically straight from database so fields differ:
SELECT DISTINCT  `cat`.`brand_name`
FROM `ps_product_brand` AS `cat`
INNER JOIN `ps_product_custom_statistics_weekly` AS `cat_p`
ON `cat_p`.`id_product` = `cat`.`id_product`
WHERE `cat_p`.`type` LIKE '%all%'
AND `cat_p`.`rank` <= 16
ORDER BY `cat_p`.`rank` ASC

PROBLEM
I get duplicate names, so i used DISTINCT which in the end ignores the duplicate values.
I want to calculate the amount where the product_id from table ONE is IN table TWO AND where they have the same category_id in table ONE.
EXPECTED OUTPUT
  +---------+--------+
  | cat_id  |  name  |   amount
  +---------+--------+
  |       1 |    w   |    210
  |       2 |    y   |     90
  |       3 |    t   |     30
  +--------+---------+

Hope it makes sense. THANKS

A: I don't have a fiddle to work with, but I think this is right.
It MIGHT have typos.
The general idea is that we do the distinct FIRST nest it.  Then, once we get the distinct, then we get the SUM of the distinct elements from the secondary table.  The reason we do it this way is because otherwise the SUM (if done in the inside) would join multiple records and get an amount that is too high.
SELECT A.CAT_ID, A.BRAND_NAME,
(SELECT SUM(AMOUNT) FROM ps_product_custom_statistics_weekly P WHERE P.ID_PRODUCT=A.ID_PRODUCT) FROM
(
SELECT DISTINCT  `cat`.`cat_id`, `cat`.`brand_name`, `cat_p`.`rank`
FROM `ps_product_brand` AS `cat`
INNER JOIN `ps_product_custom_statistics_weekly` AS `cat_p`
ON `cat_p`.`id_product` = `cat`.`id_product`
WHERE `cat_p`.`type` LIKE '%all%'
AND `cat_p`.`rank` <= 16
GROUP BY  `cat`.`cat_id`, `cat`.`brand_name`
) A
ORDER BY A.RANK

A: Try the following:
SELECT `cat`.`brand_name`, `cat_p`.`amount`, SUM(`cat_p`.`amount`) AS `sum_amount`
FROM `ps_product_brand` AS `cat`
INNER JOIN `ps_product_custom_statistics_weekly` AS `cat_p` ON `cat_p`.`id_product` = `cat`.`id_product`
WHERE `cat_p`.`type` LIKE '%all%' AND `cat_p`.`rank` <= 16
GROUP BY `cat`.`brand_name`
ORDER BY `sum_amount` DESC, `cat`.`brand_name`

Note the difference in numbers between amount and sum_amount where the duplicates are. You might have to increase the rank and possibly add LIMIT to the end.


text:
Q: Terminology: Using "distribution" when referring to densities? I've been looking through some literature on probability theory, and I have noticed that some authors seem to use the term "distribution" very loosely, and more than once when referring to probability densities. An example from the wikipedia article on marginal distributions:

Similarly for continuous random variables, the marginal probability
  density function can be written as $p_X(x)$. This is
  $$p_X(x) = \int p_{X|Y}(x|y)p_Y(y)dy $$
  where $p_{X,Y}(x,y)$ gives the joint
  distribution of X and Y, while $p_{X|Y}(x|y)$ gives the conditional
  distribution for X given Y.

Again, from the article on Posterior Probability:

The posterior probability distribution of one random variable given
  the value of another can be calculated with Bayes' theorem by
  multiplying the prior probability distribution by the likelihood
  function, and then dividing by the normalizing constant, as follows:

gives the posterior probability density function for a random variable
  X given the data Y=y, where ...

Now a probability density determines a distribution, but they are not interchangable. The reason I ask is I am reading some algorithms and proofs for MCMCs and it is often very unclear whether the computations are done via densities or probabilites, and looking at different sources is often more confusing than helping, since the terminology seems to differ. Am I missing something, or is this inconsistant usage of the terms?

A: The distribution of a random variable is a measure, defined on the space where the random variable takes its values. It encodes the probability of every event you are considering. So, when you have a real valued random variable, its distribution is a measure on $\mathbb{R}$. Sometimes this measure can be described by a probability density function, but not always.
Since the the density function fully describes the distribution, you can refer to "calculating the density function" as "calculating the distribution". So I see no problem with:

The posterior probability distribution of one random variable given the value of another can be calculated...
where $p_{X,Y}(x,y)$ gives the joint distribution of X and Y...

Keep in mind that you are only interested in knowing that function because it represents a distribution, which is what you are really interested in.
What I do find somewhat far fetched is:

by multiplying the prior probability distribution by the likelihood function...

Because here the object you really are multiplying is the density function. On the other hand, it's a little bit like this: Let's say you are searching through a photo album and someone comes along and asks what you are searching for. You respond:

I want to see if I can find Alice in here

It's clear that you mean "to find a photograph in which Alice is depicted" and you are not expecting to find the real person Alice in that album. The same way "multiplying the prior probability distribution" intends to refer to "multiplying the density function that describes the prior probability distribution" in that case.
Something to add: The reason why it's clear in the above example that a photograph of Alice is meant rather than Alice itself is the availability of additional knowledge. When writing about mathematics, whenever commensurate, it's better to do it in a way that doesn't rely on additional knowledge on the reader's side.


text:
Q: If $X$ is regular and $C$ closed, then $X/C$ is Hausdorff. Let $X$ be a topological space and $C \subseteq X$ closed. Give $X/C$ the quotient topology and suppose $X$ is regular. Then this implies that $X/C$ is Hausdorff.
Approach: Let $p: X \to X/C$ be denoted as the quotient map. Take two points $x,y \in X/C$, we then have to find two disjoint neighborhoods. Then I looked at $p^{-1}(\{x\})$ and $p^{-1}(\{y\})$, which are sets closed in $X$. And then I don't know.
Can anyone give me an hint or a solution? Thanks


text:
Q: how do i add variables with logistic distributions? i have X, Y, random logistic variables, how do I add them given the mean and scale for each?
Logistic distribution.  i ran a simulation in python, but i cannot get it to be exact.
i ran a simulation on getting a random number X, Y, and keep score on the value of X + Y.  then i did the same for getting a single random number with X + Y and test another scale based on the original scales, but i cannot fix the new scale to make them match

A: The sum of two logistic random variables does not have a logistic distribution.  However, the sum is approximately logistic.  You could justify this by arguing that a logistic distribution is approximately normal and the sum of two normal random variables is normal. (This post explains how close the normal and logistic distributions are.)
Say X1 has mean m1 and scale s1 and X2 has mean m2 and scale s2.  Then X1 + X2 has mean m1 + m2.  X1 has variance pi^2 s1^2 / 3 and X2 has variance pi^2 s2^2 / 3, so X1 + X2 has variance pi^2 (s1^2 + s2^2)/3.  This is exact.  We know the mean and variance of the sum, though not its exact distribution.  But if you're willing to assume that the sum has an approximately logistic distribution, then the corresponding logistic distribution would have mean m1 + m2 and scale sqrt(s1^2 + s2^2).

A: The numpy.random module (sorry for the strange link, but numpy's own site seems to be down right now) has a logistic function that should generate random numbers with a logistic distribution correctly (haven't tested it personally, but I'd be amazed if such a widely used package as numpy made incorrect claims).  However, as several comments mentioned, the sum of two logistic-distribution random variables doesn't have logistic distribution itself.


text:
Q: How to call RESTAPIs in magento2.2.4? Currently I am using magento2.2.4. How to call REST APIs in magento?
Is there magento2 provide default REST APIs?  and how can I call the rest apis?

A: Yes, Magento 2.2.4 provides REST API for all the functionalities like customers, products, orders, wishlist, etc.,
First, you need to get a token to access these REST APIs. For that you may use this API: http://www.domainname.com/rest/V1/integration/admin/token and your payload should have admin access username and password. Refer this screenshot: https://devdocs.magento.com/guides/v2.0/get-started/authentication/images/gs_auth_token1.png
You will receive a token and you can use this token to use on all your API calls.
Here is the list of APIs available in Magento 2 (listed by Module):
https://devdocs.magento.com/guides/v2.0/rest/list.html

A: This is the core PHP way to call APIs
<?php
$userData = array("username" => "adminUserName", "password" => "AdminPassword");
$ch = curl_init("BaseUrl/rest/V1/integration/admin/token");
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($userData));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/json", "Content-Lenght: " . strlen(json_encode($userData))));

$token = curl_exec($ch);

$ch = curl_init("BaseUrl/rest/V1/customers/1");
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/json", "Authorization: Bearer " . json_decode($token)));

$result = curl_exec($ch);

var_dump($result);

Below is the complete list of API by default provided by magento
https://devdocs.magento.com/guides/v2.0/rest/list.html

A:
Open the System > Extensions > Integrations

Add New Integration

Set the integration Name and other settings, then specify your
  Magento 2 back-end password in the Your Password field

Switch to the API sidebar tab and select the resources which will
  be available to OAuth clients:

Press the Save button. The integration will be saved and the
  Integrations list will be shown again. Press the Activate link in the integration row:

A confirmation screen will be shown. Press the Allow button

The credentials screen will be shown.
    Use them in your third-party software to access your Magento 2 as OAuth server.
You will see:

*

*Consumer Key

*Consumer Secret

*Access Token

*Access Token Secret

  Copy it to somewhere, then press the Done button.

The integration will be saved and the Integrations list will be
  shown again. You will see your integration in the Active state:

and for Customer Token
In magento web-API when you pass user name and password then it genrates token for that specific customer (Which is only valid for 1 hour - configurable from admin)

http://magento.host/index.php/rest/V1/integration/customer/token?username=test.user@test.com&password=test@123

webapi.xml code
<route url="/V1/customers/me" method="GET">
    <service class="Magento\Customer\Api\CustomerRepositoryInterface" method="getById"/>
    <resources>
        <resource ref="self"/>
    </resources>
    <data>
        <parameter name="customerId" force="true">%customer_id%</parameter>
    </data>
</route>

which returns token.
After genrating token, when we pass that token in header.
Authorization :: Bearer <Token Value>

http://magento.host/index.php/rest/V1/customers/me

Which returns customer detailes.
The above case i explained is working fine for webAPI in magento2 which i tested in POSTMAN.


text:
Q: Extend horizontal line to edges of chart area In Excel 2007 I have a chart with a horizontal line (data series) similiar to what this page shows. But, as you notice, the line starts and ends in the middle of the data point. So, if there are bars on the same chart, the horizontal line will not extend to cover the entire first and last bars. How can I extend the horizontal line to touch the chart edges on the left and right sides?
I tried putting in "dummy" points at the beginning and end of the data series that had zero values (for the bars). This looked good, but the x-axis numbering started at zero and ended at one more than my last real data point, which, in my case is unacceptable.
Oh, and I'm creating the charts in VBA, so I need a VBA solution (which may be the same as the manual solution, just coded). Thanks.

A: If you right click on the horizontal axis and go into axis options. At the very bottom under Position Axis: select "On Tick Marks"

A: I answered a similar questions here:
Bar and Line charts are not synced when in the same chart area
In the above question the user needed to move the line to the left, but you can do a similar thing for your case.
Use scatter chart for your line chart. Then you need to set the xvalues of the scatter chart to be a bit different than the ones for your column chart. So let's say that your x-axis numbering goes from 1 to 12. Then you should distribute your xvalues for scatter chart from 0.8 to 12.2. That moves the starting point a bit to the left (0.8 instead of 1) and the last point a bit to the right (12.2 instead of 12). The exact number that you should use will depend on your gap and overlap settings of the column chart.

A: I eventually found an answer here. This worked great for me and did exactly what I needed.


text:
Q: Return an array from a function I am using the PHP Simple HTML DOM Parser to scrape some results from a page.
At the moment I am having a problem with the function as it is not returning the array "$result".
Any help would be greatly appreciated :)
The result of the array:
array(1) { [0]=> array(6) { ["itemid"]=> string(6) "123456" ["title"]=> string(21) "XXX Prod1" ["unit"]=> string(6) "500ml " ["price"]=> string(4) "2.59" } [1]=> array(6) { ["itemid"]=> string(6) "123457" ["title"]=> string(27) "XXX Prod2" ["unit"]=> string(6) "500ml " ["price"]=> string(5) "10.49" }

Code in question:
function parseItems($html) {
foreach($html->find('div.product-stamp-inner') as $content) { //Finds each individual product on page and extracts its details and stores it into its own array

    $detail['itemid'] = filter_var($content->find('a.product-title-link', 0)->href, FILTER_SANITIZE_NUMBER_FLOAT);
    $detail['title'] = $content->find('span.title', 0)->plaintext;
    $detail['unit'] = $content->find('span.unit-size', 0)->plaintext;
    $detail['price'] = filter_var($content->find('span.price', 0)->plaintext, FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION | FILTER_FLAG_ALLOW_THOUSAND);
    $result[] = $detail; //Puts all individual product arrays into one large array
    }
    //var_dump($result); --Testing purposes
    return $result;
}

A: I guess what you have a piece of code like so
parseItems($html);

When it should be the following because it is returning a variable and needs a variable to hold its returning result
$retval = parseItems($html);


text:
Q: Android XML fragment tag resize programmatically Can I change the size of a fragment, added in the XML by using code? If so, how?
This is how the fragment view is inflated:
protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sigiture);
        init();
        setMetrics();

        Log.d("Layout Width", "" + fragmentLayout.getLayoutParams().width);
    }

    private void init() {
        fragmentLayout = (RelativeLayout) findViewById(R.id.fragmentLayout);
    }


text:
Q: Searching in a list to see if an item contains part of the word Not seeing my answer so I'm going to explain what I'm looking to do.  I need to break some data out of a url, some of the urls have the word limit in the followed by a guid.  What I want to do is see if the word is in any part of the item in the list.
I want to iterate through the list items and if the item contains the word limit I want to get the next 33 characters
Here is an example of the list:

limits =
  ['limit=5e8f0dc0-4074-481d-a12c-5d3a70406ad7&location=d877f1f9-fae3-4f39-82ca-499ec8a7a0d2',
  'location=d877f1f9-fae3-4f39-82ca-499ec8a7a0d2',
  'sourceLimitAllocationOid=212a7e22-aafd-40e3-9684-621dae6708af&sourceUnits=5000&sourceUnitOfMeasureCode=TON&tragetUnitOfMeasureOid=1bec1009-90d3-de11-9251-001d092afdd0&targetLimitCommodityOid=7e7a1112-b7c7-4563-9bd4-702e14b139f4',
  '',
  'limit=5e8f0dc0-4074-481d-a12c-5d3a70406ad7&location=2e12899b-e84d-4b1a-8b89-faced0771efc',
  '',  'location=2e12899b-e84d-4b1a-8b89-faced0771efc',
  'sourceLimitAllocationOid=bfa24508-a4e3-4138-8d29-7e9b7c1ea559&sourceUnits=3000000&sourceUnitOfMeasureCode=BU&tragetUnitOfMeasureOid=1bec1009-90d3-de11-9251-001d092afdd0&targetLimitCommodityOid=7e7a1112-b7c7-4563-9bd4-702e14b139f4',
  '',  '',
  'limit=c0ba884c-800b-4174-8374-0bc5515f8282&location=b3d785e6-4d0c-460b-8e2c-1f32732a1a20',
  'location=b3d785e6-4d0c-460b-8e2c-1f32732a1a20']

A: Try this:
import re
limits = ['limit=5e8f0dc0-4074-481d-a12c-5d3a70406ad7&location=d877f1f9-fae3-4f39-82ca-499ec8a7a0d2', 'location=d877f1f9-fae3-4f39-82ca-499ec8a7a0d2', 'sourceLimitAllocationOid=212a7e22-aafd-40e3-9684-621dae6708af&sourceUnits=5000&sourceUnitOfMeasureCode=TON&tragetUnitOfMeasureOid=1bec1009-90d3-de11-9251-001d092afdd0&targetLimitCommodityOid=7e7a1112-b7c7-4563-9bd4-702e14b139f4', '', 'limit=5e8f0dc0-4074-481d-a12c-5d3a70406ad7&location=2e12899b-e84d-4b1a-8b89-faced0771efc', '', 'location=2e12899b-e84d-4b1a-8b89-faced0771efc', 'sourceLimitAllocationOid=bfa24508-a4e3-4138-8d29-7e9b7c1ea559&sourceUnits=3000000&sourceUnitOfMeasureCode=BU&tragetUnitOfMeasureOid=1bec1009-90d3-de11-9251-001d092afdd0&targetLimitCommodityOid=7e7a1112-b7c7-4563-9bd4-702e14b139f4', '', '', 'limit=c0ba884c-800b-4174-8374-0bc5515f8282&location=b3d785e6-4d0c-460b-8e2c-1f32732a1a20', 'location=b3d785e6-4d0c-460b-8e2c-1f32732a1a20']

for el in limits:
    a = re.search(r'\b(limit)\b', el)
    if a is not None:
        ind = a.start()
        print(el[ind+5:ind+38])

A: According to this tutorial, you can do this:
offset = len("limit")
limit = ""
for item in limits:
    index = item.find("limit")
    if (index != -1):
        limit = item[ (limit + offset + 1): (limit + offset + 34) ]
        break

There's a couple of things going on here on top of what you asked for. First, I assumed that there's only one string with limit in it. If not, remove the break statement and make limit be a list with the assignment changed to an append. Second, I assumed you didn't want to take the = from the string so I'm actually adding one to the start and end to do that. Alternatively, you could just remove the first character later if that's what you want to do.
I hope this helps.


text:
Q: Processing: function rotate doesn't work properly Hello i'm trying to draw a square in processing using only line() and rotate() functions but i'm having a bit of an issue probably with the rotate function.
Here is my code for the draw function:
void draw(){
   background(0);
   stroke(255);
   for(int i = 0; i < 4; i++){
       line(0, 0, GRID_SIZE, 0);
       translate(GRID_SIZE, 0);
       rotate(HALF_PI);
   }
}

The result:

Why the bottom and the left lines are tilted even if i rotated by PI/2?
Thanks in advance!

A: This is pretty much expected behavior.
Keep in mind that in "real life", numbers like PI and PI/2 are infinitely long. Computers can't hold infinitely long numbers, so the variable HALF_PI holds an approximate value. So when you rotate by HALF_PI, you're actually rotating with a little bit of "error" each time. That error adds up, so you get artifacts like what you're seeing.
This is made worse by the fact that pixels are whole numbers, not float values. So if you have one pixel with a Y position of 20.0000001, and another pixel with a Y position of 19.9999999, they'll be rendered at 20 and 19 respectively, so you'll see a "big" difference (of 1 whole pixel) between them even though the real difference is small.
If you want your lines to look more square, then just use the rect() function that Processing provides.


text:
Q: Windows Forms Custom Control not painting correctly So i'm trying to make a nice rounded switch that when clicked it will slide either left or right to basically turn something on or off (it could be used for other things). I have a rectangle version working somewhat ok (i have a few tweaks in mind that I want to make for it) but the problem I'm running into is by using rounded rectangles. I made a few classes to help my self in this. I have one called RoundRectanglePath. Using the Create method I give it a Rectangle (or x,y,w,h) and a radius for the corners and it returns a closed GraphicsPath that I can then use Graphics.[Fill|Draw]Path with. I then have a RoundRectangle class which is a just a control that acts very similar to a Label. I found that if I override the OnPaintBackground and not send the event to the base, but instead paint a rectangle the same color as it's Parent.BackColor than I get the illusion that the control is really round. (as a related side note I allow transparent)
For my RoundMovableSwitch class I use 2 RoundRectanglePaths to split the Control in half. The left is a green Color and the right is Pink (thinking about it now I could have just used a horizontal LinearGradient brush...ooops oh well) I then draw the string On and Off on opposing sides. To that control I add a RoundRectangle. When the user clicks on either the RoundRectangle or the MoveableSwitch the Control then moves the RoundRectangle left or right 1 pixel at a time. The movement works great. The problem I am having is this. The outside Edge of the RoundRectangle is the correct Transparent color. The inside edge is the wrong color. See RoundMovingSwitch 1 and 2 in picture below. Once I get the code working correctly I'll go back and reorganize the code a bit more.

The code is hosted on GitHub: Here

A: "The problem I am having is this. The outside Edge of the RoundRectangle is the correct Transparent color. The inside edge is the wrong color."
Not sure I understand the problem...
Are you trying to get rid of the blue corners that are outside the rounded edges?
If so, then try this in RoundRectangle:

    public RoundRectangle()
    {
        this.ResizeRedraw = true;
        this.VisibleChanged += new EventHandler(RoundRectangle_VisibleChanged);
    }

    private bool RegionSet = false;
    void RoundRectangle_VisibleChanged(object sender, EventArgs e)
    {
        if (this.Visible && !RegionSet)
        {
            RegionSet = true;
            var r = new RectangleEx(this.ClientRectangle);
            var path = RoundRectanglePath.Create(r.ToRectangle(), this.Radius, this.Corners);
            this.Region = new Region(path);
        }
    }

*If the size of the control changes then you should reset the Region() property to the new size.
Edit: To make it reset the Region when the size changes:
    protected override void OnSizeChanged(EventArgs e)
    {
        base.OnSizeChanged(e);
        var r = new RectangleEx(this.ClientRectangle);
        var path = RoundRectanglePath.Create(r.ToRectangle(), this.Radius, this.Corners);
        this.Region = new Region(path);
    }


text:
Q: Order of operations when using evaluation bar Suppose we have the function
\begin{align*}
f(x) = \sin(x)
\end{align*}
with first derivative
\begin{align*}
\frac{d}{dx}f(x) = \cos(x).
\end{align*}
If we evaluate $f'(x)$ at $x=0$, the result depends on whether you evaluate $f(0)$ or differentiate $f(x)$ first.
\begin{align*}
\displaystyle \frac{d}{dx}f(x)\mid_{x = 0} = \cos(x)\mid_{x = 0} = 1\\
\displaystyle \frac{d}{dx}f(x)\mid_{x = 0} = \frac{d}{dx}f(0) = \frac{d}{dx}0 = 0
\end{align*}
First question: Does this mean the following two statements are not equivalent?
\begin{align*}
\displaystyle \left(\frac{d}{dx}f(x)\right)\mid_{x = 0}\\
\displaystyle \frac{d}{dx}\left(f(x)\mid_{x = 0}\right)
\end{align*}
Second question: if so, which of the following is true, and why?
\begin{align*}
\displaystyle \frac{d}{dx}f(x)\mid_{x = 0} =
\left(\frac{d}{dx}f(x)\right)\mid_{x = 0}
\end{align*}
or
\begin{align*}
\displaystyle \frac{d}{dx}f(x)\mid_{x = 0} = \frac{d}{dx}\left(f(x)\mid_{x = 0}\right)
\end{align*}

A: *

*These are not equivalent indeed. $$\displaystyle \frac{d}{dx}\left(f(x)\mid_{x = 0}\right)$$will always be 0.

*For that reason, this notation always means the first form.

A: If the following were true:
$$\frac{d}{dx}f(x)\mid_{x = n} = \frac{d}{dx}\left(f(x)\mid_{x = n}\right)$$
Then it would always be 0. Why? Because once you evaluate a function of x at a particular value of x, it is no longer a function of x; it's a value (or, a constant function). The example (sin, cos) you gave is a little misleading. Consider instead the function $f(x)=x^2$ , and instead the point $x=3$ :
$$\frac{d}{dx}f(x)\mid_{x = 0} = \frac{d}{dx}\left(f(x)\mid_{x = 0}\right)\\
f(x)\mid_{x = 0}=9\\
\frac{d}{dx}9=0$$


text:
Q: How to run node.js code on the server automatically? I am using a node package(sitemap-generator) to create a sitemap.xml file for my angular website,
At the moment I am running this code manually on my machine then uploading the generated file each time.
Is there any way I can automate this process, maybe by uploading the code and running it periodically and automatically

A: You can use node-scehdule  module to run sitemap generator everyday at a specific time , you can set time according to your requirement
   const SitemapGenerator = require('sitemap-generator');
    const cron = require('node-schedule');
    const generator = SitemapGenerator('https://examaple.com', {
        maxDepth: 0,
        filepath: '/var/www/example.com/sitemap.xml',
        maxEntriesPerFile: 50000,
        stripQuerystring: true,
        lastMod:true
    });
    cron.schedule('0 22 * * *', () => {
        console.log("will run at 10:00 PM everyday");
        generator.start();
    });


text:
Q: How to remove all JSON formatting (not just whitespace) from a JSON object in Java? I have a JSON object like this:
{
    "shippingLines": [{
        "carrier": "NZ Post",
        "price": {
            "amount": 5.50,
            "currency": "NZD"
        }
    }],
    "taxAmount": {
        "amount": 5.325,
        "currency": "NZD"
    },
    "reference": "INV000045",
    "totalAmount": {
        "amount": 35.5,
        "currency": "NZD"
    },
    "returnUrls": {
        "successUrl": "http://yourserver/success",
        "failUrl": "http://yourserver/fail",
        "callbackUrl": "http://yourserver/fail-safe-callback"
    }
}

I want to strip off all JSON formatting (spaces, comma, parentheses, brackets, quotes, colon) from it and product an output like following:
shippingLinescarrierNZPostpriceamount5.50currencyNZDtaxAmountamount5.325currencyNZDreferenceINV000045totalAmountamount35.5currencyNZDreturnUrlssuccessUrlhttp://yourserver.com/successfailUrlhttp://.yourserver.com/failcallbackUrlhttp://yourserver.com/fail-safe-callback

so I tried a bunch of replaceAll() like below:
String json = objectMapper.writeValueAsString(<Json Class here>); // using Jackson
json.replaceAll("\"", "")
    .replaceAll("\\{","")
    .replaceAll("\\}","")
    .replaceAll("\\[","")
    .replaceAll("\\]","")
    .replaceAll(":","")
    .replaceAll(",","")
    .replaceAll(" ","");

But this also replaced the "colon" in the URL (http://...) in the returnUrls object.
Is there a better way to achieve this ?
Note: I'm on Java 7.

A: Go char by char.  Copying stuff between quotes as is
String json = objectMapper.writeValueAsString(<Json Class here>); // using Jackson
String output = "";
int len = json.length();
boolean inQuotes = false;
for (int i = 0; i < len; i++)
{
    char c = json.charAt(i);
    if (c == '\"')
    {
        inQuotes = !inQuotes;
        continue;
    }
    if (inQuotes)
    {
        output = output + c;
    }
}

There's optimizations with regards to appending to strings, StringBuilder, etc... but the above is the basic gist of it.
As others have pointed out, this doesn't handle the case of an escape sequence within a string:
"A string with an \"escaped\" quote include \u1234 and \b or \t"

I'm going to leave that up you as an exercise.

A: Here's another approach. The idea is to traverse all elements, and return their string representation, with whitespace removed.
// Takes input and returns a string with all elements concatenated.
// withExactBigDecimals(true) makes sure trailing zeros (e.g. 5.50) will be
// preserved
static String toRawConcat(String input) throws IOException {
    ObjectMapper mapper = new ObjectMapper()
        .configure(DeserializationFeature.USE_BIG_DECIMAL_FOR_FLOATS, true)
        .configure(JsonGenerator.Feature.WRITE_BIGDECIMAL_AS_PLAIN, true)
        .setNodeFactory(JsonNodeFactory.withExactBigDecimals(true));
    JsonNode node = mapper.readTree(input);
    return nodeToString(node);
}

// Removes whitespaces from a string
static String removeWs(String input) {
    return input.replaceAll("\\s+", "");
}

// Inspects the node type and returns the node contents as a string
private static String nodeToString(JsonNode node) {
    switch (node.getNodeType()) {
        case NULL:
        case BOOLEAN:
        case STRING:
            return removeWs(node.asText());
        case NUMBER:
            return node.decimalValue().toString();
        case ARRAY:
            {
                String s = "";
                Iterator<JsonNode> it = node.elements();
                while (it.hasNext()) {
                    s += nodeToString(it.next());
                }
                return s;
            }
        case OBJECT:
            {
                String s = "";
                Iterator<Entry<String, JsonNode>> it = node.fields();
                while (it.hasNext()) {
                    Entry<String, JsonNode> sub = it.next();
                    s += removeWs(sub.getKey()) + nodeToString(sub.getValue());
                }
                return s;
            }
        default:
            throw new UnsupportedOperationException("Node type " + node.getNodeType() + " not supported");
    }

By the way, if you want to strip just everything that doesn't look like a node value (e.g. you're expecting "NZ Post" to become "NZPost"), why are you parsing it as JSON in the first place?

A: To remove colon after key First remove only

":

After completion get new string. Now remove

"

A: You can do in three steps, not sure that you have any other case.
Step 1: Replace all http:// to something. For instance, http:__
Step 2: Your current one.
Step 3: Reverse it from step 1.

A: If the issue is strictly the http://, then you could replace http// by the original http://.
   String output1=    json.replaceAll("\"", "")
                    .replaceAll("\\{","")
                    .replaceAll("\\}","")
                    .replaceAll("\\[","")
                    .replaceAll("\\]","")
                    .replaceAll(":","")
                    .replaceAll(",","")
                    .replaceAll(" ","")
                    .replaceAll("\\\\","")
                    .replaceAll("http//", "http://");

Careful though, as this will result in unwanted replacements if your json ever contains a http// that you don't wish to replace.

A: You can use regex for it. This will help you.
REGEX [^a-zA-Z0-9-./]
public class Test {

    public static void main(String[] args) {
        String jsonString = "{\n" +
                "    \"shippingLines\": [{\n" +
                "        \"carrier\": \"NZ Post\",\n" +
                "        \"price\": {\n" +
                "            \"amount\": 5.50,\n" +
                "            \"currency\": \"NZD\"\n" +
                "        }\n" +
                "    }],\n" +
                "    \"taxAmount\": {\n" +
                "        \"amount\": 5.325,\n" +
                "        \"currency\": \"NZD\"\n" +
                "    },\n" +
                "    \"reference\": \"INV000045\",\n" +
                "    \"totalAmount\": {\n" +
                "        \"amount\": 35.5,\n" +
                "        \"currency\": \"NZD\"\n" +
                "    },\n" +
                "    \"returnUrls\": {\n" +
                "        \"successUrl\": \"http://yourserver/success\",\n" +
                "        \"failUrl\": \"http://yourserver/fail\",\n" +
                "        \"callbackUrl\": \"http://yourserver/fail-safe-callback\"\n" +
                "    }\n" +
                "}";
        String format = jsonString.replaceAll("[^a-zA-Z0-9-./]", "");
    }
}

A: We can first convert it to yaml, then replacing would be more easier and generic. Like here
import java.io.IOException;

import org.springframework.util.StringUtils;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.yaml.YAMLMapper;

public class Library {

    public static String asYaml(String jsonString) throws JsonProcessingException, IOException {
        // parse JSON
        JsonNode jsonNodeTree = new ObjectMapper().readTree(jsonString);
        // save it as YAML
        String jsonAsYaml = new YAMLMapper().writeValueAsString(jsonNodeTree);
        return jsonAsYaml;
    }
    public static void main(String[] args) {
        String jsonStr = "{\r\n" +
                "    \"shippingLines\": [{\r\n" +
                "        \"carrier\": \"NZ Post\",\r\n" +
                "        \"price\": {\r\n" +
                "            \"amount\": 5.50,\r\n" +
                "            \"currency\": \"NZD\"\r\n" +
                "        }\r\n" +
                "    }],\r\n" +
                "    \"taxAmount\": {\r\n" +
                "        \"amount\": 5.325,\r\n" +
                "        \"currency\": \"NZD\"\r\n" +
                "    },\r\n" +
                "    \"reference\": \"INV000045\",\r\n" +
                "    \"totalAmount\": {\r\n" +
                "        \"amount\": 35.5,\r\n" +
                "        \"currency\": \"NZD\"\r\n" +
                "    },\r\n" +
                "    \"returnUrls\": {\r\n" +
                "        \"successUrl\": \"http://yourserver/success\",\r\n" +
                "        \"failUrl\": \"http://yourserver/fail\",\r\n" +
                "        \"callbackUrl\": \"http://yourserver/fail-safe-callback\"\r\n" +
                "    }\r\n" +
                "}";
        try {
            String ymlstr = asYaml(jsonStr);
            System.out.println(ymlstr);
            ymlstr=StringUtils.replace(ymlstr, ":", "");
            ymlstr=StringUtils.replace(ymlstr, "-", "");
            ymlstr=StringUtils.replace(ymlstr, "\n", "");
            ymlstr=StringUtils.replace(ymlstr, " ", "");
            ymlstr=StringUtils.replace(ymlstr, "\"", "");
            System.out.println(ymlstr);
        } catch (JsonProcessingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }
}

Maven dependencies:
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-core -->
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-core</artifactId>
    <version>2.8.6</version>
</dependency>
    <!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.8.6</version>
</dependency>
    <!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.dataformat/jackson-dataformat-yaml -->
<dependency>
    <groupId>com.fasterxml.jackson.dataformat</groupId>
    <artifactId>jackson-dataformat-yaml</artifactId>
    <version>2.8.6</version>
</dependency>

Output:
shippingLinescarrierNZPostpriceamount5.5currencyNZDtaxAmountamount5.325currencyNZDreferenceINV000045totalAmountamount35.5currencyNZDreturnUrlssuccessUrlhttp//yourserver/successfailUrlhttp//yourserver/failcallbackUrlhttp//yourserver/failsafecallback


text:
Q: angular2 ngOnChanges not working for multiple inputs I am working on this angular2 app in which I am accepting two inputs in one component.
I have used ngOnChanges to detect changes on these input values.
@Input() games: any;
@Input() selectedGame:any;

ngOnChanges(changes: {[propName: string]: SimpleChange}) {
    this.selectedGame=changes['selectedGame'].currentValue;  //this works
    this.games=changes['games'].currentValue;    //this doesn't work
}

However, I can only detect change in first variable. the second variable is not getting updated when its value changes in parent.
any inputs?

A: Depending on the change from the parent component, ngOnChanges might be triggered separately for each Input changed. You need to check which Input has changed first.
ngOnChanges(changes: SimpleChange}) {
    if(changes['selectedGame'] !== undefined)
        this.selectedGame=changes['selectedGame'].currentValue;

    if(changes['games'] !== undefined)
        this.games=changes['games'].currentValue;
}

Here's the working plunk
https://plnkr.co/edit/n6X21VHXw1xlA8XCPoQu

A: You supposed to use SimpleChanges instaed of SimpleChange, it will give you all list of input parameters.
ngOnChanges(changes: SimpleChanges) {
 for (let propName in changes) {
   let change = changes[propName];
   let curVal  = JSON.stringify(change.currentValue);
   let prevVal = JSON.stringify(change.previousValue);

    console.log(curVal);
    console.log(prevVal);
 }
}


text:
Q: application memory optimization We have a project written in ANSI C. Generally the memory consumption was not a big concern, but now we have a request to fit our program into 256 KB of RAM. I don't have  this exact platform on hands, so I compile  my project under 32 bit x86 Linux (because it provides enough different tools to evaluate the memory consumption), optimize what I can, remove some features and eventually I have  to have the conclusion: what features we need to sacrifice to be able to run on very small systems (if we're able at all). First of all I did a research what exactly a memory size in linux and it seems I have to optimize the RSS size, not VSZ. But in linux even a smallest program which prints "Hello world!" once a second consumes 285-320 KB in RSS:
#include  <stdio.h>
#include  <unistd.h>
#include  <signal.h>

unsigned char  cuStopCycle = 0;

void SigIntHandler(int signo)
{
   printf("SIGINT received, terminating the program\n");
   cuStopCycle = 1;
}

int main()
{
   signal( SIGINT, SigIntHandler);

   while(!cuStopCycle)
   {
      printf("Hello, World!\n");
      sleep(1);
   }
   printf("Exiting...\n");
}

user@Ubuntu12-vm:~/tmp/prog_size$ size ./prog_size
text       data     bss     dec     hex filename
1456        272      12    1740     6cc ./prog_size

root@Ubuntu12-vm:/home/app# ps -C prog_size -o pid,rss,vsz,args
PID     RSS    VSZ   COMMAND
22348   316   2120   ./prog_size

Obviously this program will perfectly run on small PLCs, with 64KB of RAM. It is just linux loads a lot of libs. I generate a map file for this program and all this data + bss comes from the CRT library. I need to mention that if I add some code to this project - 10,000 times "a = a + b" or manipulate arrays 2000 long  int variables, I see the difference in code size, bss size but eventually the RSS size of the process is the same, it doesn't affected)
So I take this as a baseline, the point I want to reach (and which I will never reach, because I need more functions than just print a message once a second).
So here comes my project, where I removed all extra features, removed all auxiliary functions, removed everything except the basic functionality. There are some ways to optimize more, but not that much, what could be removed is already taken away:
root@Ubuntu12-vm:/home/app/workspace/proj_sizeopt/Cmds# ls -l App
-rwxr-xr-x 1 root root 42520 Jul 13 18:33 App

root@Ubuntu12-vm:/home/app/workspace/proj_sizeopt/Cmds# size ./App
   text    data     bss     dec     hex filename
  37027     404     736   38167    9517 ./App

So I have ~36KB of code and ~1KB of data. I do not call malloc inside of my project, I use a shared memory allocation with a wrapper library so I can control how much memory is allocated:
The total memory size allocated is 2052 bytes

Under the hood there are malloc calls obviously, if I substitute 'malloc' calls with  my function which summarize all alloc requests I see that ~2.3KB of memory is allocated:
 root@Ubuntu12-vm:/home/app/workspace/proj_sizeopt/Cmds# LD_PRELOAD=./override_malloc.so ./App
Malloc allocates 2464 bytes total

Now I run my project amd see that it consumes 600KB of RAM.
root@Ubuntu12-vm:/home/app/workspace/proj_sizeopt# ps -C App -o pid,rss,vsz,args
  PID   RSS    VSZ COMMAND
22093   604   2340 ./App

I do not understand why it eats so much memory. The code size is small. There is not much memory allocated. The size of data is small. Why it takes so much memory? I tried to analyze the mapping of the process:
root@Ubuntu12-vm:/home/app/workspace/proj_sizeopt# pmap -x 22093
22093:   ./App
Address   Kbytes     RSS   Dirty Mode   Mapping
08048000       0      28       0 r-x--  App
08052000       0       4       4 r----  App
08053000       0       4       4 rw---  App
09e6a000       0       4       4 rw---    [ anon ]
b7553000       0       4       4 rw---    [ anon ]
b7554000       0      48       0 r-x--  libpthread-2.15.so
b756b000       0       4       4 r----  libpthread-2.15.so
b756c000       0       4       4 rw---  libpthread-2.15.so
b756d000       0       8       8 rw---    [ anon ]
b7570000       0     300       0 r-x--  libc-2.15.so
b7714000       0       8       8 r----  libc-2.15.so
b7716000       0       4       4 rw---  libc-2.15.so
b7717000       0      12      12 rw---    [ anon ]
b771a000       0      16       0 r-x--  librt-2.15.so
b7721000       0       4       4 r----  librt-2.15.so
b7722000       0       4       4 rw---  librt-2.15.so
b7731000       0       4       4 rw-s-    [ shmid=0x70000c ]
b7732000       0       4       4 rw-s-    [ shmid=0x6f800b ]
b7733000       0       4       4 rw-s-    [ shmid=0x6f000a ]
b7734000       0       4       4 rw-s-    [ shmid=0x6e8009 ]
b7735000       0      12      12 rw---    [ anon ]
b7738000       0       4       0 r-x--    [ anon ]
b7739000       0     104       0 r-x--  ld-2.15.so
b7759000       0       4       4 r----  ld-2.15.so
b775a000       0       4       4 rw---  ld-2.15.so
bfb41000       0      12      12 rw---    [ stack ]
-------- ------- ------- ------- -------
total kB    2336       -       -       -

And it looks like the program size (in RSS) is only 28KB, the rest is consumed by shared libraries. BTW I do not use posix threads, I do not explicitly link to it, but somehow the linker anyway links this library I have no idea why (this is not really important). If we look at the mapping in more details:
root@Ubuntu12-vm:/home/app/workspace/proj_sizeopt# cat /proc/22093/smaps
08048000-08052000 r-xp 00000000 08:01 344838     /home/app/workspace/proj_sizeopt/Cmds/App
Size:                 40 kB
Rss:                  28 kB
Pss:                  28 kB
Shared_Clean:          0 kB
Shared_Dirty:          0 kB
Private_Clean:        28 kB
Private_Dirty:         0 kB
Referenced:           28 kB
Anonymous:             0 kB
AnonHugePages:         0 kB
Swap:                  0 kB
KernelPageSize:        4 kB
MMUPageSize:           4 kB
Locked:                0 kB

...

09e6a000-09e8b000 rw-p 00000000 00:00 0          [heap]
Size:                132 kB
Rss:                   4 kB
Pss:                   4 kB
Shared_Clean:          0 kB
Shared_Dirty:          0 kB
Private_Clean:         0 kB
Private_Dirty:         4 kB
Referenced:            4 kB
Anonymous:             4 kB
AnonHugePages:         0 kB
Swap:                  0 kB
KernelPageSize:        4 kB
MMUPageSize:           4 kB
Locked:                0 kB

...

b7570000-b7714000 r-xp 00000000 08:01 34450      /lib/i386-linux-gnu/libc-2.15.so
Size:               1680 kB
Rss:                 300 kB
Pss:                   7 kB
Shared_Clean:        300 kB
Shared_Dirty:          0 kB
Private_Clean:         0 kB
Private_Dirty:         0 kB
Referenced:          300 kB
Anonymous:             0 kB
AnonHugePages:         0 kB
Swap:                  0 kB
KernelPageSize:        4 kB
MMUPageSize:           4 kB
Locked:                0 kB

...

b7739000-b7759000 r-xp 00000000 08:01 33401      /lib/i386-linux-gnu/ld-2.15.so
Size:                128 kB
Rss:                 104 kB
Pss:                   3 kB
Shared_Clean:        104 kB
Shared_Dirty:          0 kB
Private_Clean:         0 kB
Private_Dirty:         0 kB
Referenced:          104 kB
Anonymous:             0 kB
AnonHugePages:         0 kB
Swap:                  0 kB
KernelPageSize:        4 kB
MMUPageSize:           4 kB
Locked:                0 kB

...

bfb41000-bfb62000 rw-p 00000000 00:00 0          [stack]
Size:                136 kB
Rss:                  12 kB
Pss:                  12 kB
Shared_Clean:          0 kB
Shared_Dirty:          0 kB
Private_Clean:         0 kB
Private_Dirty:        12 kB
Referenced:           12 kB
Anonymous:            12 kB
AnonHugePages:         0 kB
Swap:                  0 kB
KernelPageSize:        4 kB
MMUPageSize:           4 kB
Locked:                0 kB

*

*So I see that RSS size for my project is 40KB, but only 28 KB is used. Does it mean that this project will fit into 256 KB of RAM?

*The heap size is 132KB but only 4 KB is used. Why is that? I'm sure it will be different on the small embedded platform.

*The stack is 136KB but only 12KB is used.

*GLIBC/LD obviously consume some memory, but what exactly memory will it be on the embedded platform?

I do not look at PSS because it doesn't make any sense in my case, I look only at RSS.
What conclusions can I draw from this picture? How exactly to evaluate memory consumption by the application? Look at the RSS size of the process?  Or subtract from this size RSS of all mapped system libraries? What is about heap/stack size?
I would be very grateful for any advises, notes, memory consumption optimizations techniques, DOs and DON'Ts for platforms with extremely small amount of RAM (except obvious - keep amount of data and code to the very minimum).
I also will appreciate an explanation WHY the program with small amount of code and data (and which doesn't allocate much memory) still consumes a lot of RAM in RSS.
Thank you in advance

A:
... fit our program into 256 KB of RAM. I don't have this exact platform on hands, so I compile my project under 32 bit x86 Linux..

And what you now see is that the Linux platform tools make reasonable assumptions of your possible need of stack and heap, given that it nows you run on a big machine, and links-in a reasonable set of library functions for your needs. Some you won't need, but it gives them to you "for free".
To fit in 256 Kb on your target platform, you must compile for your target platform and link with the target platform's libraries (and CRT) using the target platform's linker.
Those will make different assumptions, use possibly smaller linbrary footprints, make smaller assumptions on stack and heap space, etcetera. For example, create "Hello World" for the target platform and check its needs on that target platform. Or use a realistic simulator of the target platform and libraries (and not to forget, OS, whch partly dictates what the libraries must do).
And if it is then still too  big, you have to re-write or tweak the whole CRT and all libraries....

A: the program needs to be compiled/linked with the embedded device in mind.
For best results use a makefile
use the 'rt' library written for the embedded device
use the start.s file, located, via the makefile, where execution begins.
use 'static' in the linker parameters
use the linker parameters to not include any libraries but what is specifically requested.
do not use libraries written for your development machine.  Only use libraries written for the embedded device.
do NOT include stdio.h, etc. unless specifically written for the embedded device
do NOT call printf() inside a signal handler.
if possible, do not call printf() at all.
instead write a small char output function and have it perform the output through the uart.
do not use signals, instead use interrupts
the resulting application will not run on your PC., but, once loaded, will run on the 256k device
do not call sleep(), rather write your own function that uses a device timer peripheral, that sets the timer and puts the device into powerdown mode.
the time interrupt needs to bring the device out of the powerdown mode.
in the makefile, specifically set the size of the stack, heap, etc.
have the link step output a .map file.  study that map file until you understand everything in it.
use a compiler/linker that is specific for the embedded device
you probably will need to include a function that initializes the peripherals on the device, like the clock, the uart, the timer, the watchdog, and any other built in peripherals that the code actually uses.
you will need a file that allocates the interrupt table, and a small function to handle each of the interrupts, even though most of those functions will do nothing beyond clearing the appropriate interrupt pending flag and returning from the interrupt
you will probably need a function to periodically refresh the watchdog, conditionally, depending on an indication that the main function is still cycling regularily.  I.E the main function loop and the initialization function will refresh the watchdog