text:
Q: Pdf File In asset folder not open in thirdparty app Hi I am new in android  i have some PDF file that exist in this path asset/pdf/example.pdf
when i try PDF file  with this code
Intent intent = new Intent(Intent.ACTION_VIEW);
    File file = new File("file:///android_asset/pdf/example.pdf");
    intent.setDataAndType( Uri.fromFile( file ), "application/pdf" );
    startActivity(intent);

i get  this error & know it's because third party has no access to file
what is solution?

A:
know it's because third party has no access to file

file:///android_asset/ only works for WebView AFAIK.

what is solution?

You can use my StreamProvider, which offers a ContentProvider that can serve a file from assets/.
Or, you can implement your own ContentProvider that can serve the file from assets/.
Or, you can copy the asset to a local file (e.g., in getFilesDir() or getCacheDir()), then use FileProvider to serve that local file.


text:
Q: Access property in ListView that is not coming from ItemsSource My ListView is bound to MyTexts list. Nevertheless i need to bind TextCell's Text to property that is not comming from Texts (StandAloneProperty). How can i do that?
<ListView
            SelectedItem="{Binding SelectedText, Mode=TwoWay}"
            ItemsSource="{Binding MyTexts}">
            <ListView.ItemTemplate>
                <DataTemplate>
                    <TextCell
                        Text="{Binding StandAloneProperty, StringFormat='Value: {0}'}"
                        TextColor="{Binding Color}"
                    />
                </DataTemplate>
            </ListView.ItemTemplate>
</ListView>

A: Set your binding Source to the current page, and access to StandAloneProperty, from BindingContext which is your ViewModel.
<ContentPage x:Name="pageRef"
...

<ListView
            SelectedItem="{Binding SelectedText, Mode=TwoWay}"
            ItemsSource="{Binding MyTexts}">
            <ListView.ItemTemplate>
                <DataTemplate>
                    <TextCell
                        Text="{Binding Source={x:Reference pageRef} Path=BindingContext.StandAloneProperty, StringFormat='Value: {0}'}"
                        TextColor="{Binding Color}"
                    />
                </DataTemplate>
            </ListView.ItemTemplate>
</ListView>

redpajama_set_name: RedPajamaStackExchange


text:
Q: roblox lua script not activating so i have this code
local player = game.Players.LocalPlayer
local unitFrame = script.Parent
local buttona = unitFrame.buttonA
local sprinting = true

unitFrame.Title.Text = "Perks"
local function onButtonAClick()
    unitFrame.Title.Text = "perks"
end

local function sprintButton()
    if sprinting == false then
        sprinting = true
        player.Character.Humanoid.WalkSpeed = 20
        unitFrame.buttonA.Text = "strinting"
    end
    if sprinting == true then
        sprinting = false
        player.Character.Humanoid.WalkSpeed = 16
        unitFrame.buttonA.Text = "walking"
    end
end

buttona.MouseButton1Click:connect(sprintButton)

what i am trying to do is make a sprinting toggle program. The only problem is that it will work once then not work at all. i can click it and it changes the text then when i click it again it does nothing. i want it to be able to work every time you press it.

A: In the function you test 2 if statements. If sprinting is false, and if it it is true.
The key to understanding your problem is that your if statements counteract eachother.
Let's walk through this, first it detects if it's false. No, sprinting is not false. Then if checks if it's true. It is! So it sets it to false.
Great so far, right? Well here's your problem. When you try it again, sprinting is false. So the first if statement is run, and it sets it to true. But then, ANOTHER if statement is run immediately after. Since it's now true, this runs, setting it to false. It appears nothing happened.
Your solution? Take out the end to the first if statement, and replace the second if to an elseif. This way once one statement evaluated to true, it won't evaluate the next.

A: Your logic is not correct. As warspyking said, you have an issue with your conditionals. Fix this by adding an elseif statement instead.
local function sprintButton()
    if not sprinting then
        sprinting = true
        player.Character.Humanoid.WalkSpeed = 20
        unitFrame.buttonA.Text = "sprinting"
    elseif sprinting then
        sprinting = false
        player.Character.Humanoid.WalkSpeed = 16
        unitFrame.buttonA.Text = "walking"
    end
end


text:
Q: How to get the value of a map from a key which is a POJO I got the following function
Map<MyClass, String> someFunction() {
    Map<MyClass, String> result = new HashMap<>();
    return result.put(new MyClass("someString"), "someOtherString"));
}

The implementation of MyClass looks like the following:
public class MyClass{

    String string;

    public MyClass(String string) {
        this.string = string;
    }

    public void setString(String string) {
        this.string = string;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((string== null) ? 0 : string.hashCode());
        return result;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj) {
            return true;
        }
        if (obj == null) {
            return false;
        }
        if (getClass() != obj.getClass()) {
            return false;
        }
        MyClass other = (MyClass) obj;
        if (string== null) {
            if (other.string!= null) {
                return false;
            }
        } else if (!string.equals(other.string)) {
            return false;
        }
        return true;
    }

}

In my test I am doing the following:
@Test
public void test() {
    Map<MyClass, String> outcome = classUnderTest.someFunction();

    assertThat(outcome.get(new MyClass("someString")), is("someOtherString"));
}

But this test fails, because actual is null.
If I try the following:
assertThat(outcome.keySet(), hasItem(MY_CLASS));

this also fails, telling me, that these are different intantiations. I even tried to debug my test, but it never reaches the equals method. Can you tell me what is happening here?

A: In your function you are returning null
From the JavaDoc for HashMap:

public V put(K key, V value)

Associates the specified value with the specified key in this map. If the map previously contained a mapping for the key, the old value is replaced.

Specified by:
    put in interface Map<K,V>
Overrides:
    put in class AbstractMap<K,V>
Parameters:
    key - key with which the specified value is to be associated
    value - value to be associated with the specified key
Returns:
    the previous value associated with key, or null if there was no mapping for key. (A null return can also indicate that the map previously associated null with key.)

put() returns what used to be there, not what you just put there

A: Are you sure, that your method doesn't modify the objecT? I think, that someFunction replaces the string in MyClass. That causes that your object of MyClass return another hashCode.
A HashMap works like that:
put:

*

*compute hashCode of the key. Store value under that hashCode

get:

*

*compute hashCode of the key. Search for a value with that hashCode. If there is a value, then maybe call equals.

So: never use mutable values as key! Otherwise, you may lose your data (or make it difficult to resolve)
Just try to execute this test, it should be green
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertThat;

import java.util.HashMap;
import java.util.Map;

import org.junit.Test;

public class SomeTest {

    Map<MyClass, String> someFunction() {
        Map<MyClass, String> result = new HashMap<>();
        result.put(new MyClass("someString"), "someOtherString");
        return result;
    }

    @Test
    public void test() {
        Map<MyClass, String> outcome = someFunction();

        assertThat(outcome.get(new MyClass("someString")), is("someOtherString"));
    }

    public static class MyClass {

        String string;

        public MyClass(String string) {
            this.string = string;
        }

        public void setString(String string) {
            this.string = string;
        }

        @Override
        public int hashCode() {
            final int prime = 31;
            int result = 1;
            result = prime * result + ((string == null) ? 0 : string.hashCode());
            return result;
        }

        @Override
        public boolean equals(Object obj) {
            if (this == obj) {
                return true;
            }
            if (obj == null) {
                return false;
            }
            if (getClass() != obj.getClass()) {
                return false;
            }
            MyClass other = (MyClass) obj;
            if (string == null) {
                if (other.string != null) {
                    return false;
                }
            } else if (!string.equals(other.string)) {
                return false;
            }
            return true;
        }

    }
}

but if you modify MyClass object after it was added to Map, the test became red:
Map<MyClass, String> someFunction() {
    Map<MyClass, String> result = new HashMap<>();
    MyClass key = new MyClass("someOldString");
    result.put(key, "someOtherString");
    key.setString("someString");
    return result;
}


text:
Q: mysql_num_rows() does not work with SUM()? Using PHP mysql_num_rows() returns "1" when running the query below on the table below when there are no matching rows present.
Upon testing I found out that the problem happens when I use the SUM() function in the query. If I take SUM() out of the query mysql_num_rows() returns "0" like it should.
Is there something else I should use instead of mysql_num_rows() to find out if there is a matching row in the table?
Table:
name | students_money | grade
George | 5 | A
Bill | 10 | A
Dan | 7 | A

Code:
$sql = "SELECT SUM(students_money) AS sum_money FROM students_table WHERE name = 'Tom' AND name = 'Jack'";
$result = @mysql_query($sql, $con) or die(mysql_error());

$num_rows = mysql_num_rows($result);

if ($num_rows < 1) {

    echo "not everyone has paid";
    exit;

}

while($row = mysql_fetch_array($result)) {

    $sum_money = $row[sum_money];
    $total = $total + $sum_money;

}

A: SUM() is an aggregate function.  It takes all the rows that are returned for a group and adds them up.
Since you do not have a GROUP BY clause, it is adding up the values of all rows, even if there are none.  It is then returning the total as a single row, so there should only be 1 row.
If you clarify what you want returned, I can try to help you write a statement to return it.

A: mysql_num_rows() tells you the number of rows returned by the database query. There is always a one row return in your case because there is always one a sum. The sum may be 0 of course.
It may be a good idea to test your query in the mysql query browser. Perhaps you are looking for something like this?
SELECT name, SUM(students_money) AS sum_money
FROM students_table
GROUP BY name;

This will group the sums on a per name basis. To skip 0 sums you can add this:
HAVING sum_money > 0;


text:
Q: Dynamic Result Redirection in Struts 2 How to redirect to dynamic URL given page which value stored in variable in Struts 2?
I am performing Dynamic Method Invocation in struts 2. When LoginCheck() method executes and returns "Error", I want to redirect to Login.jsp. And following are my methods of controller:
 public String LoginCheck() throws Exception {
    setrURL("Login.jsp");
    System.out.println(cmodel.Login());
    System.out.println("Page = " + rURL);
    return (cmodel.Login()) ? "LSuccess" : "Error";
}

And it is navigating to wrong page.
Struts.xml:
<struts>
<!-- Configuration for the default package. -->
<constant name="struts.enable.DynamicMethodInvocation" value="true"></constant>
<package name="default" extends="struts-default">
    <interceptors>
        <interceptor name="RegValidate" class="Interceptors.RegValidateInterceptor"></interceptor>
    </interceptors>
    <action name="regAction" class="Controller.ClientController">
        <interceptor-ref name="RegValidate"></interceptor-ref>
        <result name="RSuccess">Login.jsp</result>
        <result name="LSuccess">Home.jsp</result>
        <result name="Error" type="redirect">${rURL}</result>
    </action>
</package>


text:
Q: Inconsistent subscription behaviour in Chrome client I'm registering my clients with a SignalR hub as shown here:
        self.connect = () => {
            hub = $.connection.instantMessageHub;
            hub.client.receiveMessage = receiveMessage;
            hub.client.receiveCommand = receiveCommand;
            $.connection.hub.logging = true;
            $.connection.hub.start();
        }

In Chrome, on initial page load or soft reload (F5) the client does not subscribe to the hub therefore no messages are being received. Turning on logging verifies this i.e. the following line does not display:
[17:12:50 GMT+0100 (GMT Standard Time)] SignalR: Client subscribed to hub 'instantmessagehub'.
However doing a hard reload (Ctrl-F5) connects the Chrome client to the hub. This same code works fine in IE and Firefox in all scenarios, and is definitely being hit when the Chrome client fails to subscribe.
So what would be causing this inconsistent hub subscription behaviour in Chrome?

A: After stepping through the SignalR code I realised that the connection was being started twice due to calling...
$.connection.hub.start();

... in two separate places as I was trying to initialise two separate hubs.
I chose to merge the two hubs into one in this instance as it made more sense anyway.
I'm unsure why this issue was isolated to Chrome however...


text:
Q: Angular 6 - Can't use ngModel I'm using Angular 6. And I want to use ngModel like so:
<input type="text" [(ngModel)]="textValue">

On the html I was getting the following error:
Can't bind to 'ngModel' since it isn't a known property of 'input'

When I searched I learnt that I have to import FormsModule. So in my package json I added the angular forms like so:
"dependencies": {
        "@angular/core": "^6.0.4",
        "@angular/forms": "^0.2.0"
   ...

Did a npm install and then on the app.module,
I added FormsModule to imports,
imports: [
        CommonModule,
        FormsModule,
    ],

But when I tried importing FormsModule from angular/forms,
import { FormsModule } from '@angular/forms';

It says:
Module '"PATH-TO-PROJECT/node_modules/@angular/forms/index"' has no exported member 'FormsModule'

What should I do to get mgModel working on Angular 6?

A: On your line of package.json:
"@angular/forms": "0.2.0"

change to:
"@angular/forms": "0.3.0"

run again:
npm install

A: Change in package.json:
"@angular/forms": "0.3.0"

and then npm install.
There is important information is that whenever we use [(ngModel)] in html tags to bind data then we must have to give name to that tag:

otherwise it will throw error: ngModel must have name property.


text:
Q: Changing .text() depending on the window size with jQuery I've got a simple function that finds and shows the first sentence of every paragraph:
function firstSentence(){
  $('p').each(function(){
      var p = $(this).text();
      var s = p.split('.');
      var f = s[0];
      $(this).text(f + '...');
     });
}

And I use it when the window size is less than 600:
$(window).resize(function(){
    if ($(window).width() < 600) {
    firstSentence();
     } else {
        // back to normal please!
    }
});

However, when the user resizes their window above 600, the content obviously does not change back.
What is the best way for the content to be reverted, if the user resizes to a larger window ( > 600)?

A: Before you do anything else, you need to store the original text in each paragraph. E.g. like this:
var originalTexts = $('p').map(function () {
    return $(this).text();
});

and then, for your "back to normal code":
$('p').each(function (key) {
    $(this).text(originalTexts[key]);
});

A: I'm not certain this is perfect but it will give you an idea
function origSentence(){
$('p').each(function(){
var o = $(this).text()}}

then
} else {
prigSentence()

Not forgetting this all over again on (doc).rdy.


text:
Q: scatterplot with Xcode for iPhone data not sync with axis and major thick not shown I'm a beginner in Stackoverflow and Xcode for iPhone.
English is not my native language, so please bear with me.
I've been trying to make a graph between dates (x axis) and the Fuel Economy value (y axis).
I'm using core plot 1.4.
My problem are:

*

*The data somehow is not sync directly to x axis.

*Major checklist somehow is not shown. (solved)

*Is there any way to make the graph only shows the positif axis? (solved)

I've doing a lot of NSLog to debug the data. I've search google (including this site) for the tutorial of how to use the custom label and how to make scatter plot graph).
I have the following data:
(
    {
    0 = "31-Jan-2014";
    1 = 10;
},
    {
    0 = "02-Feb-2014";
    1 = "10.07";
},
    {
    0 = "24-Feb-2014";
    1 = "8.75";
}
)

I've got strange result with above data. Please see the included graph
this is the picture of my graph:

in the graph, the y data is not mapped to x axis.
here's the relevant code
    - (NSUInteger)numberOfRecordsForPlot:(CPTPlot *)plot
{
    NSLog(@"Number of Records for Plot = %lu",(unsigned long)[self.plotData count]);
    return [_plotData count];
}

- (NSNumber *)numberForPlot:(CPTPlot *)plot field:(NSUInteger)fieldEnum recordIndex:(NSUInteger)idx
{
    //NSDecimalNumber *result = [[_plotData objectAtIndex:idx]objectForKey:[NSNumber numberWithInt:fieldEnum]];
    NSNumber *result;
        switch (fieldEnum) {
        case CPTScatterPlotFieldX:
//                NSDate * observationDate = [[_plotData objectAtIndex:idx]objectForKey:[NSNumber numberWithInt:fieldEnum]];
//                NSTimeInterval secondsSince1970 = [_observationDate timeIntervalSince1970];
                result = [[_plotData objectAtIndex:idx]objectForKey:[NSNumber numberWithInt:fieldEnum]];

            break;
        case CPTScatterPlotFieldY:
            result = [[_plotData objectAtIndex:idx] objectForKey:[NSNumber numberWithInt:fieldEnum]];
}

//result = [[_plotData objectAtIndex:idx] objectForKey:[NSNumber numberWithInt:fieldEnum]];
     NSLog(@"Number tobe  Plot with index = %@ %lu, %lu",result,(unsigned long)idx,(unsigned long)fieldEnum);
    return result;

}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self initPlot];

    // Do any additional setup after loading the view.
}

- (void)initPlot
{
    //NSDate *refDate       = [NSDate dateWithNaturalLanguageString:@"12:00 Oct 29, 2009"];
    [self fetchResultOneWeek];
    [self configureHost];
    [self configureFEGraph];
    [self configurePlots];
    [self configureAxis];
}

- (void)configureHost
{
    CGRect frame1 = CGRectMake(0,80,320,200);
    FESubView = [[CPTGraphHostingView alloc]initWithFrame:frame1];
    FESubView.allowPinchScaling = YES;
    [self.view addSubview:FESubView];
    CGRect frame2 = CGRectMake(0,410,320,400);
    GasPriceSubView = [[CPTGraphHostingView alloc]initWithFrame:frame2];
    GasPriceSubView.allowPinchScaling = YES;
    [self.view addSubview:GasPriceSubView];
}

- (void)configureFEGraph
{
    CPTGraph *graph = [[CPTXYGraph alloc]initWithFrame:FESubView.bounds];
    [graph applyTheme:[CPTTheme themeNamed:kCPTStocksTheme]];
    FESubView.hostedGraph = graph;

    graph.title = @"Fuel Economy Graph";
    CPTMutableTextStyle *titleStyle = [CPTMutableTextStyle textStyle];
    titleStyle.color = [CPTColor whiteColor];
    titleStyle.fontName = @"Helvetica-Bold";
    titleStyle.fontSize = 14.0f;
    graph.titleTextStyle = titleStyle;
    graph.titlePlotAreaFrameAnchor = CPTRectAnchorTop;
    graph.titleDisplacement = CGPointMake(0.0f, 10.0f);

    // 4 - Set padding for plot area
    [graph.plotAreaFrame setPaddingLeft:10.0f];
    [graph.plotAreaFrame setPaddingBottom:10.0f];
    [graph.plotAreaFrame setPaddingTop:10.0f];
    [graph.plotAreaFrame setPaddingRight:10.0f];

    // 5 - Enable user interactions for plot space
    CPTXYPlotSpace *plotSpace = (CPTXYPlotSpace *) graph.defaultPlotSpace;
    plotSpace.allowsUserInteraction = YES;

}

- (void)configurePlots
{
    NSMutableArray *dataTobePlotted = [NSMutableArray array];

    NSUInteger i;
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
    [dateFormatter setDateFormat:@"dd-MMM-YYY"];
    [dateFormatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"GMT+0:07"]];
    //NSTimeInterval oneDay = 24 * 60 * 60;

   for (i = 0;i < [[self.fullTransaction valueForKey:@"tDate"]count]; i++)
    {
        NSDate *observationDate = [[self.fullTransaction valueForKey:@"tDate"]objectAtIndex:i];
         NSLog(@"observationDate is : %@",observationDate);
        NSTimeInterval x = [observationDate timeIntervalSince1970];
        NSLog(@"x is : %f",x);
        id y = [[self.fullTransaction valueForKey:@"tFuelEconomy"]objectAtIndex:i];
         NSLog(@"y is : %@",y);
        [dataTobePlotted addObject:[NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithDouble:x],[NSNumber numberWithInt:CPTScatterPlotFieldX],y,[NSNumber numberWithInt:CPTScatterPlotFieldY],nil]];
        //[dataTobePlotted addObject:[NSDictionary dictionaryWithObjectsAndKeys:[NSDecimalNumber numberWithFloat:x],[NSNumber numberWithInt:CPTScatterPlotFieldX],y,[NSNumber numberWithInt:CPTScatterPlotFieldY],nil]];
        NSLog(@" int X is %@",[NSNumber numberWithInt:CPTScatterPlotFieldX]);
        NSLog(@" int Y is %@",[NSNumber numberWithInt:CPTScatterPlotFieldY]);
        NSLog(@"ScatterPlotField X is %@",[NSNumber numberWithInt:CPTScatterPlotFieldX]);
        NSLog(@"ScatterPlotField Y is %@",[NSNumber numberWithInt:CPTScatterPlotFieldY]);
        NSLog(@"Data to be Plotted: %@",dataTobePlotted);
    }
    self.plotData = dataTobePlotted;

    CPTGraph *graph = FESubView.hostedGraph;
    [graph applyTheme:[CPTTheme themeNamed:kCPTStocksTheme]];

    CPTXYPlotSpace *plotSpace = (CPTXYPlotSpace *)graph.defaultPlotSpace;
        //create plot
    CPTScatterPlot *fePlot = [[CPTScatterPlot alloc]init];
    fePlot.dataSource = self;
    CPTColor *feColor = [CPTColor greenColor];
    [graph addPlot:fePlot];

    //setup plot space
    [plotSpace scaleToFitPlots:[NSArray arrayWithObjects: fePlot,Nil]];
    plotSpace.xRange = [CPTPlotRange plotRangeWithLocation:CPTDecimalFromString(@"3.0") length:CPTDecimalFromString(@"10.0")];
    plotSpace.yRange = [CPTPlotRange plotRangeWithLocation:CPTDecimalFromString(@"8.0") length:CPTDecimalFromString(@"2.0")];

    //set up plot space
    //[plotSpace scaleToFitPlots:[NSArray arrayWithObjects:fePlot,nil]];
    CPTMutablePlotRange *xRange = [plotSpace.xRange mutableCopy];
    [xRange expandRangeByFactor:CPTDecimalFromCGFloat(2.0f)];
    plotSpace.xRange = xRange;
    CPTMutablePlotRange *yRange = [plotSpace.yRange mutableCopy];
    [yRange expandRangeByFactor:CPTDecimalFromCGFloat(5.0f)];
    plotSpace.yRange = yRange;

//    //create styles and symbols
    CPTMutableLineStyle *feLineStyle = [fePlot.dataLineStyle mutableCopy];
    CPTColor *areaColor = [CPTColor colorWithComponentRed:0.3 green:1.0 blue:0.3 alpha:0.3];
    CPTGradient *areaGradient = [CPTGradient gradientWithBeginningColor:areaColor endingColor:[CPTColor clearColor]];
    areaGradient.angle = -90.0f;
    CPTFill *areaGradientFill = [CPTFill fillWithGradient:areaGradient];
    fePlot.areaFill = areaGradientFill;

    feLineStyle.lineWidth = 2.5;
    feLineStyle.lineColor = feColor;
    fePlot.dataLineStyle = feLineStyle;
    CPTMutableLineStyle *feSymbolLineStyle = [CPTMutableLineStyle lineStyle];
    feSymbolLineStyle.lineColor = feColor;
    CPTPlotSymbol *feSymbol = [CPTPlotSymbol ellipsePlotSymbol];
    feSymbol.fill = [CPTFill fillWithColor:feColor];
    feSymbol.lineStyle = feSymbolLineStyle;
    feSymbol.size = CGSizeMake(6.0f, 6.0f);
    fePlot.plotSymbol = feSymbol;
}

- (void)configureAxis
{
  // 1 - Create styles
        // 2 - Get axis set
    CPTMutableTextStyle *axisTitleStyle = [CPTMutableTextStyle textStyle];
    axisTitleStyle.color = [CPTColor whiteColor];
    axisTitleStyle.fontName = @"Helvetica-Bold";
    axisTitleStyle.fontSize = 12.0f;
    CPTMutableLineStyle *axisLineStyle = [CPTMutableLineStyle lineStyle];
    axisLineStyle.lineWidth = 2.0f;
    axisLineStyle.lineColor = [CPTColor whiteColor];
    CPTMutableTextStyle *axisTextStyle = [[CPTMutableTextStyle alloc] init];
    axisTextStyle.color = [CPTColor whiteColor];
    axisTextStyle.fontName = @"Helvetica-Bold";
    axisTextStyle.fontSize = 11.0f;
    CPTMutableLineStyle *tickLineStyle = [CPTMutableLineStyle lineStyle];
    tickLineStyle.lineColor = [CPTColor whiteColor];
    tickLineStyle.lineWidth = 2.0f;
    CPTMutableLineStyle *gridLineStyle = [CPTMutableLineStyle lineStyle];
    tickLineStyle.lineColor = [CPTColor blackColor];
    tickLineStyle.lineWidth = 1.0f;
    CPTMutableTextStyle *labelXTextStyle = [CPTMutableTextStyle textStyle];
    labelXTextStyle.fontName = @"Helvetica";
    labelXTextStyle.fontSize = 10;
    labelXTextStyle.color = [CPTColor whiteColor];

    // 2 - Get Axis Set
    CPTXYAxisSet *axisSet = (CPTXYAxisSet *) FESubView.hostedGraph.axisSet;

    // 3 Configure x-Axis
    CPTXYAxis *x          = axisSet.xAxis;
    x.orthogonalCoordinateDecimal = CPTDecimalFromString(@"4");
    x.title = @"Date";
    x.titleTextStyle = axisTitleStyle;
    x.titleOffset = 47.0f;
    //x.title = @"Date";
    x.minorTicksPerInterval       = 0;
    x.majorTickLength = 10.0f;
    x.tickDirection = CPTSignPositive;

    //NSArray *customTickLocations = [NSArray arrayWithObjects:[NSDecimalNumber numberWithInt:5], [NSDecimalNumber numberWithInt:10], [NSDecimalNumber numberWithInt:10], [NSDecimalNumber numberWithInt:15],
    //                                [NSDecimalNumber numberWithInt:20], [NSDecimalNumber numberWithInt:25],[NSDecimalNumber numberWithInt:30],nil];

    NSInteger i;
    NSMutableArray *customTickLocations = [NSMutableArray array];
    for (i = 0; i < [[self.fullTransaction valueForKey:@"tDate"]count];i++)
    {
        [customTickLocations addObject:[NSDecimalNumber numberWithInt:((i+1)*5)]];
    }

    CPTPlotRange *xAxisRange=[CPTPlotRange plotRangeWithLocation:CPTDecimalFromString(@"0.0") length:CPTDecimalFromString(@"24.0")];
      x.visibleRange=xAxisRange;

    NSLog(@"dates are %@", [self.fullTransaction valueForKey:@"tDate"]);
    NSLog(@"Transaction FE %@", [self.fullTransaction valueForKey:@"tFuelEconomy"]);
    NSMutableArray *customLabels = [NSMutableArray arrayWithCapacity:[self.plotData count]];
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
    [dateFormatter setDateFormat:@"dd-MMM-YYY"];
    [dateFormatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"GMT+0:07"]];
    NSMutableSet *xLocations = [NSMutableSet setWithCapacity:[[self.fullTransaction valueForKey:@"tDate"]count]];
    x.labelingPolicy=CPTAxisLabelingPolicyNone;
    x.majorIntervalLength = [[NSDecimalNumber decimalNumberWithString:@"1"] decimalValue];
    NSInteger location;
    for (location = 0; location < [[self.fullTransaction valueForKey:@"tDate"]count];location++)
    {
        CPTAxisLabel *newLabel = [[CPTAxisLabel alloc] initWithText: [dateFormatter stringFromDate:[[self.fullTransaction valueForKey:@"tDate"] objectAtIndex:location]] textStyle:labelXTextStyle];
        NSLog(@"Custom Labels = %@",newLabel);
        NSLog(@"Real Date = %@",[[self.fullTransaction valueForKey:@"tDate"] objectAtIndex:location]);
        NSLog(@"After assigned date = %@",[dateFormatter stringFromDate:[[self.fullTransaction valueForKey:@"tDate"] objectAtIndex:location]]);
        newLabel.tickLocation = CPTDecimalFromInt([[customTickLocations objectAtIndex:location] integerValue]);
        newLabel.offset =  2;
        newLabel.rotation = (1*M_PI)/4;
        [customLabels addObject:newLabel];
        [xLocations addObject:[NSNumber numberWithInteger:[[customTickLocations objectAtIndex:location] integerValue]]];

    }
    x.axisLabels = [NSSet setWithArray:customLabels];
    NSLog(@"Custom Labels = %@",customLabels);
    x.majorTickLocations = xLocations;
    //x.majorTickLocations = customTickLocations;
    x.majorTickLength = 5.0f;
    NSLog(@"Major TickLocations: %@",customTickLocations);

    CPTXYAxis *y = axisSet.yAxis;
    //y.orthogonalCoordinateDecimal = CPTDecimalFromCGFloat(0.0);
    y.majorIntervalLength         = CPTDecimalFromString(@"1.0");
    y.minorTicksPerInterval       = 5;
    y.majorTickLength = 5.0f;
    y.preferredNumberOfMajorTicks = 5;
    y.labelTextStyle = labelXTextStyle;
}

The following is the result of nslog for the id x and id y data
2014-02-25 16:09:01.855 Fuel Eco[12079:70b] x is : 31-Jan-2014
2014-02-25 16:09:01.855 Fuel Eco[12079:70b] y is : 10
2014-02-25 16:09:01.855 Fuel Eco[12079:70b]  int X is 0
2014-02-25 16:09:01.856 Fuel Eco[12079:70b]  int Y is 1
2014-02-25 16:09:01.856 Fuel Eco[12079:70b] ScatterPlotField X is 0
2014-02-25 16:09:01.856 Fuel Eco[12079:70b] ScatterPlotField Y is 1
2014-02-25 16:09:01.857 Fuel Eco[12079:70b] Data to be Plotted: (
        {
        0 = "31-Jan-2014";
        1 = 10;
    }
)
2014-02-25 16:09:01.857 Fuel Eco[12079:70b] x is : 02-Feb-2014
2014-02-25 16:09:01.857 Fuel Eco[12079:70b] y is : 10.07
2014-02-25 16:09:01.858 Fuel Eco[12079:70b]  int X is 0
2014-02-25 16:09:01.858 Fuel Eco[12079:70b]  int Y is 1
2014-02-25 16:09:01.858 Fuel Eco[12079:70b] ScatterPlotField X is 0
2014-02-25 16:09:01.859 Fuel Eco[12079:70b] ScatterPlotField Y is 1
2014-02-25 16:09:01.859 Fuel Eco[12079:70b] Data to be Plotted: (
        {
        0 = "31-Jan-2014";
        1 = 10;
    },
        {
        0 = "02-Feb-2014";
        1 = "10.07";
    }
)
2014-02-25 16:09:01.859 Fuel Eco[12079:70b] x is : 24-Feb-2014
2014-02-25 16:09:01.860 Fuel Eco[12079:70b] y is : 8.75
2014-02-25 16:09:01.860 Fuel Eco[12079:70b]  int X is 0
2014-02-25 16:09:01.860 Fuel Eco[12079:70b]  int Y is 1
2014-02-25 16:09:01.861 Fuel Eco[12079:70b] ScatterPlotField X is 0
2014-02-25 16:09:01.861 Fuel Eco[12079:70b] ScatterPlotField Y is 1
2014-02-25 16:09:01.861 Fuel Eco[12079:70b] Data to be Plotted: (
        {
        0 = "31-Jan-2014";
        1 = 10;
    },
        {
        0 = "02-Feb-2014";
        1 = "10.07";
    },
        {
        0 = "24-Feb-2014";
        1 = "8.75";
    }
)

Below is the result of the nslog to show the result of "- (NSNumber *)numberForPlot:(CPTPlot *)plot field:(NSUInteger)fieldEnum recordIndex:(NSUInteger)idx" with the data,idx,fieldEnum.
2014-02-25 16:09:01.862 Fuel Eco[12079:70b] Number of Records for Plot = 3
2014-02-25 16:09:01.862 Fuel Eco[12079:70b] Number of Records for Plot = 3
2014-02-25 16:09:01.863 Fuel Eco[12079:70b] Number tobe  Plot with index = 31-Jan-2014 0, 0
2014-02-25 16:09:01.863 Fuel Eco[12079:70b] Number tobe  Plot with index = 02-Feb-2014 1, 0
2014-02-25 16:09:01.863 Fuel Eco[12079:70b] Number tobe  Plot with index = 24-Feb-2014 2, 0
2014-02-25 16:09:01.864 Fuel Eco[12079:70b] Number of Records for Plot = 3
2014-02-25 16:09:01.864 Fuel Eco[12079:70b] Number tobe  Plot with index = 10 0, 1
2014-02-25 16:09:01.864 Fuel Eco[12079:70b] Number tobe  Plot with index = 10.07 1, 1
2014-02-25 16:09:01.865 Fuel Eco[12079:70b] Number tobe  Plot with index = 8.75 2, 1
2014-02-25 16:09:01.865 Fuel Eco[12079:70b] Number of Records for Plot = 3

Thanks all
UPDATE ***
I rewrote the code to become like this, and it works:
-(NSNumber *)numberForPlot:(CPTPlot *)plot field:(NSUInteger)fieldEnum recordIndex:(NSUInteger)index
{
    switch (fieldEnum)
    {
        case CPTScatterPlotFieldX:
        {
            NSDecimalNumber *num = [[plotData objectAtIndex:index] objectForKey:[NSNumber numberWithInt:fieldEnum]];
            return num;
        }
        case CPTScatterPlotFieldY:
        {
            if ([plot.identifier isEqual:@"Honda Plot"])
            {
                NSDecimalNumber *num = [[plotData1 objectAtIndex:index] objectForKey:[NSNumber numberWithInt:fieldEnum]];
                return num;
            }
            else
            {
                NSDecimalNumber *num = [[plotData objectAtIndex:index] objectForKey:[NSNumber numberWithInt:fieldEnum]];
                return num;
            }
        }
    }
    return nil;
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self fetchResult];
    [self filterarray];
    [self filterArray1];

    //CGRect frame1 = CGRectMake(0,200,300,600);
    [self generateData];
    //FESubView = [[CPTGraphHostingView alloc]initWithFrame:frame1];
    [self renderInLayer:FESubView withTheme:Nil animated:NO];
    }

-(void)generateData
{

    if ( !plotData ) {
        //const NSTimeInterval oneDay = 24 * 60 * 60 ;
        gregorian = [self setCalendar];
       NSDateComponents *dateComponents = [gregorian components:(NSYearCalendarUnit | NSMonthCalendarUnit  | NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit     ) fromDate:[[self.fullTransaction valueForKey:@"tDate" ] objectAtIndex:0]];
NSDate *refDate = [gregorian dateFromComponents:dateComponents];

        NSDate *dataDate = [[NSDate alloc]init];

        NSDateComponents *comps;

        int days;

        // Add some data
        NSMutableArray *newData = [NSMutableArray array];
        NSMutableArray *newData1 = [NSMutableArray array];
        NSUInteger i;

        for ( i = 0; i < [[self.fullTransaction valueForKey:@"tDate"]count]; i++ ) {

            dataDate = [[self.fullTransaction valueForKey:@"tDate"]objectAtIndex:i];
           NSLog(@"RefDate is: %@",refDate);
            NSLog(@"DateDate is: %@",dataDate);
            comps = [gregorian components:NSDayCalendarUnit fromDate:refDate toDate:dataDate  options:0];
            days = [comps day];
            NSTimeInterval x = oneDay *days;
            //id y             = [[self.fullTransaction valueForKey:@"tFuelEconomy"]objectAtIndex:i];
            int counts = [self.filteredTransaction count];
            id y;
            id z;
            int count1 = [self.filteredTransaction1 count];
            if (i < counts)
            {
            y             = [[self.filteredTransaction valueForKey:@"tFuelEconomy"]objectAtIndex:i];
            }else y = NULL;
            if (i < count1)
            {
                z            = [[self.filteredTransaction1 valueForKey:@"tFuelEconomy"]objectAtIndex:i];
            }else z = NULL;

           [newData addObject:
             [NSDictionary dictionaryWithObjectsAndKeys:
              [NSDecimalNumber numberWithFloat:x], [NSNumber numberWithInt:CPTScatterPlotFieldX],
              y, [NSNumber numberWithInt:CPTScatterPlotFieldY],
              nil]];
            [newData1 addObject:
             [NSDictionary dictionaryWithObjectsAndKeys:
              [NSDecimalNumber numberWithFloat:x], [NSNumber numberWithInt:CPTScatterPlotFieldX],
              z, [NSNumber numberWithInt:CPTScatterPlotFieldY],
              nil]];
        }
        plotData = newData;
        plotData1 = newData1;
        NSLog(@"Data are: %@",plotData);
        NSLog(@"Data are: %@",plotData1);
    }
}

-(void)renderInLayer:(CPTGraphHostingView *)layerHostingView withTheme:(CPTTheme *)theme animated:(BOOL)animated
{
    // If you make sure your dates are calculated at noon, you shouldn't have to
    // worry about daylight savings. If you use midnight, you will have to adjust
    // for daylight savings time.
    CGRect frame1 = CGRectMake(10,150,320,250);
    FESubView = [[CPTGraphHostingView alloc]initWithFrame:frame1];
    FESubView.allowPinchScaling = YES;
    [self.view addSubview:FESubView];

    //NSDateComponents *dateComponents = [[NSDateComponents alloc] init];

    gregorian = [self setCalendar];
    NSDateComponents *dateComponents = [gregorian components:(NSYearCalendarUnit | NSMonthCalendarUnit  | NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit     ) fromDate:[[self.fullTransaction valueForKey:@"tDate" ] objectAtIndex:0]];

    NSDate *refDate = [gregorian dateFromComponents:dateComponents];

    NSLog(@"RefDate is :%@",refDate);

#if TARGET_IPHONE_SIMULATOR || TARGET_OS_IPHONE
    CGRect bounds = layerHostingView.bounds;
#else
    CGRect bounds = NSRectToCGRect(layerHostingView.bounds);
#endif

    CPTGraph *graph = [[CPTXYGraph alloc] initWithFrame:bounds];
    [graph applyTheme:[CPTTheme themeNamed:kCPTDarkGradientTheme]];
    FESubView.hostedGraph = graph;
    graph.title = @"Fuel Economy Graph";
    CPTMutableTextStyle *titleStyle = [CPTMutableTextStyle textStyle];
    titleStyle.color = [CPTColor whiteColor];
    titleStyle.fontName = @"Helvetica-Bold";
    titleStyle.fontSize = 14.0f;
    graph.titleTextStyle = titleStyle;
    graph.titlePlotAreaFrameAnchor = CPTRectAnchorTop;
    graph.titleDisplacement = CGPointMake(0.0f, 10.0f);
    // 4 - Set padding for plot area
    [graph.plotAreaFrame setPaddingLeft:40.0f];
    [graph.plotAreaFrame setPaddingBottom:65.0f];
    [graph.plotAreaFrame setPaddingTop:3.0f];
    [graph.plotAreaFrame setPaddingRight:3.0f];

    graph.legend = [CPTLegend legendWithGraph:graph];
    graph.legend.fill = [CPTFill fillWithColor:[CPTColor darkGrayColor]];
    graph.legend.cornerRadius = 5.0;
    graph.legend.swatchSize = CGSizeMake(25.0, 25.0);
    graph.legendAnchor = CPTRectAnchorCenter;

    graph.legendDisplacement = CGPointMake(2.40, 12.0);

    // Setup scatter plot space
    CPTXYPlotSpace *plotSpace = (CPTXYPlotSpace *)graph.defaultPlotSpace;
    NSTimeInterval xLow       = 0.0f;
    plotSpace.xRange = [CPTPlotRange plotRangeWithLocation:CPTDecimalFromFloat(xLow) length:CPTDecimalFromFloat(oneDay * 10)];
    plotSpace.yRange = [CPTPlotRange plotRangeWithLocation:CPTDecimalFromFloat(5.0) length:CPTDecimalFromFloat(10.0f)];

    //symbol

    CPTMutablePlotRange *xRange = [plotSpace.xRange mutableCopy];
    [xRange expandRangeByFactor:CPTDecimalFromCGFloat(1)];
//
    plotSpace.allowsUserInteraction = YES;

    // Create a plot that uses the data source method
    CPTScatterPlot *dataSourceLinePlot = [[CPTScatterPlot alloc] init];
    dataSourceLinePlot.identifier = @"Nisan Plot";
    CPTColor *feColor = [CPTColor redColor];
    CPTMutableLineStyle *feLineStyle = [dataSourceLinePlot.dataLineStyle mutableCopy];
    feLineStyle.lineWidth = 2.5;
    feLineStyle.lineColor = feColor;
    dataSourceLinePlot.dataLineStyle = feLineStyle;
    CPTMutableLineStyle *feSymbolLineStyle = [CPTMutableLineStyle lineStyle];
    feSymbolLineStyle.lineColor = feColor;
    CPTPlotSymbol *feSymbol = [CPTPlotSymbol ellipsePlotSymbol];
    feSymbol.fill = [CPTFill fillWithColor:feColor];
    feSymbol.lineStyle = feSymbolLineStyle;
    feSymbol.size = CGSizeMake(6.0f, 6.0f);
    dataSourceLinePlot.plotSymbol = feSymbol;
    CPTMutableTextStyle *feLabelStyle = [CPTMutableTextStyle textStyle];
    feLabelStyle.fontSize = 10;
    feLabelStyle.color = [CPTColor whiteColor];
    dataSourceLinePlot.labelTextStyle = feLabelStyle;
    dataSourceLinePlot.title = @"Nissan Terano";

    dataSourceLinePlot.dataSource = self;
    [graph addPlot:dataSourceLinePlot];

    CPTMutableTextStyle *axisTextStyle = [[CPTMutableTextStyle alloc] init];
    axisTextStyle.color = [CPTColor whiteColor];
    axisTextStyle.fontName = @"Helvetica-Bold";
    axisTextStyle.fontSize = 8.0f;
    CPTScatterPlot *dataSourceLinePlot1 = [[CPTScatterPlot alloc] init];
    dataSourceLinePlot1.identifier = @"Honda Plot";
    CPTColor *feColor1 = [CPTColor blueColor];
    CPTMutableLineStyle *feLineStyle1 = [dataSourceLinePlot1.dataLineStyle mutableCopy];
    feLineStyle1.lineWidth = 2.5;
    feLineStyle1.lineColor = feColor1;
    dataSourceLinePlot1.dataLineStyle = feLineStyle1;
    CPTMutableLineStyle *feSymbolLineStyle1 = [CPTMutableLineStyle lineStyle];
    feSymbolLineStyle1.lineColor = feColor1;
    CPTPlotSymbol *feSymbol1 = [CPTPlotSymbol ellipsePlotSymbol];
    feSymbol1.fill = [CPTFill fillWithColor:feColor1];
    feSymbol1.lineStyle = feSymbolLineStyle1;
    feSymbol1.size = CGSizeMake(6.0f, 6.0f);
    dataSourceLinePlot1.plotSymbol = feSymbol1;
    //CPTTextStyle *test = [CPTTextStyle textStyle];
    //test.fontSize = 12;
    CPTMutableTextStyle *feLabelStyle1 = [CPTMutableTextStyle textStyle];
    feLabelStyle1.fontSize = 10;
    feLabelStyle1.color = [CPTColor whiteColor];
    dataSourceLinePlot1.labelTextStyle = feLabelStyle1;

    dataSourceLinePlot1.dataSource = self;
    [graph addPlot:dataSourceLinePlot1];
dataSourceLinePlot1.title = @"Honda Jazz";
//
    // Axes
    CPTXYAxisSet *axisSet = (CPTXYAxisSet *)graph.axisSet;
    CPTXYAxis *x          = axisSet.xAxis;
    x.majorIntervalLength         = CPTDecimalFromFloat(oneDay);
    x.orthogonalCoordinateDecimal = CPTDecimalFromString(@"5");
    x.minorTicksPerInterval       = 0;
    x.labelTextStyle = axisTextStyle;
    //x.axisLineStyle = axisLineStyle;
    //x.axisLineStyle = feLabelStyle;
    dateFormatter = [self setDateFormatterLabel];
    //dateFormatter.dateStyle = kCFDateFormatterShortStyle;

    CPTTimeFormatter *timeFormatter = [[CPTTimeFormatter alloc] initWithDateFormatter:dateFormatter];
    timeFormatter.referenceDate = refDate;
    x.labelFormatter            = timeFormatter;
    x.labelRotation            = M_PI / 4;
    x.tickLabelDirection = CPTSignPositive;
    x.tickDirection = CPTSignPositive;
    //x.labelTextStyle = feLabelStyle;
    //x.visibleRange=plotSpace.xRange;
    x.labelOffset = -70;

    CPTXYAxis *y = axisSet.yAxis;
    y.majorIntervalLength         = CPTDecimalFromString(@"5.0");
    y.minorTicksPerInterval       = 10;
    y.orthogonalCoordinateDecimal = CPTDecimalFromString(@"-1");

    }

A: *

*I'm not sure what you mean. Can you explain the question more clearly?

*You never add any locations to the xLocations set. If the customTickLocations array contains all of the locations you need, just set the tick locations directly:
x.majorTickLocations = [NSSet setWithArray:customTickLocations];

*Why are you using -expandRangeByFactor:? If you know the plot range you want, just set it directly:
plotSpace.yRange = [CPTPlotRange plotRangeWithLocation:CPTDecimalFromDouble(0.0)
                                            length:CPTDecimalFromDouble(10.0)];


text:
Q: Parse JSON to deeply nested generic with jackson I've been trying all kinds of solutions to get this working. But without success.
I have a few classes like this
class Level1<T> {

    public Level2<T> l2;
}

class Level2<T> {

    public Level3<T> l3;
}

class Level3<T> {

    public List<T> objectsList;
}

T in this case can be any object, and should be possible to be resolved during runtime.
My JSON looks like this:
{
    "Level1": {
        "Level2": {
            "Level3": {
                "genericObject": [
                    {
                      "attribute1": ...,
                      "attribute2": ...
                    },
                    {
                      "attribute1": ...,
                      "attribute2": ...
                    }
                ]
            }
        }
    }
}

The JSON property "genericObject" changes its name and attributes depending of which kind of object I'm receiving.
I've tried defining in my ObjectMapper like this, in which I pass a Class object to my function (genericObjectClass):
JavaType javaType = TypeFactory.defaultInstance().constructParametricType(ArrayList.class, List.class, genericObjectClass);
javaType = TypeFactory.defaultInstance().constructParametricType(Level3.class, javaType);
javaType = TypeFactory.defaultInstance().constructParametricType(Level2.class, javaType);
javaType = TypeFactory.defaultInstance().constructParametricType(Level1.class, javaType);

Level1<genericObject> l1 = objectMapper.readValue(jsonString, javaType);

Tried solutions:
(de)serialising Nested Generics in Jackson
How to use Jackson with Generics
Is Jackson really unable to deserialize json into a generic type?

A: There are several things that you need to change

*

*Level1 object is not the root object, but a field. If you don't want to create one more wrapper object, use UNWRAP_ROOT_VALUE
mapper.enable(DeserializationFeature.UNWRAP_ROOT_VALUE);

*You don't need to constructParametricType for the whole object hierarchy, just construct it for top class in the chain
constructParametricType(Level1.class, genericObjectClass);

*Your json fields don't map to pojo fields. So you need to annotate your POJO fields with @JsonProperty("Level2") @JsonProperty("genericObject") and so on.
So your deserialization code should look like
ObjectMapper mapper = new ObjectMapper();
mapper.enable(DeserializationFeature.UNWRAP_ROOT_VALUE);

JavaType javaType = TypeFactory.defaultInstance()
         .constructParametricType(Level1.class, c);

mapper.readValue(json, javaType);

And classes look like
class Level1<T> {
    @JsonProperty("Level2")
    public Level2<T> l2;
}
class Level2<T> {
    @JsonProperty("Level3")
    public Level3<T> l3;
}
class Level3<T> {
    @JsonProperty("genericObject")
    public List<T> objectsList;
}

And here is full working gist demo


text:
Q: Why does dragging (drop/drag) element cause dropzone (div) to partially disappear? Using HTML5 Drag/Drop, when dragging element the dropzone partially disappears from UI, as seen in screenshot. The partial missing div in the image has a red boarder.  When I remove the "hr" tag, from the code below, it works and the div does NOT disappear when dragging element!  This is only happening in Chrome browser.  All the code is below.  Does anyone know why this is occurring?
<!DOCTYPE html>

<meta name="viewport" content="width=device-width" />
<title></title>

App status...

Drop Zone

object 1

object 2

object 3

<button onclick="readDropZone()">Get Object Data</button>

A: In my tests, even if I deleted the
, the error was still reproduced. I noticed, that it occurs after changing h2#app_status text. If you wrap div#drop_zone and all next elements like div#object... with div that has inline-block as display style, then there will be no such disappearing.

object 1

object 2

object 3


text:
Q: xcode using view in subclass I am learning to program the iphone and I wanted to do some drawing. I followed some example code and subclassed the viewcontroller and it worked fine. Now as I wanted to expand the program I came upon a design question that I could use a little help on.
I subclass myviewcontroller with mynewview. If I have any code in the myviewcontroller how do I call or reference it in mynewview and vice versa? I am not sure if I am asking this right but I am trying to understand the relationship between the class and subclass.

A: Objective-C objects benefit from inheritance. All classes are subclasses of NSObject, therefore you can call init on any object. If you created a custom class and gave it a method doSomethingAwesome, you are free to then implement doSomethingAwesome in any subclass of your custom class. However, declaring a method in a subclass does not add that method to the superclass. As an aside, I rarely find myself subclass sing my own custom classes. I believe that it is encouraged to maintain what is called a shallow object hierarchy. Usually I subclass the stock cocoa classes, customize to my needs and if I need custom methods in more than one subclass I will declare a category on the superclass rather than relying on inheritance to provide my custom behavior

A: The messaging system in Objective-C is dynamic. Every object includes a struct with information that the runtime use for introspection. Here the runtime will find a list of methods the object is able to respond. So, let's say you message an instance like this:
[mynewview someMethod];

The runtime will first check the object information to trying to find some method that will be able to respond the message. If nothing is found, then will query the super class, and so on. In fact, the runtime is much more complex, and will give any object more opportunities to respond (that's the dynamic part. For instance, mynewview might not have any method called someMethod and yet, might be able to satisfy the call, but that's something you might not want to worry right now).
From a child class you can call the superclass implementation of a given method with the keyboard super, so if mynewview is a subclass of myviewcontroller you can call myviewcontroller implementation from mynewview with:
[super someMethod];

If someMethod is both present in myviewcontroller and in mynewview, the runtime will automatically only call the child implementation, you have to call the parent implementation (if you have to) from the child implementation.


text:
Q: Redux and libraries with state (cytoscape) I have a particular problem with react, redux and a library which has it's own state and would like to know what is considered the best solution:
I have a form wizard with 3 steps (general information, advanced information, a graph which the user draws (cytoscape))
Component wise I have a Wizard component which decides which form to render, as well as forward and backward buttons. And a component for each step.
Problem: The last form has it's own state in cytoscape.js and I need when the user is finished and presses the button to finish, gather some information and do a small computation. However the button is managed by the wizard component.
Possible Solutions:

*

*On each operation mirror the needed state in redux (produces overhead as I don't show the informations and they are duplicate and it might be rather much information)

*Move the state of the graph up to the wizard component so that on the button press the necessary information can be taken (defeats the whole point that i wanted to split the logic in the Graph component)
Thank you for your help

A: Usually, people who use Redux keep all their state themselves so their entire app is serialisable.  They use cy.json() and/or ele.json() to diff-patch the graph with the updated app state.  I'm not a Redux expert, but this is what I've seen people often do.


text:
Q: Setup resource not working in Magento 1.6.0 I am trying to build a module for Magento 1.6.0. Here is my config. I don't know what is wrong with it. The setup sql script is not running.
<config>
    <modules>
        <MagePsycho_Shipmentfiles>
            <version>1.0.0</version>
        </MagePsycho_Shipmentfiles>
    </modules>
    <global>
        <models>
           <shipmentfiles>
                <class>MagePsycho_Shipmentfiles_Model</class>
            </shipmentfiles>
        </models>
        <helpers>
            <shipmentfiles>
                <class>MagePsycho_Shipmentfiles_Helper</class>
            </shipmentfiles>
        </helpers>
        <resources>
            <shipmentfiles_setup>
                <setup>
                    <module>MagePsycho_Shipmentfiles</module>
                </setup>
            </shipmentfiles_setup>
        </resources>
    </global>
    .......
    ..........

I have created install-1.0.0.php file inside sql/shipmentfiles_setup directory. But this file doesn't seem to load. Also, I have checked in core_resource table. It doesn't have any record of "shipmentfiles_setup".

A: Your file have to be named mysql4-install-1.0.0.php, not install-1.0.0.php.
If even then your setup will not run then use the most comprehensive guide on this subject ever written My Magento Extension Install Script Will Not Run by Alan Storm.

A: per my comment, Magento caches a lot of it's settings. After installing something/changing configuration it's a good idea to clear out the /tmp and /cache directories.


text:
Q: How to add rel="nofollow" to links with preg_replace() The function below is designed to apply rel="nofollow" attributes to all external links and no internal links unless the path matches a predefined root URL defined as $my_folder below.
So given the variables...
$my_folder = 'http://localhost/mytest/go/';
$blog_url = 'http://localhost/mytest';

And the content...
internal

internal cloaked link

external

The end result, after replacement should be...
internal

internal cloaked link

external

Notice that the first link is not altered, since its an internal link.
The link on the second line is also an internal link, but since it matches our $my_folder string, it gets the nofollow too.
The third link is the easiest, since it does not match the blog_url, its obviously an external link.
However, in the script below, ALL of my links are getting nofollow. How can I fix the script to do what I want?
function save_rseo_nofollow($content) {
$my_folder =  $rseo['nofollow_folder'];
$blog_url = get_bloginfo('url');
    preg_match_all('~~isU',$content["post_content"],$matches);
    for ( $i = 0; $i <= sizeof($matches[0]); $i++){
        if ( !preg_match( '~nofollow~is',$matches[0][$i])
            && (preg_match('~' . $my_folder . '~', $matches[0][$i])
               || !preg_match( '~'.$blog_url.'~',$matches[0][$i]))){
            $result = trim($matches[0][$i],">");
            $result .= ' rel="nofollow">';
            $content["post_content"] = str_replace($matches[0][$i], $result, $content["post_content"]);
        }
    }
    return $content;
}

A: Using regular expressions to do this job properly would be quite complicated. It would be easier to use an actual parser, such as the one from the DOM extension. DOM isn't very beginner-friendly, so what you can do is load the HTML with DOM then run the modifications with SimpleXML. They're backed by the same library, so it's easy to use one with the other.
Here's how it can look like:
$my_folder = 'http://localhost/mytest/go/';
$blog_url = 'http://localhost/mytest';

$html = '
internal
internal cloaked link
external
';

$dom = new DOMDocument;
$dom->loadHTML($html);

$sxe = simplexml_import_dom($dom);

// grab all  nodes with an href attribute
foreach ($sxe->xpath('//a[@href]') as $a)
{
    if (substr($a['href'], 0, strlen($blog_url)) === $blog_url
     && substr($a['href'], 0, strlen($my_folder)) !== $my_folder)
    {
        // skip all links that start with the URL in $blog_url, as long as they
        // don't start with the URL from $my_folder;
        continue;
    }

    if (empty($a['rel']))
    {
        $a['rel'] = 'nofollow';
    }
    else
    {
        $a['rel'] .= ' nofollow';
    }
}

$new_html = $dom->saveHTML();
echo $new_html;

As you can see, it's really short and simple. Depending on your needs, you may want to use preg_match() in place of the strpos() stuff, for example:
    // change the regexp to your own rules, here we match everything under
    // "http://localhost/mytest/" as long as it's not followed by "go"
    if (preg_match('#^http://localhost/mytest/(?!go)#', $a['href']))
    {
        continue;
    }

Note
I missed the last code block in the OP when I first read the question. The code I posted (and basically any solution based on DOM) is better suited at processing a whole page rather than a HTML block. Otherwise, DOM will attempt to "fix" your HTML and may add a  tag, a DOCTYPE, etc...

A: Thanks @alex for your nice solution. But, I was having a problem with Japanese text. I have fixed it as following way. Also, this code can skip multiple domains with the $whiteList array.
public function addRelNoFollow($html, $whiteList = [])
{
    $dom = new \DOMDocument();
    $dom->preserveWhiteSpace = false;
    $dom->loadHTML(mb_convert_encoding($html, 'HTML-ENTITIES', 'UTF-8'));
    $a = $dom->getElementsByTagName('a');

    /** @var \DOMElement $anchor */
    foreach ($a as $anchor) {
        $href = $anchor->attributes->getNamedItem('href')->nodeValue;
        $domain = parse_url($href, PHP_URL_HOST);

        // Skip whiteList domains
        if (in_array($domain, $whiteList, true)) {
            continue;
        }

        // Check & get existing rel attribute values
        $noFollow = 'nofollow';
        $rel = $anchor->attributes->getNamedItem('rel');
        if ($rel) {
            $values = explode(' ', $rel->nodeValue);
            if (in_array($noFollow, $values, true)) {
                continue;
            }
            $values[] = $noFollow;
            $newValue = implode($values, ' ');
        } else {
            $newValue = $noFollow;
        }

        // Create new rel attribute
        $rel = $dom->createAttribute('rel');
        $node = $dom->createTextNode($newValue);
        $rel->appendChild($node);
        $anchor->appendChild($rel);
    }

    // There is a problem with saveHTML() and saveXML(), both of them do not work correctly in Unix.
    // They do not save UTF-8 characters correctly when used in Unix, but they work in Windows.
    // So we need to do as follows. @see https://stackoverflow.com/a/20675396/1710782
    return $dom->saveHTML($dom->documentElement);
}

A: Here is the DOMDocument solution...
$str = 'internal

internal cloaked link

external

external

external

external
';
$dom = new DOMDocument();

$dom->preserveWhitespace = FALSE;

$dom->loadHTML($str);

$a = $dom->getElementsByTagName('a');

$host = strtok($_SERVER['HTTP_HOST'], ':');

foreach($a as $anchor) {
        $href = $anchor->attributes->getNamedItem('href')->nodeValue;

        if (preg_match('/^https?:\/\/' . preg_quote($host, '/') . '/', $href)) {
           continue;
        }

        $noFollowRel = 'nofollow';
        $oldRelAtt = $anchor->attributes->getNamedItem('rel');

        if ($oldRelAtt == NULL) {
            $newRel = $noFollowRel;
        } else {
            $oldRel = $oldRelAtt->nodeValue;
            $oldRel = explode(' ', $oldRel);
            if (in_array($noFollowRel, $oldRel)) {
                continue;
            }
            $oldRel[] = $noFollowRel;
            $newRel = implode($oldRel,  ' ');
        }

        $newRelAtt = $dom->createAttribute('rel');
        $noFollowNode = $dom->createTextNode($newRel);
        $newRelAtt->appendChild($noFollowNode);
        $anchor->appendChild($newRelAtt);

}

var_dump($dom->saveHTML());

Output
string(509) "<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">

internal

internal cloaked link

external

external

external

external

"

A: Try to make it more readable first, and only afterwards make your if rules more complex:
function save_rseo_nofollow($content) {
    $content["post_content"] =
    preg_replace_callback('~<(a\s[^>]+)>~isU', "cb2", $content["post_content"]);
    return $content;
}

function cb2($match) {
    list($original, $tag) = $match;   // regex match groups

    $my_folder =  "/hostgator";       // re-add quirky config here
    $blog_url = "http://localhost/";

    if (strpos($tag, "nofollow")) {
        return $original;
    }
    elseif (strpos($tag, $blog_url) && (!$my_folder || !strpos($tag, $my_folder))) {
        return $original;
    }
    else {
        return "<$tag rel='nofollow'>";
    }
}

Gives following output:
[post_content] =>
  internal
  internal cloaked link
  external

The problem in your original code might have been $rseo which wasn't declared anywhere.

A: Try this one (PHP 5.3+):

*

*skip selected address

*allow manually set rel parameter

and code:
function nofollow($html, $skip = null) {
    return preg_replace_callback(
        "#(]+?)>#is", function ($mach) use ($skip) {
            return (
                !($skip && strpos($mach[1], $skip) !== false) &&
                strpos($mach[1], 'rel=') === false
            ) ? $mach[1] . ' rel="nofollow">' : $mach[0];
        },
        $html
    );
}

Examples:
echo nofollow('something');
// will be same because it's already contains rel parameter

echo nofollow('something'); // ad
// add rel="nofollow" parameter to anchor

echo nofollow('something', 'localhost');
// skip this link as internall link

A: <?

$str='internal
internal cloaked link
external';

function test($x){
  if (preg_match('@localhost/mytest/(?!go/)@i',$x[0])>0) return $x[0];
  return 'rel="nofollow" '.$x[0];
}

echo preg_replace_callback('/href=[\'"][^\'"]+/i', 'test', $str);

?>

A: Here is the another solution which has whitelist option and add tagret Blank attribute.
And also it check if there already a rel attribute before add a new one.
function Add_Nofollow_Attr($Content, $Whitelist = [], $Add_Target_Blank = true)
{
    $Whitelist[] = $_SERVER['HTTP_HOST'];
    foreach ($Whitelist as $Key => $Link)
    {
        $Host = preg_replace('#^https?://#', '', $Link);
        $Host = "https?://". preg_quote($Host, '/');
        $Whitelist[$Key] = $Host;
    }

    if(preg_match_all("//", $Content, $matches, PREG_SET_ORDER))
    {
        foreach ($matches as $Anchor_Tag)
        {
            $IS_Rel_Exist = $IS_Follow_Exist = $IS_Target_Blank_Exist = $Is_Valid_Tag =  false;
            if(preg_match_all("/(\w+)\s*=\s*['|\"](.*?)['|\"]/",$Anchor_Tag[0],$All_matches2))
            {
                foreach ($All_matches2[1] as $Key => $Attr_Name)
                {
                    if($Attr_Name == 'href')
                    {
                        $Is_Valid_Tag = true;
                        $Url = $All_matches2[2][$Key];
                        // bypass #.. or internal links like "/"
                        if(preg_match('/^\s*[#|\/].*/', $Url))
                        {
                            continue 2;
                        }

                        foreach ($Whitelist as $Link)
                        {
                            if (preg_match("#$Link#", $Url)) {
                                continue 3;
                            }
                        }
                    }
                    else if($Attr_Name == 'rel')
                    {
                        $IS_Rel_Exist = true;
                        $Rel = $All_matches2[2][$Key];
                        preg_match("/[n|d]ofollow/", $Rel, $match, PREG_OFFSET_CAPTURE);
                        if( count($match) > 0 )
                        {
                            $IS_Follow_Exist = true;
                        }
                        else
                        {
                            $New_Rel = 'rel="'. $Rel . ' nofollow"';
                        }
                    }
                    else if($Attr_Name == 'target')
                    {
                        $IS_Target_Blank_Exist = true;
                    }
                }
            }

            $New_Anchor_Tag = $Anchor_Tag;
            if(!$IS_Rel_Exist)
            {
                $New_Anchor_Tag = str_replace(">",' rel="nofollow">',$Anchor_Tag);
            }
            else if(!$IS_Follow_Exist)
            {
                $New_Anchor_Tag = preg_replace("/rel=[\"|'].*?[\"|']/",$New_Rel,$Anchor_Tag);
            }

            if($Add_Target_Blank && !$IS_Target_Blank_Exist)
            {
                $New_Anchor_Tag = str_replace(">",' target="_blank">',$New_Anchor_Tag);
            }

            $Content = str_replace($Anchor_Tag,$New_Anchor_Tag,$Content);
        }
    }
    return $Content;
}

To use it:
$Page_Content = 'internal
                 internal
                 google
                 example
                 stackoverflow';

$Whitelist = ["http://yoursite.com","http://localhost"];

echo Add_Nofollow_Attr($Page_Content,$Whitelist,true);

A: WordPress decision:
function replace__method($match) {
    list($original, $tag) = $match;   // regex match groups

    $my_folder =  "/articles";       // re-add quirky config here
    $blog_url = 'https://'.$_SERVER['SERVER_NAME'];

    if (strpos($tag, "nofollow")) {
        return $original;
    }
    elseif (strpos($tag, $blog_url) && (!$my_folder || !strpos($tag, $my_folder))) {
        return $original;
    }
    else {
        return "<$tag rel='nofollow'>";
    }
}

add_filter( 'the_content', 'add_nofollow_to_external_links', 1 );

function add_nofollow_to_external_links( $content ) {
    $content = preg_replace_callback('~<(a\s[^>]+)>~isU', "replace__method", $content);
    return $content;
}

A: a good script which allows to add nofollow automatically and to keep the other attributes
function nofollow(string $html, string $baseUrl = null) {
    return preg_replace_callback(
            '#]*)>(.+)#isU', function ($mach) use ($baseUrl) {
                list ($a, $attr, $text) = $mach;
                if (preg_match('#href=["\']([^"\']*)["\']#', $attr, $url)) {
                    $url = $url[1];
                    if (is_null($baseUrl) || !str_starts_with($url, $baseUrl)) {
                        if (preg_match('#rel=["\']([^"\']*)["\']#', $attr, $rel)) {
                            $relAttr = $rel[0];
                            $rel = $rel[1];
                        }
                        $rel = 'rel="' . ($rel ? (strpos($rel, 'nofollow') ? $rel : $rel . ' nofollow') : 'nofollow') . '"';
                        $attr = isset($relAttr) ? str_replace($relAttr, $rel, $attr) : $attr . ' ' . $rel;
                        $a = '' . $text . '';
                    }
                }
                return $a;
            },
            $html
    );
}


text:
Q: Проблемы с добавлением Toolbar в android-приложение Я попытался добавить Toolbar в свое android-приложение и при объявлении и инициализации возникли кое-какие проблемы. А именно:
При выполнении этого кода возникает ошибка:

Class requires API level 21 (current min is 15): android.widget.Toolbar

Код:
toolbar = (Toolbar) findViewById(R.id.myToolBar);
setSupportActionBar(toolbar);

Как это исправить?

A: Текст вашей ошибки говорит о том, что используемый вами класс Toolbar можно использовать только с минимальной версией API проекта 21, а у вас в проекте установлена 15.
Вы используете android.widget.Toolbar, а для использования начиная с 14 версии API нужен android.support.v7.widget.Toolbar.
Чтобы его использовать, подключите в зависимостях в build.gradle для вашего модуля:
implementation "com.android.support:appcompat-v7:27.1.1"


text:
Q: Strange JsonSerializationException while deserializing nested classes with List members I'm trying to deserialize some complex json (using custom converters that extend JsonConverter) that contains lists of interfaces. These lists need to be filled with class instances that implement those interfaces.
Some of these class instances also have their own List<IInterface> member to deserialize. Here's a snippet of this json (with parts omitted/changed for brevity). This json is valid and I do not have any control over its structure. It was made using the Jackson parser, (the server side is implemented in Java) if that matters.
Features is a member of a larger object I'm trying to deserialize.
"features": {
      "features": [
        {
          "@class": "com.company.project.business_logic.StandardFeatureArtifact",
          "feature_number": 1,
          "weight": 1,
          "player_bool": false,
          "override_bool": false,
          "play_bool": false,
          "evaluates_bool": false,
          "result_bool": false,
          "runners": [
            {
              "@class": "com.company.project.business_logic.StandardRunnableFeatureArtifact",
              "components": [
                {
                  "@class": "com.company.project.business_logic.components.GamePlayComponent",
                  "composition_order": 1,
                  "behaviours": [
                    {
                      "@class": "com.company.project.business_logic.behaviours.MultiplierBehaviour",
                      "order": 2,
                      "weight": 1,
                      "multiplier": 1
                    },
                    {
                      "@class": "com.company.project.business_logic.behaviours.RepeatActionBehaviour",
                      "order": 1,
                      "weight": 1,
                      "times_to_run": 8
                    },
                    {
                      "@class": "com.company.project.business_logic.behaviours.SymbolBehaviour",
                      "order": 0,
                      "weight": 1,
                      "symbol_to_fill": "STRING"
                    }
                }
            }
        }

Features is a List<IFeature>
Runners is a List<IRunnableFeature>
Components is a List<IRunnableComponent>
Behaviours is a List<IBehaviour>
I've written custom JsonConverters for each of the above 4 member lists. Here's a snippet of one of my custom JsonConverters
class StandardFeatureArtifactConverter : JsonConverter
    {
        public override bool CanConvert(Type objectType)
        {
            return (objectType == typeof(StandardFeatureArtifact));
        }

        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            JArray jo = JArray.Load(reader);
            StandardFeatureArtifact sfa = new StandardFeatureArtifact();
            sfa.Runners = new List<IRunnableFeature>();
            foreach (JObject jobj in jo)
            {
                if (jobj["@class"].ToString().EndsWith("StandardRunnableFeatureArtifact"))
                {
                    StandardRunnableFeatureArtifact srfa = jobj.ToObject<StandardRunnableFeatureArtifact>(serializer);
                    sfa.Runners.Add(srfa);
                }
            }
            return sfa;
        }

My WriteJson() just throws a NotImplementedException() at the moment because I'm solely focusing on deserialization first.
So here's the problem. I can deserialize to the return sfa line just fine. I get a valid StandardFeatureArtifact object, however my custom converter for Behaviors is never executed and when the ReadJson() method above returns, I get a JsonSerializationException {"Error setting value to 'Runners' on 'Company.JSON.StandardFeatureArtifact'."}.
The above exception occurs on the following line in my FeatureConverter class in ReadJson() (which is very similar to the above ReadJson() except jo in FeatureConverter is a JObject)
StandardFeatureArtifact sfa = jobj.ToObject<StandardFeatureArtifact>(serializer);

This doesn't make any sense because sfa is a valid object when I'm stepping through the return sfa line.
I'm positive that I'm annotating and implementing the converters correctly because I have another List<Interface> member (for the same outer object that Features belongs to) that I deserialize correctly. The difference between that and Features is that the former only has members of primitive types.

*

*Any thoughts on what's causing that exception?

*Why does my Behaviours converter never get executed?

My understanding of nested json deserialization is that each member is deserialized in a "depth first" manner. This order seems to hold for features -> StandardFeatureArtifact -> StandardRunnableFeatureArtifact -> GamePlayComponent but breaks for Behaviours.
Please let me know if more information is needed. This is my first post on SO. Thank you!


text:
Q: Two questions on ensuring EndInvoke() gets called on a list of IAsyncResult objects So this question is regarding the .Net IAsyncResult design pattern and the necessity of calling EndInvoke as covered in this question
Background
I have some code where I'm firing off potentially many asynchronous calls to a particular function and then waiting for all these calls to finish before using EndInvoke() to get back all the results.
Question 1
I don't know whether any of the calls has encountered an exception until I call EndInvoke() and in the event that an exception occurs in one of the calls the entire method should fail and the exception gets wrapped into an API specific exception and thrown upwards.
So my first question is what's the best way then to ensure that the remainder of the async calls get properly terminated?
Is a finally block which calls EndInvoke() on the remainder of the unterminated calls (and ignores any further exceptions) the best way to do this?
Question 2
Secondly when I first fire off all my asyc calls I then call WaitHandle.WaitAll() on the array of WaitHandle instances that I've got from my IAsyncResult instances.  The method which is firing all these async calls has a timeout to adhere to so I provide this to the WaitAll() method.  Then I test whether all the calls have completed, if not then the timeout must have been reached so the method should also fail and throw another API specific exception.
So my second question is what should I do in this case?
I need to call EndInvoke() to terminate all these async calls before I throw the error but at the same time I don't want the code to get stuck since EndInvoke() is blocking.  In theory at least if the WaitAll() call times out then all the async calls should themselves have timed out and thrown exceptions (thus completing the call) since they are also governed by a timeout but this timeout is potentially different from the main timeout

A: I would iterate through your IAsyncResult objects, wrapping each EndInvoke in a try/catch that stores any generated exception somewhere else. Then, when you've called all the EndInvokes, you can see if you've stored any exceptions and throw an API exception if so. Something like:
var exs = new List<Exception>();

foreach (IAsyncResult iasr in asyncResults) {
    try {
        iasr.EndInvoke();
    }
    catch (Exception e) {
        exs.Add(e);
    }
}

if (exs.Count > 0) {
    throw new MyException(exs.ToReadOnly());
}

A: I recommend using Tasks instead of IAsyncResult if at all possible. They have nicer "continuation" semantics, and can wrap an IAsyncResult API, calling EndInvoke appropriately for you.


text:
Q: How to handle the event / detect hold SHIFT key in Spec 2 toolbars? I have a toolbar (SpToolbarPresenter) as an instance var toolbar and I have an #updatePresenter implementation as:
updatePresenter

    cmds isEmpty ifTrue: [ ^ self ].

    btnHandlers := cmds collect: [ :cmd |
                          | btn |
                          btn := SpToolbarButtonPresenter new
                                     label: cmd name;
                                     action: [];
                                     help: cmd help.
                          toolbar addItem: btn.
                          (SpEventHandler for: btn) whenMouseDownDo: [ :ev |
                              self onCmd: cmd name event: ev ] ]

I use SpEventHandler instead of #action: because I want to detect hold SHIFT key while the toolbar's button is clicked. However, I still need the #action: because without it I get a strange error like "#cull: was sent to nil".
This code works for the second toolbar's button (I have two of them on the toolbar), but not for the first one! The first toolbar's button never gets the event, so onCmd is never called.
So, how to either 1) to detect hold SHIFT while toolbar's button is clicked or 2) to fix this code, so all buttons will get this event ? Any help will be useful.
PS. Windows 10, Spec 2, Pharo-9.0.0+build.940.sha.deeec198ef752789431ee24667709a4a3ff87bda (64 Bit)

A: as @RandomB says, but also adding a shiftPressed test :
updatePresenter

    commands do: [ :aCommand |
        | button |
        button := self newToolbarButton
                   label: aCommand name;
                   action: [  ];
                   help: aCommand help.
        toolbar addItem: button.
        button eventHandler whenMouseDownDo: [ :event |
            event shiftPressed ifTrue: [
                self onCmd: aCommand name event: event ] ] ]

also, even not being directly related, I cannot avoid to say : use complete variable/method names! it will make your code a lot more readable :)

A: The fix may be:
updatePresenter

    cmds do: [ :cmd |
        | btn |
        btn := SpToolbarButtonPresenter new
                   label: cmd name;
                   action: [  ];
                   help: cmd help.
        toolbar addItem: btn.
        btn eventHandler whenMouseDownDo: [ :ev |
            self onCmd: cmd name event: ev ] ]

Tested - it works. The idea is to use eventHandler of the buttons then to create new handlers for them.


text:
Q: how to get key values and key value pairs of array Here I am trying to parse two dimensional array using php
Array
(
    [1] => Array
        (
            [0] => 2
            [1] => 6
            [2] => 10
            [3] => 13
            [4] => 15
            [5] => 17
            [6] => 21
        )

    [2] => Array
        (
            [0] => 6
            [1] => 9
            [2] => 23
        )

    [3] => Array
        (
            [0] => 10
            [1] => 18
            [2] => 23
        )

    [4] => Array
        (
            [0] => 8
            [1] => 12
        )

    [5] => Array
        (
            [0] => 10
        )

    [6] => Array
        (
            [0] => 13
        )

    [7] => Array
        (
            [0] => 5
            [1] => 8
            [2] => 11
            [3] => 21
            [4] => 23
        )

)

this array come from a scheduler : https://www.jqueryscript.net/time-clock/appointment-week-view-scheduler.html
Here key value 1,2,3,4,5,.. are days of week..,1 stands for Monday and 0-23 stands for hrs of the day.
Here I want to store day of the week and Hrs of the day in a variable for MySQL,using loops.

A: You just need to use 2 for(;;) loops
for($outerLoop=0; $outerLoop<count($arrMain); $outerLoop++ ) {
    $innerArray = $arrMain[$outerLoop];
    for($innerLoop=0; $innerLoop<count($innerArray); $innerLoop++ ) {
       //--- do your stuff with the data
    } // end innerLoop
} // end outerLoop


text:
Q: StatusBar is on top of navigationBar after MailComposer is dismissed Problem: My status bar appears on top of navigationBar after I present and dismiss MFMailComposerViewController as modal view.
-(IBAction)openMail:(id)sender
{
    MFMailComposeViewController *mc = [[MFMailComposeViewController alloc] init];
    mc.mailComposeDelegate = self;

    [mc setSubject:emailTitle];
    [mc setMessageBody:messageBody isHTML:YES];
    [mc setToRecipients:toRecipents];
    [mc.navigationItem.leftBarButtonItem setTintColor:[UIColor colorWithRed:144/255.0f green:5/255.0f blue:5/255.0f alpha:1.0f]];
    [self presentViewController:mc animated:YES completion:NULL];
}

- (void) mailComposeController:(MFMailComposeViewController *)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError *)error
{
switch (result)
{
    case MFMailComposeResultCancelled:
        NSLog(@"Mail cancelled");
        break;
    case MFMailComposeResultSaved:
        NSLog(@"Mail saved");
        break;
    case MFMailComposeResultSent:
        NSLog(@"Mail sent");
        break;
    case MFMailComposeResultFailed:
        NSLog(@"Mail sent failure: %@", [error localizedDescription]);
        break;
    default:
        break;
}
// Reset background image for navigation bars
[[UINavigationBar appearance] setBackgroundImage:[UIImage imageNamed:@"navigationBar.png"] forBarMetrics:UIBarMetricsDefault];
NSLog(@"%@",[GGStackPanel printFrameParams:self.view]);
// Close the Mail Interface
GGAppDelegate * appDel = [[UIApplication sharedApplication] delegate];

HHTabListController * contr = (HHTabListController*)appDel.viewController;
[contr setWantsFullScreenLayout:NO];
NSLog(@"%i",[contr wantsFullScreenLayout]);
[self dismissViewControllerAnimated:YES completion:NULL];

}

There are couple of similar questions on Stackoverflow, but none of the solutions suggested there work for me.
I have already tried:
status bar and Navigation bar problem after dismissed modal view
http://developer.appcelerator.com/question/120577/nav-bar-appears-underneath-status-bar
I tried presenting and dismissing from AppDelegate, no help.
Changing the view frame or navigationBar frame works, but I would have to do the same thing for all other views in my app (there are many of them). That will make my whole app depend on this tiny bug.
Screenshots

After dismissing MailComposer:

A: wantsFullScreenLayout is something complex and unrelated. ALL viewcontrollers are required to EITHER be embedded inside a "layout" viewcontroller (Apples UINavigationController, Apple's UITabBarController), OR to fully implement the complex logic of "how big should I be, and where am I positioned?" themselves.
Apple decided with iOS 1.0 that the main iPhone view you see DOES NOT START at 0,0. The Window that contains it starts at (0,0), but it is OVERLAPPED by the status bar.
I think this is a decision they came to regret, it made sense at the time, but in the long term it caused a lot of bugs.
The net effect is:

*

*UINavigationController and UITabBarController have special (undocumented) internal code that makes it SEEM AS IF (0,0) is the top left corner - they force-resize/reposition any UIViewController's you add to them

*...if you are NOT using one of them as your main controller, you have to re-implement that logic yourself. If you're using 3rd-party UIViewController instance, the logic is often implemented incorrectly or missing.

*... you can FIX THIS yourself at runtime by re-positioning the UIViewController.view (its root view), e.g. by this:

(code)
UIViewController* rootController = // in this case HHTabController?
UIView* rootView = rootController.view;
CGRect frame = rootView.frame;
CGPoint oldOrigin = frame.origin;
CGPoint newOrigin = // calculate this, according to Apple docs.
// in your current case, it should be: CGPointMake( 0, 20 );
frame.origin = newOrigin;
frame.size = CGSizeMake( frame.size.width - (newOrigin.x - oldOrigin.x), frame.size.height - (newOrigin.y - oldOrigin.y) );
rootView.frame = frame;

...obviously, it's annoying having to do this everytime. This is why Apple strongly encourages everyone to use UINavigationController and/or UITabBarController :)

A: This alternative solution is also really handy to handle the weird behaviour of top layout guide repositioning itself after view controller is presented modally.
Add constraint for top spacing not to "Top Layout Guide", but to the actual "view". Select view (current distance ...) as shown in screenshot below:

Courtesy: https://stackoverflow.com/a/24818204/2959346


text:
Q: how to move image near to table in GitHub markdown? I just started using GitHub, and I can't find any information on how to move images in README.md files.
I managed to move the table beneath the image, but I want to put it next to the image.

As you can see in the screenshot, "RED" is the current position and "BLUE" indicates the desired position. Link to the GitHub repository.
Any ideas?

A: That is not possible. At least I tried with a flexbox.
The closest you can get is putting the image directly inside the table and use HTML instead of MarkDown like this:

        kur:

        x un y - šāviņa koordinātes (metros);

        t - laiks (sekundes);

        v0 - sākuma ātrums (metros sekundē);

        α - leņķis zem kura izlido šāviņš attiecība pret horizontālu virsmu;

        g - brīvas krišanas paātrinājums (m/s2).

Preview on GitHub:

Live Demo


text:
Q: Salt and Pepper impulse Denoising opencv I am creating a generic method to work on salt and pepper noise and variants. The example images are as shown below :

I tried few methods, such as

*

*Median filter from scipy

*Selective Adaptive Median Filter by Jayanta Das et al.

The closest result was on Image 3, with Median filter, giving the closest result to the original image with no noise.
These are my following doubts :

*

*Can we consider these noises as salt and pepper noise? Is there something else that I am missing?

*What could be the better suggested method? Currently, I am planning to implement Switching Median filter by Pei-Eng et al, but I would like to know if this could be the right track.

The originals that I am trying to get closer to:

A: As far as I know these noises are not natural and estimating them is almost impossible. As a simple and handy method, median filter is the best. Since the presence of the noise is too much, the images are corrupted and there is a huge loss in the image information. In this situation, the best practice is to use deep learning method, because they can restore the impaired parts of the image to a desirable level.
I found this paper, promising for such purpose but you would find more resources:
https://arxiv.org/pdf/1810.10039.pdf
In this page also you will find many strong deep learning methods and codes for denoising image:
https://github.com/z-bingo/awesome-image-denoising-state-of-the-art


text:
Q: Create DefaultWsdl11Definition with SimpleXsdSchema I'm using Spring WS and I'm trying to create a dynamic WSDL trough DefaultWsdl11Definition. Based on Spring WS documentation thw following code should work:
@Bean
public DefaultWsdl11Definition orders() {
    DefaultWsdl11Definition definition = new DefaultWsdl11Definition();
    definition.setPortTypeName("Orders");
    definition.setLocationUri("http://localhost:8080/ordersService/");
    definition.setSchema(new SimpleXsdSchema(new ClassPathResource("echo.xsd")));

    return definition;
}

But the WSDL that is returned doesn't include the operations that are defined in my schema. There is no error in log, the WSDL returned is almost blank, only with the defaults of WSDL generation.
What could be missing?

A: Checking this tutorial from Spring team I finally understand what's wrong. The SimpleXsdSchema has to be a bean.
@EnableWs
@Configuration
public class WebServiceConfig extends WsConfigurerAdapter {

    @Bean
    public ServletRegistrationBean messageDispatcherServlet(ApplicationContext applicationContext) {
        MessageDispatcherServlet servlet = new MessageDispatcherServlet();
        servlet.setApplicationContext(applicationContext);
        servlet.setTransformWsdlLocations(true);
        return new ServletRegistrationBean(servlet, "/ws/*");
    }

    @Bean(name = "countries")
    public DefaultWsdl11Definition defaultWsdl11Definition(XsdSchema countriesSchema) {
        DefaultWsdl11Definition wsdl11Definition = new DefaultWsdl11Definition();
        wsdl11Definition.setPortTypeName("CountriesPort");
        wsdl11Definition.setLocationUri("/ws");
        wsdl11Definition.setTargetNamespace("http://spring.io/guides/gs-producing-web-service");
        wsdl11Definition.setSchema(countriesSchema);
        return wsdl11Definition;
    }

    @Bean
    public XsdSchema countriesSchema() {
        return new SimpleXsdSchema(new ClassPathResource("countries.xsd"));
    }
}

Going deeper, I checked that SimpleXsdSchema implements InitializingBean interface that has afterPropertiesSet() method. It's in the implementation of that method that the schema file is loaded.
So the documentation of Spring WS is wrong. I hope that in the next version this is fixed.


text:
Q: how to send data in view from laravel controller in the body not in url after getting callback from google socialite? Login Controller :
<?php

namespace App\Http\Controllers\Auth;

use Illuminate\Support\Facades\Redirect;

use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Route;
use App\Providers\RouteServiceProvider;
use Illuminate\Foundation\Auth\AuthenticatesUsers;

use Laravel\Socialite\Facades\Socialite;
use App\Models\User;

class LoginController extends Controller
{

    use AuthenticatesUsers;

    /**
     * Where to redirect users after login.
     *
     * @var string
     */
    //protected $redirectTo = '/home';

    /**
     * Create a new controller instance.
     *
     * @return void
     */

    public function redirectToProvider()
    {
        return Socialite::driver('google')->redirect();
    }

    /**
     * Obtain the user information from GitHub.
     *
     * @return \Illuminate\Http\Response
     */
    public function handleProviderCallback()
    {
        $user = Socialite::driver('google')->stateless()->user();

        $user_status = User::whereEmail($user->getEmail())->first();

        if ($user_status) {
            auth()->login($user_status, true);

            return Redirect::route('home', ['role' => $user_status->Role]);
        } else {
            return redirect('login');
        }
    }
    public function __construct()
    {
        $this->middleware('guest')->except('logout');
    }
}

In home.blade.php :
@extends('layouts.admin')

@section('content')

Dashboard

Home

        {{$role}}

@endsection

web.php :

Route::get('/', function () {
    return view('welcome');
});

Auth::routes();

Route::get('/home/{role?}', [App\Http\Controllers\HomeController::class, 'index'])->name('home');

Route::get('login/google', [LoginController::class, 'redirectToProvider']);
Route::get('login/google/callback', [LoginController::class, 'handleProviderCallback']);

Question :
So my query is that i want to redirect to page with user's role data to home page.
so when i write {{$role}} in home page it says that $role is undefined. my main motive is to change content page based on the user but i could not get the data in view page. also it does send data once in URL but i forgot that code(Beginner) so kindly advice me what to do.

A: use view() helper for that
return view('home', ['role' => $user_status->Role]);

or if you  want redirect then use this

        {{  auth()->user()->Role  ?? '' }} // use this

directlty u can use auth()->user()->Role in blade as you are logged in


text:
Q: Trouble with encrypted SD card I recently encrypted a SD card with disk utility to secure some of my most precious files, with a password. I then renamed the SD card, and then copied the files to it. The trouble is, that when I unplugged my sd and plugged it back, the password I did set didn't work anymore. I guess it's because I changed the name of my card. I tried many things with the terminal, but I can't get anywhere. Does anybody have an idea that could get me out of this trouble, cause those files are really important to me, I'd be desperate to lose access to them forever.
Many thanks in advance,

A: You'll need to step through the process manually using Disk Utility.
First connect the card and then don't enter anything. Next open Disk Utility and then see if the entire disk is encrypted and how many volumes exist. You can also get this data from the command line:
diskutil list

Or the information tab in Disk Utility and perhaps the menu item to show all partitions. It's possible you erased everything but it's also possible that you just renamed the volume inside the encryption. It's hard to guess without specifics and some back/forth between you and someone that knows disk partitioning.


text:
Q: Reactjs Next.js 12 Webpack monorepo build error due"Module parse failed: Unexpected token (x:y)" I have 2 modules in a mono-repo with 2 web applications using ReactJS, NextJS:
/project
   |- api/
   |- web/

    "react": "^18.2.0",
    "next": "^12.2.5",
    "react-dom": "^18.2.0",
    "rollup": "^2.79.0",
    "rollup-plugin-ts": "^3.0.2",
    "ts-loader": "^9.3.1",
    "ts-node": "^10.9.1",
    "typescript": "^4.7.4",
    "webpack": "^5.74.0",
    "webpack-cli": "^4.10.0"

next.config.js:
const aliases = {
  api: path.join(__dirname, '../api/'),
}
module.exports = {
  reactStrictMode: true,
  swcMinify: true,
  experimental: {
    forceSwcTransforms: true,
    swcTraceProfiling: true,
  },
  output: 'standalone',
  i18n: {
    defaultLocale: 'us',
    locales: ['us', 'sg', 'my', 'th', 'vn', 'id', 'de'],
  },
  webpack: (config) => {
    // Add aliases
    config.resolve.alias = {
      ...(config.resolve.alias || {}),
      ...aliases,
    }
    // Find rules that includes current directory
    const rulesWithCurrentDir = config.module.rules.filter((rule) => rule.include && rule.include.includes(dirname))
    // Prepare the sibling package paths that we want to include
    const siblingPackagePaths = [path.resolve(`${dirname}../api`)]
    // Push sibling package paths
    rulesWithCurrentDir.forEach((ruleWithCurrentDir) => ruleWithCurrentDir.include.push(...siblingPackagePaths))
    return config
  },
}

webpack.config.js:
import path from 'path';

module.exports = {
    mode: "development",
    // Change to your "entry-point".
    entry: './index',
    output: {
        path: path.resolve(__dirname, '.next'),
        filename: 'app.bundle.js'
    },
    resolve: {
        extensions: ['.ts', '.tsx', '.js', '.jsx', '.json']
    },
    module: {
        rules: [
        {
            test: /\.(css)$/,
            include: [/stylesheets/, /node_modules/],
            use: [
                'css-loader',
            ],
        },
        {
            test: /\.css$/,
            exclude: [/stylesheets/, /node_modules/],
            use: [
                'css-loader?sourceMap&modules,localIdentName=[local]-[hash:base64]',
            ],
        },
      {
        test: /\.(ts|tsx)?$/,
        include: path.resolve(__dirname, '**/*'),
        exclude: /node_modules/,
        loader: 'ts-loader',
      },
      {
        test: /\.(ts|tsx)?$/,
        include: path.resolve(__dirname, '../api/**/*'),
        exclude: /node_modules/,
        loader: 'ts-loader',
      },
      ],
    }
};

.babelrc:
{
    "presets": [
      "@babel/preset-env",
      "@babel/preset-react",
      "@babel/preset-typescript"
    ],
    "plugins": [
      "@babel/plugin-proposal-class-properties"
    ]
}

tsconfig.json:
{
  "extends": "../../tsconfig.json",
  "exclude": [
    "node_modules",
    "build"
  ],
  "include": [
    "next-env.d.ts",
    "**/*.ts",
    "**/*.js",
    "**/*.tsx",
    "**/*.json"
  ],
  "node-option": [
    "experimental-specifier-resolution=node",
    "loader=ts-node/esm"
  ],
  "extensions": [
    "ts",
    "tsx"
  ],
  "compilerOptions": {
    "baseUrl": ".",
    "outDir": "build/",
    "incremental": true,
    "target": "es2022",
    "lib": [
      "dom",
      "dom.iterable",
      "es2022"
    ],
    "allowJs": true,
    "skipLibCheck": true,
    "strict": false,
    "forceConsistentCasingInFileNames": true,
    "esModuleInterop": true,
    "module": "esnext",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "plugins": [
      {
        "name": "@rollup/plugin-typescript"
      },
      {
        "name": "@rollup/plugin-json"
      }
    ],
    "noEmit": true,
    "jsx": "preserve"
  },
  "references": [
    {
      "path": "../api"
    }
  ]
}

next.config.mjs:
export default {
  swcMinify: true,
  experimental: {
    forceSwcTransforms: true,
    swcTraceProfiling: true,
  },
  output: 'standalone',
};

next build errors:
../web/src/views/Dashboard/Bids/BidDetailsDescriptionTable.tsx
Module parse failed: Unexpected token (58:4)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
|   const { subtotal, shipping } = pricing || {}
|   return (
>     <Root>
|       <Hidden mdDown>
|

../web/src/views/Dashboard/Bids/QuotationDetails/QuotationSlip.tsx
Module parse failed: Unexpected token (65:4)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
|   const { sellerSignature, sellerSigneeName, sellerSigneeDesignation, quotationTimeStamp } = quotationBid || {}
|   return (
>     <Root className={classes.boxWrap}>
|       <SharedSlipDetails titleType="Quotation" bidStatusTimeStamp={QUOTATION_TIME_STAMP} quotationBid={quotationBid} />
|       <BidDetailsDescriptionTable quotationBid={quotationBid} />

../web/src/views/Dashboard/Bids/SharedSlipDetails.tsx
Module parse failed: Unexpected token (69:4)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
|
|   return (
>     <Root>
|       <Box display="flex">
|

../web/src/views/Dashboard/Messages/Messages.tsx
Module parse failed: Unexpected token (194:27)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
|
|   // Getters
>   const getInitialChats = (): ChatInterface[] => {
|     const isNewChatAlreadyExists =
|       hasNewChat && prevChats?.find((prevChat) => prevChat.participantIDs.includes(query.sellerID as string))

../web/src/views/Dashboard/Messages/utils.ts
Module parse failed: Unexpected token (9:42)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
| import { SellerInterface } from '@app/api/src/modules/Seller/model/Seller'
|
> export const getUnreadMessageCount = (chat: ChatInterface, userID: string): number => {
|   const unReadMessages =
|     chat?.messages?.filter(({ isReadIDs }) => !isReadIDs || !isReadIDs.includes(userID))?.length || 0

I only see this error after upgrading from Next.JS 11 to 12.


text:
Q: Why is `evalf` not working? Why is evalf not changing $\pi$ and $e$ to floating point in the following:
h := proc (x) options operator, arrow; exp(x)*cos(x) end proc
Tay := taylor(h(x), x = (1/6)*pi, 2)
P2 := convert(Tay, polynom)
evalf(P2(.5))
The output is(exp((1/6)*Pi))(.5)*(cos((1/6)*Pi))(.5)+(-1.*(exp((1/6)*Pi))(.5)*(sin((1/6)*Pi))(.5)+(exp((1/6)*Pi))(.5)*(cos((1/6)*Pi))(.5))*(x(.5)-.1666666667*Pi(.5)). For my calculation, I need $\pi$  and $e$ to be approximations.

A: To Maple, Pi is $\pi$, but pi is just a variable.
Also, seeing the result, I think you shouldn't do "evalf(P2(0.5))", but "evalf(subs(x=0.5,P2))".

A: You should use the  capital letter for 'Pi-
Tay := taylor(h(x), x = (1/6) *Pi, 2);
It works.


text:
Q: Data extraction from student identification card I am doing a mobile application using flutter and need to scan a student identification card.
Most of the libraries I found are for nationality identification cards, so I would like to customize one for myself. Are there any customizable libraries that can be used?