text:
Q: d3.nest() sum for object array data I have data in the format of
data={
  "Month": "Jan",
  "typeA": [
     {
        "A": 24000,
        "B": 24000,
        "C": 24000
     }],
  "typeB": [
     {
        "A": 20000,
        "B": 14000,
        "C": 10000
     }],
  "typeC": [
     {
        "A": 34000,
        "B": 44000,
        "C": 54000
     }]
     },
      {
  "Month": "Feb",
  "typeA": [
     {
        "A": 84000,
        "B": 64000,
        "C": 14000
     }],
  "typeB": [
     {
        "A": 20000,
        "B": 34000,
        "C": 10000
     }],
  "typeC": [
     {
        "A": 30000,
        "B": 40000,
        "C": 50000
     }]
    }
    ]

I want to calculate sum of each type( ie typeA, TypeB) for indivisual months,
Ie I want data in the format below,
Month: jan
typeA:72000
typeB:44000
typeC:13200

Month:feb
typeA:162000
typeB:64000
typeC:120000

I am using d3.nest() to achieve this,
This is my code,
    var months= d3.nest()
    .key(function (d) { return (d.Month) })
    .key(function (d) { return (d.typeA) })
    .key(function (d) { return (d.typeB) })
    .key(function (d) { return (d.typeC) })
      .rollup(function (leaves) {
          return d3.sum(leaves, function (d) { return d3.sum(sum,d3.values(d.A,d.B,d.C,d.D)) });
      })
      .entries(data);

I am not able to get the sum of the elements here. I'm getting zero as sum. Can anybody suggest me where I am doing wrong?

A: I am not much familiar with d3.nest. But I think you can get your results by using JavaScript Array map function. Try this code.

var data=[{
  "Month": "Jan",
  "typeA": [
     {
        "A": 24000,
        "B": 24000,
        "C": 24000
     }],
  "typeB": [
     {
        "A": 20000,
        "B": 14000,
        "C": 10000
     }],
  "typeC": [
     {
        "A": 34000,
        "B": 44000,
        "C": 54000
     }]
     },
      {
  "Month": "Feb",
  "typeA": [
     {
        "A": 84000,
        "B": 64000,
        "C": 14000
     }],
  "typeB": [
     {
        "A": 20000,
        "B": 34000,
        "C": 10000
     }],
  "typeC": [
     {
        "A": 30000,
        "B": 40000,
        "C": 50000
     }]
    }
  ];

var results = data.map(function(d){
  return {
    Month: d.Month ,
    typeA: d3.sum(d3.values(d.typeA[0])),
    typeB: d3.sum(d3.values(d.typeB[0])),
    typeC: d3.sum(d3.values(d.typeC[0]))
  }
});

alert(JSON.stringify(results));

A: You can do it with nesting like this...

  data = [{
    "Month": "Jan",
    "typeA": [
      {
        "A": 24000,
        "B": 24000,
        "C": 24000
      }],
    "typeB": [
      {
        "A": 20000,
        "B": 14000,
        "C": 10000
      }],
    "typeC": [
      {
        "A": 34000,
        "B": 44000,
        "C": 54000
      }]
  },
  {
    "Month": "Feb",
    "typeA": [
      {
        "A": 84000,
        "B": 64000,
        "C": 14000
      }],
    "typeB": [
      {
        "A": 20000,
        "B": 34000,
        "C": 10000
      }],
    "typeC": [
      {
        "A": 30000,
        "B": 40000,
        "C": 50000
      }]
  }],
    months = d3.nest()

  var months = d3.nest()
    .key(function(d){return d.Month})
    .rollup(function(leaves){
      //leaves is an array so use d3.sum
      return d3.sum(leaves, function(d) {
        //d can be an object who's value can be an array
        //use d3.sum
        return d3.sum(d3.values(d), function(e){
          //
          return d3.sum(e, function(f) {
            return d3.sum(d3.values(f))
          });
        })
      } )
    })
    .entries(data);
  d3.select("#output").text(JSON.stringify(months));

A: You just need to change your code like this:

*

*Add ]; end of data
data = [
    {
        "Month": "Jan",
        "typeA": [
            {
                "A": 24000,
                "B": 24000,
                "C": 24000
            }
        ],
        "typeB": [
            {
                "A": 20000,
                "B": 14000,
                "C": 10000
            }
        ],
        "typeC": [
            {
                "A": 34000,
                "B": 44000,
                "C": 54000
            }
        ]
    },
    {
        "Month": "Feb",
        "typeA": [
            {
                "A": 84000,
                "B": 64000,
                "C": 14000
            }
        ],
        "typeB": [
            {
                "A": 20000,
                "B": 34000,
                "C": 10000
            }
        ],
        "typeC": [
            {
                "A": 30000,
                "B": 40000,
                "C": 50000
            }
        ]
    }
];

*Change your code to:
var months = d3.nest()
    .key(function(d) { return (d.Month) })
    .rollup(function (v) {
      return {

            typeA: d3.sum(d3.values(v[0].typeA[0])),
            typeB: d3.sum(d3.values(v[0].typeB[0])),
            typeC: d3.sum(d3.values(v[0].typeC[0]))

    } })
    .map(data);

console.log(JSON.stringify(months));

Edit:
You can use this type of d3.sum() function too, But remember the value's that return are string 'the part that you missed in your code'  to see the actual result need to parse data.
    var months = d3.nest()
    .key(function(d) { return (d.Month) })
    .rollup(function(v) {
        return {
            typeA: d3.sum(v, function(d) {
                var type = d3.values(d.typeA[0]);
                var array = type.map(function (x) { return parseInt(x, 10) });
                return d3.sum(array);
            }),
            typeB: d3.sum(v, function (d) {
                var type = d3.values(d.typeB[0]);
                var array = type.map(function (x) { return parseInt(x, 10) });
                return d3.sum(array);
            }),
            typeC: d3.sum(v, function (d) {
                var type = d3.values(d.typeC[0]);
                var array = type.map(function (x) { return parseInt(x, 10) });
                return d3.sum(array);
            })

        }
    })
    .entries(data);

console.log(JSON.stringify(months));

A: Unfortunately my other answer was for a different question but I'll leave it in case it's useful.
The answer by @Gabriel is very cool but is using d3 functions but its not generic and the categories are hard-coded in which is not ideal.
Here is a way to do it in (mostly) plain JS that is completely generic.  The only assumption is that the first member of each array element is the heading being grouped and the other members are the ones to be rolled up.  Anyway, as well as generic, this way is quite short.
I also included a version of the @Gabriel answer to show it's easy to generalise also.

  var data = [{
        "Month": "Jan",
        "typeA": [
          {
            "A": 24000,
            "B": 24000,
            "C": 24000
          }],
        "typeB": [
          {
            "A": 20000,
            "B": 14000,
            "C": 10000
          }],
        "typeC": [
          {
            "A": 34000,
            "B": 44000,
            "C": 54000
          }]
      },
      {
        "Month": "Feb",
        "typeA": [
          {
            "A": 84000,
            "B": 64000,
            "C": 14000
          }],
        "typeB": [
          {
            "A": 20000,
            "B": 34000,
            "C": 10000
          }],
        "typeC": [
          {
            "A": 30000,
            "B": 40000,
            "C": 50000
          }]
      }],
//////////////////////////////////////////////////////////////////////////////////
//Method one: without rollup
// assume that the first member of each object in the array is a heading
//  e.g. Month
//////////////////////////////////////////////////////////////////////////////////
  headings = data.reduce(function(headings, d) {
      var h = d3.keys(d)[0];  //get the heading
      return (headings [d[h]] = d3.keys(d).filter(function(p, i){return i}) //filter out the heading
        .reduce(function(s, p){   //sum each of the other members
          //p is the category being summed
          return (s[p] = d3.sum(d3.values(d[p][0])), s);
        }, {}), headings);
    }, {});

  d3.select("#output").text(JSON.stringify(headings));
//////////////////////////////////////////////////////////////////////////////////
//Method two: @Gabriel solution generalised
//////////////////////////////////////////////////////////////////////////////////
  var months = d3.nest()
    .key(function(d) { return (d.Month) })
    .rollup(function (v) {
      return d3.keys(v[0]).filter(function(p, i){return i}) //filter out the heading
        .reduce(function(s, p){   //sum each of the other members
          //p is the category being summed
          return (s[p] = d3.sum(d3.values(v[0][p][0])), s);
        }, {});
    })
    .map(data);

  d3.select("#output2").text(JSON.stringify(months));


text:
Q: Google authentication in php/laravel error: Error: invalid_request Invalid parameter value for redirect_uri: Missing authority I'm trying to build a simple authentication system in my php/laravel app with Google auth using Socialite package, based on this post, but I'm getting the following error on the browser:

my google console credentials are configured like this

and I get this error when I try to login using google, accessing the route '/redirect/google/'
I've been searching for two days, but I haven't found any results containing 'missing authority'.
what does missing authority mean? and how to fix this error?

A: Under "Authorized Redirect URIs", there is mention that the URL not contain relative paths. You would have to redirect directly to localhost:8000, not localhost:8000/callback/google/  ..
If you need to be at the relative path, then make your callback endpoint do whatever it needs to do at localhost:8000, then from there have it itself handle any further redirection.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to set custom page size in fpdf php library? I need some help with fPDF. I want to set up my custom page size (exactly: width 3 inch, and height 5 or 6 inch).
it will create number of pages again height parameter .

i set the size array(3,5). it will create 5 page. I

found fPDF() manual (http://www.fpdf.org/) but there are only ready formats like A4, B5 etc. I have to set up my own page format.
<?php
require_once('fpdf/fpdf.php');
//$fromat = array(3,5);
$pdf = new FPDF('p','in', [4.1,2.9]);
$pdf->SetTopMargin(50);
$pdf->Addpage();
$pdf->SetTitle("invoice");
$pdf->SetCreator("maqbool solutons");
$pdf->SetAuthor("my name");
$pdf->SetSubject("report");

$pdf->SetFont('Arial', 'B', '16');
$pdf->SetTextColor(155,14,9);// rgb
$pdf->SetDrawColor(155,14,9);
$pdf->SetfillColor(15,140,95);
$pdf->Cell(60,10, 'hello word');
$pdf->Cell(60,10,'powered by fpdf', 1, 0,'c',true);
$pdf->Cell(60,10,'powered by fpdf', 1, 2,'c');
$pdf->Cell(60,10,'powered by fpdf', 1, 1,'c');
$pdf->Image("images/coat.jpg", 10,20,10,35);
$pdf->MultiCell(94,10,"skldjfsldfsfjsdkfsjdlfjsdflkjsdflksjflksjdflskjfslkjfdslkfdjslkfdjslkfjslkfjslkfjsflkjsflkjsflksjflksjfslkjfslkjslkf",1,"L",false);
$pdf->Output("I", "invice.pdf");
 ?>[that is my file size][1]

when i add array of size

A: As said in the documentation, when you call the constructor or AddPage, you can either give a String or an Array containing the width and height:
// AddPage([string orientation [, mixed size [, int rotation]]])
$pdf->AddPage("P", [3, 5]); // assuming you are using 'in' as unit

Or directly using the constructor:
// __construct([string orientation [, string unit [, mixed size]]])
$pdf = new FPDF('P','in',[3, 5]);

A: You should should define it in your constructor like so:
$pdf = new FPDF('P','in',[3,6]);

You can find more info in tutorial #1 and in the manual > AddPage

A: I think you can set the page size with the constructor.
I have not tested it but this should show you the way:
$format=array(3,5);
$pdf=new FPDF('P','in',$format);
$pdf->Open();
....


text:
Q: AlertDialog.Builder declaration inside or outside inner AsyncTask class? Consider this AsyncTask inside activity MyActivity:
private class MyTask extends AsyncTask<Void, Void, Void> {

    private ProgressDialog progressDialog;
    private AlertDialog.Builder alertDialog;

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        progressDialog = ProgressDialog.show(MyActivity.this, "MyApp", "Working...");
    }

    @Override
    protected Void doInBackground(Void... params) {
        // elaborate...
        return null;
    }

    @Override
    protected void onPostExecute(Void result) {
        super.onPostExecute(result);
        progressDialog.dismiss();

        alertDialog = new AlertDialog.Builder(MyActivity);
        alertDialog.setMessage("Done !");
        alertDialog.show();
    }
}

What happen if I declare
private ProgressDialog progressDialog;
private AlertDialog.Builder alertDialog;

outside the AsyncTask, in the activity scope?
Is it really the same (for memory leaks and other inner Java behaviours)? Is one better than the other?

A: Not quite sure what you mean by 'the same'. But if you are talking about the scope of both progressDialog and alertDialog then the answer would definitely be no. A variable belongs to the class that declares it.
Basically what both progressDialog and alertDialog actually need is just a reference to a Context instance(In your case is 'MyActivity') in order for it to be instantiated and displayed, hence it doesn't matter where they are created as long as that Context object is available.
Hope it helps.


text:
Q: How to show WPF DataGrid Parent/Child records with Entity Framework I have been trying to find an example of how to create a WPF parent/child datagrid where the child records are displayed underneath the related parent row.  I am using the Entity Framework for aquiring the data.

A: Assuming you have worked out the Bindings and the Columns stuff....
You can use the RowDetails to show more information about the Row....
For Example
<WPFToolkit:DataGrid x:Name="dg" ItemsSource="{Binding}"
        RowDetailsVisibilityMode="VisibleWhenSelected">

    <WPFToolkit:DataGrid.RowDetailsTemplate>
        <DataTemplate>
            <StackPanel>
              <!--Your Favourite Controls-->
            </StackPanel>
        </DataTemplate>
    </WPFToolkit:DataGrid.RowDetailsTemplate>


text:
Q: Xamarin.Forms application analytics tracking concerns I am trying to track my Xamarin.Forms application below details using App Center Analytics for enhance our application in the future.

*

*Device API version.

*Most visited page.

*Time Spend per page.

Is this legal?
Can I publish my application to PlayStore with App Center Analytics?

A: Those are (just a few) use cases App Center Analytics was made for.
Tracking custom properties can be acheived through Custom Properties APIs:
https://learn.microsoft.com/en-us/appcenter/sdk/analytics/xamarin#custom-events
Or you can use custom properties sdk-wise:
https://learn.microsoft.com/en-us/appcenter/sdk/other-apis/xamarin#use-custom-properties
With those, you can track quite a plenty of information you need. Note the limits, though - 200 different events max, and up to 20 properties per event.
As for publishing application on PlayStore it's totally fine, since App Center is basically just an SDK.


text:
Q: Cannot assign property "Converter": Property does not exist, or is not assignable, or mismatching type between value and property I am writing an app with Xamarin.Forms and MvvmCross. I am having an issue with my converter. In my Core project:
public class BoolInverseValueConverter : MvxValueConverter<bool, bool>
{
    public bool Convert(bool value, Type targetType, CultureInfo culture, object parameter)
    {
        return !value;
    }
}

In my Forms project:
namespace MyApp.Forms.NativeConverters
{
    public class BoolInverseValueConverter : MvxNativeValueConverter<MyApp.Core.Converters.BoolInverseValueConverter>
    {
    }
}

In my xaml:
<Application xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:converters="clr-namespace:MyApp.Forms.NativeConverters;assembly=MyApp.Forms"
x:Class="MyApp.Forms.App">
<Application.Resources>
    <converters:BoolInverseValueConverter x:Key="BoolInverseValueConverter" />
</Application.Resources>

In my page:
<views:MvxContentPage x:TypeArguments="viewModels:LoginViewModel"
xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:views="clr-namespace:MvvmCross.Forms.Views;assembly=MvvmCross.Forms"
xmlns:mvx="clr-namespace:MvvmCross.Forms.Bindings;assembly=MvvmCross.Forms"
xmlns:viewModels="clr-namespace:MyApp.Core.ViewModels;assembly=MyApp.Core"
xmlns:localviews="clr-namespace:MyApp.Forms.Views;assembly=MyApp.Forms"
xmlns:resx="clr-namespace:MyApp.Core.Resources;assembly=MyApp.Core"
x:Class="MyApp.Forms.Pages.LoginPage"
Title="Login">
    <ContentPage.Content>
        <localviews:UserLoginView DataContext="{Binding .}" IsVisible="{mvx:MvxBind MyBoolVariable, Converter={StaticResource BoolInverseValueConverter}}"/>
    </ContentPage.Content>
</views:MvxContentPage>

When I run the UWP app I get the message:

Cannot assign property "Converter": Property does not exist, or is not
  assignable, or mismatching type between value and property

A: no idea about MvvmCross, but in your xaml file, between
<Application.Resources>

and
<converters:BoolInverseValueConverter ...>

did you add
<ResourceDictionary> ?

A: I think MvvmCross is not scanning the assembly where you have your converter, thus it cannot be found. Try registering the converter class assembly in your Setup:
protected override IEnumerable<Assembly> ValueConverterAssemblies
{
    get
    {
        var toReturn = base.ValueConverterAssemblies.ToList();
        toReturn.Add(typeof(BoolInverseValueConverter).Assembly);
        return toReturn;
    }
}

HIH

A: Your converter should be something like below
 public class BoolInverseValueConverter: IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, string language)
        {
            if (value == null || (value as bool?) == false)
                return Visibility.Collapsed;
            else
                return Visibility.Visible;
        }

        public object ConvertBack(object value, Type targetType, object parameter, string language)
        {
            if (value == null || (value as bool?) == false)
                return Visibility.Collapsed;
            else
                return Visibility.Visible;

        }

A: I ended up making the converter without MvvmCross to have it working. Maybe it's a bug in the current version of MvvmCross (6.2.1).


text:
Q: Install CentOS from hard drive - kernel panic I want to dual-boot CentOS and Windows XP. The computer has two partitions (C: and D:) and I want to install CentOS 6.2 on the D: drive.
So I downloaded the i386 ISO package, used UNetbootin to deploy that ISO on the hard drive and booted to UNetbootin. After I select the Install CentOS option, I get the following
Kernel Panic - not syncing: Attempted to kill init!
panic occured, switching back to text console

and nothing else.
Any advice? Please note that I don't have a CD Drive, and also I do not have any USB storage at hand.

A: Installing CentOS from HDD is possible,  extract the ISO image onto your HDD, copy the syslinux config out, to e.g if you use grub4dos to load the installer.
Last time I managed to do this, by modifying the installer partly, which make it mount the ISO image instead of real CD, but it might be fixed already.

A: Without knowing your hardware specifics it is difficult to really say why you are getting kernel panic.  If you are looking for another method in creating boot media without using a CD/DVD drive I would recommend pendrive Linux (http://www.pendrivelinux.com/)  it's free software that I have had good luck with in the past.  (apologies if this isn't helpful due to no USB storage, I wasn't entirely sure from the post as unetbootin is used to create USB media).


text:
Q: I want to make a program in C++ on two platforms, Mac and Linux, using GitHub and (a) IDE(s) Basically I want to use GitHub as my repository and develop on Mac and Linux operating systems. Is this even possible? For example, can I use Xcode on my Mac and Code::Blocks on my Linux OS? Or does it have to be the same IDE, if so any suggestions?

A: I would suggest using the same standard IDE on each machine to prevent from version conflicts, and compiler variation issues.
It is entirely possible to use two different IDE's but it would be much simpler with one as you would not have to worry about project specific settings in one ide, not being read by the other ide.
If you use "for example" Code::Blocks for each machine, you could just put the entire project to the repository, and git it on another machine, and go right into it and start using it. "providing the ide versions are the same".
For simplicity, I would use one.

A: Yes, it's possible. Take care to ensure:

*

*Cross-platform code checked in for one platform is compatible with the other

*Platform-specific code does not affect the other platform

*The Xcode and Code::Blocks configurations don't fall out of sync
It helps immensely to work on a branch, and only merge into master once you have tested on all platforms that you wish to support. You can use GitHub's pull request feature to keep track of feature branches.
The compiler shipped with Xcode is Clang; Code::Blocks uses GCC by default. On one hand, this is good because you're continually maintaining compatibility with multiple compilers. On the other, it might generate unexpected headaches, as it's yet another platform difference to manage.

A: As an alternative to these answers, you can also setup and use something like Cmake to have a build system that can then be compiled to different IDE's project files on each machine or platform you support. This way, only the cmake files (not Xcode or Code::Blocks projects) are stored in the repository, and setting it up only requires downloading the repository and running Cmake to build the Xcode or Code::Blocks projects from that.
Assuming your code is sufficiently cross platform, this would also make porting to another IDE or OS without much difficulty.
I've used it for several projects, and while I admit that getting things set up takes a bit more time, once its running, only a single set of files needs to be updated when new files, assemblies, and settings are specified.


text:
Q: How to pop to root view controller with view hierarchy containing multiple Navigation controllers I have a view hierarchy with multiple UINavigationControllers
Now from a particular view controller, I wanted to pop to window.rootviewcontroller
How can I do that?
I tried
[UIApplication sharedApplication].keyWindow.rootViewController popToRootViewController];
But it does not work. Please suggest.
Please note I want to go to window.rootVC.
THis will not work for me
 [self.navigationController popToRootViewControllerAnimated:YES];

A: set
UINavigationController *navController = (UINavigationController*)self.window.rootViewController;

[self.navigationController popToRootViewControllerAnimated:YES];

A: Just get the window instance and set the root view controller again, as popToRootViewController only pops to root view controller of particular navigation stack
- (void)popToRoot
{
    AppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
    UIWindow *mainWindow = appDelegate.window;
    ViewController *viewControllerObj = [ViewController new];
    UINavigationController *navigationObject = [[UINavigationController alloc] initWithRootViewController:viewControllerObj];
    [mainWindow setRootViewController:navigationObject];
}

Hope this helps.


text:
Q: graph plot API for ArangoDB pyArango I am using ArangoDB community edition, I can query on a created graph in AQL and get results in JSON which is graphically visualized on ArangoDB web interface tool.
AQL Query
FOR v,e,p IN 1..3 OUTBOUND 'germanCity/Hamburg' GRAPH 'routeplanner'
OPTIONS{bfs :true}
RETURN p

JSON output
[
  {
    "edges": [
      {
        "_key": "6392826",
        "_id": "germanHighway/6392826",
        "_from": "germanCity/Hamburg",
        "_to": "germanCity/Cologne",
        "_rev": "_WmZ77pW--D",
        "distance": 500
      }
    ],
    "vertices": [
      {
        "_key": "Hamburg",
        "_id": "germanCity/Hamburg",
        "_rev": "_WmZ77Z---_",
        "population": 1000000,
        "isCapital": false,
        "loc": [
          53.5653,
          10.0014
        ]
      },
      {
        "_key": "Cologne",
        "_id": "germanCity/Cologne",
        "_rev": "_WmZ77Y6--B",
        "population": 1000000,
        "isCapital": false,
        "loc": [
          50.9364,
          6.9528
        ]
      }
    ]
  },
  {
    "edges": [
      {
        "_key": "6392840",
        "_id": "internationalHighway/6392840",
        "_from": "germanCity/Hamburg",
        "_to": "frenchCity/Paris",
        "_rev": "_WmZ77pa--_",
        "distance": 900
      }
    ],
    "vertices": [
      {
        "_key": "Hamburg",
        "_id": "germanCity/Hamburg",
        "_rev": "_WmZ77Z---_",
        "population": 1000000,
        "isCapital": false,
        "loc": [
          53.5653,
          10.0014
        ]
      },
      {
        "_key": "Paris",
        "_id": "frenchCity/Paris",
        "_rev": "_WmZ77Z---D",
        "population": 4000000,
        "isCapital": true,
        "loc": [
          48.8567,
          2.3508
        ]
      }
    ]
  },
  {
    "edges": [
      {
        "_key": "6392843",
        "_id": "internationalHighway/6392843",
        "_from": "germanCity/Hamburg",
        "_to": "frenchCity/Lyon",
        "_rev": "_WmZ77pa--B",
        "distance": 1300
      }
    ],
    "vertices": [
      {
        "_key": "Hamburg",
        "_id": "germanCity/Hamburg",
        "_rev": "_WmZ77Z---_",
        "population": 1000000,
        "isCapital": false,
        "loc": [
          53.5653,
          10.0014
        ]
      },
      {
        "_key": "Lyon",
        "_id": "frenchCity/Lyon",
        "_rev": "_WmZ77Z---B",
        "population": 80000,
        "isCapital": false,
        "loc": [
          45.76,
          4.84
        ]
      }
    ]
  }
]

Equivalent Graph

As we can get visualized graph output in web interface I would like to display the same in Language<->ArangoDB.
Language here can be driver language supported : Python, Java , C# etc.
I am using pyArango for interfacing with ArangoDB
I couldnt find an ArangoDB API for getting this graph visualization in JPG or matlibplot.
Is there any other way apart from using below two options?

*

*Use networkx.draw(networkx.graph)

*matplotlib.pyplot

A: If you need graph visualization then Graphviz library is for you. And if Python is OK then you only need a Python binding-library graphviz (that utilizes DOT language representation internally.)
It is super easy to feed your graph JSON from Arango DB to graphviz for rendering.
You can customize it to your style, add labels, colors, reshape nodes and more.
Here is a simple example of your sample JSON:
from graphviz import Digraph

arango_graph = [
    {
        "edges": [
            {
                "_key": "6392826",
                "_id": "germanHighway/6392826",
                "_from": "germanCity/Hamburg",
                "_to": "germanCity/Cologne",
                "_rev": "_WmZ77pW--D",
                "distance": 500
            }
        ],
        "vertices": [
            {
                "_key": "Hamburg",
                "_id": "germanCity/Hamburg",
                "_rev": "_WmZ77Z---_",
                "population": 1000000,
                "isCapital": False,
                "loc": [
                    53.5653,
                    10.0014
                ]
            },
            {
                "_key": "Cologne",
                "_id": "germanCity/Cologne",
                "_rev": "_WmZ77Y6--B",
                "population": 1000000,
                "isCapital": False,
                "loc": [
                    50.9364,
                    6.9528
                ]
            }
        ]
    },
    {
        "edges": [
            {
                "_key": "6392840",
                "_id": "internationalHighway/6392840",
                "_from": "germanCity/Hamburg",
                "_to": "frenchCity/Paris",
                "_rev": "_WmZ77pa--_",
                "distance": 900
            }
        ],
        "vertices": [
            {
                "_key": "Hamburg",
                "_id": "germanCity/Hamburg",
                "_rev": "_WmZ77Z---_",
                "population": 1000000,
                "isCapital": False,
                "loc": [
                    53.5653,
                    10.0014
                ]
            },
            {
                "_key": "Paris",
                "_id": "frenchCity/Paris",
                "_rev": "_WmZ77Z---D",
                "population": 4000000,
                "isCapital": True,
                "loc": [
                    48.8567,
                    2.3508
                ]
            }
        ]
    },
    {
        "edges": [
            {
                "_key": "6392843",
                "_id": "internationalHighway/6392843",
                "_from": "germanCity/Hamburg",
                "_to": "frenchCity/Lyon",
                "_rev": "_WmZ77pa--B",
                "distance": 1300
            }
        ],
        "vertices": [
            {
                "_key": "Hamburg",
                "_id": "germanCity/Hamburg",
                "_rev": "_WmZ77Z---_",
                "population": 1000000,
                "isCapital": False,
                "loc": [
                    53.5653,
                    10.0014
                ]
            },
            {
                "_key": "Lyon",
                "_id": "frenchCity/Lyon",
                "_rev": "_WmZ77Z---B",
                "population": 80000,
                "isCapital": False,
                "loc": [
                    45.76,
                    4.84
                ]
            }
        ]
    }
]

graph_name = 'amazing'

g = Digraph(graph_name, filename=graph_name, format='jpeg', engine='neato')
g.attr(scale='2', label='Look at my graph my graph is amazing!', fontsize='18')
g.attr('node', shape='circle', fixedsize='true', width='1')

for item in arango_graph:
    for vertex in item['vertices']:
        g.node(vertex['_id'], label=vertex['_key'])
    for edge in item['edges']:
        g.edge(edge['_from'], edge['_to'], label=str(edge['distance']))

# Render to file into some directory
g.render(directory='/tmp/', filename=graph_name)
# Or just show rendered file using system default program
g.view()

Just 3 code lines for customization and 5 more to feed the graph visualization renderer. And please note that Arango Web UI does not render all of the edges between the same pair of nodes while graphviz does and you can style each differently.
You will need to install graphviz library and Python bindings
Step #1: Install library
Assuming your machine is Ubuntu:
sudo apt install graphviz

Step #2: Get Python bindings
pipenv install graphviz

If you not yet using Pipenv you can install with good old Pip:
pip install graphviz

Step #3: Run sample and enjoy


text:
Q: How is it possible for the wavelength of light to change in a medium? So my physics class has just finished a long unit on optics while at the same time I've been trying to teach myself relativity. I admit my understanding is probably rudimentary, but I figured all the more reason to ask for help on this.
So I'll start off my question just with what I know of relativity, just to see if maybe my issue is in my understanding of it. I was told that the rest mass of light is 0 based on the equation $E=pc$ adequately representing the energy of light instead of the original equation, $$E^2 ={ (m_0 c^2)^2 + (pc)^2 } \,\!.$$ Now because $E=pc$, we can then say, based on $p=mv$, that $E=(mv)c$. changing relativistic mass out for invariant mass, we can say $$E = \frac{m_0 v c}{\sqrt{1-\frac{v^2}{c^2}}}.$$ Now when we plug a photon with velocity $c$ into this equation,
we get that $\frac{1}{\sqrt{1-\frac{(c)^2}{c^2}}}=\frac{1}{0}$, and that along with the rest of the equation gives us $E=\frac{(0)(c)c}{(0)}$. We then of course say $\frac{0}{0}=undefined$, which from my basic understanding of other people showing this to me, means that E is a value, it's just that this specific equation where we use the lorentz factor and rest mass is incapable of defining what the value is, thus we rely on other equations such as $E=hf$. Please feel free to correct me if that is all wrong, it's just what I've been told thus far.
Now then, I'm going to put a bookmark in that thought above so I can talk about optics. In optics, one of the first things we learned is that the wavelength of light changes in a medium based on $c=fλ$, where $f$ is being used for frequency, because $c$ changes in a medium, as mapped by $n=\frac{c}{v}$, where $v$ is, in that equation, the speed of light in a medium, and $c$ is now defined as the constant speed of light in a vacuum.
So based on the final equation given in my paragraph on relativity, if the speed of light $v$ (again, $v$ meaning speed of light in a medium) changes in a medium, we get this equation: $E = \frac{m_0 v c}{\sqrt{1-\frac{v^2}{c^2}}}$ where $v < c$ in a medium that is not a vacuum, meaning our lorentz factor does not equal 0 anymore. However, $E > 0$ still, and therefore it would seem that rest mass can no longer equal 0 since it is being multiplied by two real numbers, and any real number multiplied by 0 should be 0.
Finally, on to my actual question. The issue shown in the paragraph above has already been addressed numerous times it would seem, stating that particles in the medium might absorb the photons energy and then emit them back out. The issue I'm having understanding is that this answer does not seem to show how the wavelength of light could still change in the medium. if $c$ is actually constant in that medium and only appears to change because it is being delayed by absorption, then the wavelength of light should not change because of the prior equation, $c=fλ$. This problem would seem to come up in any answer that states that the speed of light is only appearing to change, and therefore it seems to me that either the idea that the wavelength of light changes in a medium or something in relativity is inadequate.
Does anyone have any explanation for how to reconcile this issue, or perhaps have an answer to the original problem of the speed of light changing in a medium that circumvents it? Or is the problem that just my math or understanding is incorrect and needs to be tweaked?

A: The basic confusion comes with identifying Photons with Light, i.e. the quantum mechanical entity that a photon is, with the classical electromagnetic wave. The classical electromagnetic wave emerges  from a confluence of photons, the quantum mechanical entities, in an analogous way that a crystal symmetry emerges from the quantum mechanical entities of molecules.
Photons, as quantum mechanical entities, have wave functions which have real and imaginary parts which will contribute in interactions to the probability distributions. They build up the classical electric and magnetic fields of the beam in synergy of wave functions, not interacting , but by their complex wave functions being in phase with each other. In vacuum a wave front is built up having the same frequency h*nu, photon energy and light beam frequency.
When the light beam hits a medium, if it is opaque, the photons scatter and are absorbed and turn into infrared eventually. In a transparent medium the organization of the wavefront  changes, as the photons scatter elastically, the path on each photon changes, each individual photon is not following the shortest ray path. The collective wave function built up from the scattered photon changes the velocity of the wavefront that they build up accordingly. Thus the wavelength changes because of the changed path length of the constituent photons of the beam, with respect to the ray direction.
Note that the scattering has to be elastic for phases to be retained and a coherent beam to come out. It is not a matter of absorbing and re-emission as is wrongly stated sometimes. If the photon excites an energy level the deexcitation will have arbitrary phases and direction with the original beam.

A: There are a lot of intertwined ideas here. Let me try to tackle just part of it.
When a photon interacts with a medium, it causes local polarization - that is, electrons are displaced by the E/M field of the photon. This interaction leads to a slowing down of the wave - and, as you pointed out, a shortening of the wavelength. However, at this point the wave energy is partly in the medium - the displaced electrons. The "wave" you are seeing is both the electromagnetic wave (the photon) and the "Mexican wave" of electrons along the way that move with the photon as it passes. You can't simply throw equations that relate to photons in a vacuum at such a situation and expect the result to be correct.
Reading your question, I think you know that - so really, I'm just confirming it for you.

A: Maybe the explanations you got until now were sufficient, but I would just want to add something simple.
Let's represent a light-wave traveling in the direction $x$ as $Ae^{i\phi}$
where the phase of the wave is
$(\text i) \ \phi = kx - \omega t = 2\pi\left(\frac {x}{\lambda} - \nu t\right).$
Consider a wave-front (a surface on which the phase is constant), and let's denote by $\Delta x$ the distance to the next wave-front with the same phase, and by $\Delta t$ the time needed for the light to travel this distance.
$(\text {ii}) \ 0 = \frac {\Delta x}{\lambda} - \nu \Delta t.$
In vacuum $\Delta x = c\Delta t$, and we can also simplify by $\Delta t$
$(\text {iii}) \  \frac {c}{\lambda} = \nu.$
However, in a medium with refraction index $n$ we are said that the velocity is $n$ times smaller. So, since the frequency doesn't change
$(\text {iv}) \ \frac {c}{n} \frac {n}{\lambda} = \nu,$
or,
$(\text {v}) \ v \frac {n}{\lambda} = \nu,$
Therefore $\lambda$ shortens,
$(\text {vi}) \ \lambda ' = \frac {\lambda}{n}.$

A: The wavelength of harmonic EM wave changes in medium, but saying "the phase velocity of the wave changes in the medium, while frequency stays the same" is no explanation, since then we have the question why phase velocity changes in the medium.
The explanation is based on the wave theory of light, not photon theory. Essentially, primary EM wave from the source interacts with the electric particles in the dielectric medium in such a way that polarization $\mathbf P$ of the medium oscillates with the same frequency as the primary wave, but due to mutual interaction of the particles in the medium the spatial profile of the polarization has modified wavelength. Microscopically, the electric field of the medium adds to the primary wave and results in a complicated EM wave with same frequency but complicated spatial profile (reflecting distribution of the electric particles in the medium). This complicated field, however, has similar effect on the particles of the medium as simple harmonic wave with modified wavelength. Details can be found in advanced textbooks on wave optics and research papers; it is not a simple issue, though.

A: Yes
There is a trivial answer:  frequency doubling crystals (KDP, BaTiO3, ...).  Changing the frequency (and hence the wavelength) is one outcome from non-linear optics.  The foundations of non-linear optics are that the media does not respond linearly to the electro-magnetic wave.
Consider that the media is not a simple harmonic oscillator.  If that is the case, a sine wave could be clipped or misshaped in some way.  This produces harmonics of the original wave.  This is a simple way to envision how non-linear optics can change the wavelength.
Another example is acousto-optics.  Phonons traveling through the material both diffract incoming light and transfer momentum.  The wave that exits the A-O material is frequency shifted by the frequency of the acoustic wave.
BTW the first green laser pointers were frequency doubled YAG lasers!


text:
Q: Find the max, min, sup and inf of a sequence
Let $\{a_n\}=\{x\mid x\in\mathbb {Q},x^2 <2\}$, find the max, min, sup and inf of a sequence

Clearly, sup is $\sqrt {2} $ and inf is $-\sqrt {2} $, so we have $-\sqrt {2}<a_n <\sqrt {2} $. Since $\mathbb {Q} $ is dense of $\mathbb {R} $, max and min both don't exist cause there are many small number between sup and inf.

After I look at the solution, the answer for max and min both are not "DNE", can anyone tell me why cause I don't see it. Thanks.

A: The max
(and, similarly, the min)
does not exist because
there is no rational $r$
such that
$r^2 = 2$
and,
for any rational $r < \sqrt{2}$
there is another rational $s$
such that
$r < s < \sqrt{2}$.

A: This is a classic example of $\mathbb{Q}$ not being a complete field while being dense in $\mathbb{R}$.
Let's denote the set containing the sequence $\{a_n\}$ as $S$. Then, for any $q\in S$, using Archimedes's axiom for the numbers $2-q^2>0$ and $2q+1>0$ there exists an $n\in \mathbb{N}$ such that $n(2-q^2)>2q+1$.
Thus we have: $n^2(2-q^2)>n(2q+1)=2nq+n\geq 2nq+1 \Rightarrow (q+\frac{1}{n})^2<2$, so there always exists a $q'=q+\frac{1}{n} \in S, q'>q$, ergo there is no maximum of this sequence in $\mathbb{Q}$. The reasoning for the nonexistance of a minimum is similar.

A: Okay, I guess my first answer wasn't clear.
If you have a bounded set A one of three things can happen.
1) A has a maximum element x.  If so then x is also the sup of A and the sup of A is a member of the set A.  (sup means least upper bound and if x is maximal it is a least upper bound.)  So max A = sup A = x; x $\in$ A.
The same is true about minimum elements and the inf.
2) A doesn't have a maximum element.  Then if A has a sup, x, the sup is not a member of the set.  If the metric space has the least upper bound property (as R does) the the sup must exist.  So max A does not exist; sup A = x; x $\notin$ A.
The same is true about minimum elements and the inf.
3) If the metric space does not have the least upper bound property (as Q does not) then it is possible (but not always true) that if A doesn't have a maximum element nor does it have a sup.  max A does not exist, sup A does not exist; metric space X does not have least upper bound property.
So if A = {$a_n$} = {$x| x \in Q, x^2 < 2$} is bounded and, I presume, we are viewing it in R which has the least upper bound property, so 3 isn't possible.
So if A has a max element then max = sup = x and $x^2 < 2$.  Is this possible?
If not, then max does not exist and sup A is the smallest real number that is larger than all of the elements of A.  What real number is that?


text:
Q: Given matrices $A$ and $B$, solve for $Z$ in the following equation: $A^{-4}BZ^{3}A^{5}B^{2}A=-3A^{-6}$ $
A=
\begin{pmatrix}
2 & -4 & 3\\
4 & -1 & 2\\
-1 & 1 & -1\\
\end{pmatrix}
$
$
B=
\begin{pmatrix}
3 & -4 & 5\\
1 & -2 & 3\\
-2 & 3 & -4\\
\end{pmatrix}
$
Solve Z in the following equation: $A^{-4}BZ^{3}A^{5}B^{2}A=-3A^{-6}$.
I tried this way:
$A^{-4}BZ^{3}A^{5}B^{2}A=-3A^{-6}$
$\Leftrightarrow BZ^{3}A^{5}B^{2}A=-3A^{-2}$
$\Leftrightarrow Z^{3}A^{5}B^{2}A=-3B^{-1}A^{-2}$
$\Leftrightarrow Z^{3}A^{5}B^{2}=-3B^{-1}A^{-3}$
$\Leftrightarrow Z^{3}A^{5}=-3B^{-1}A^{-3}B^{-2}$
$\Leftrightarrow Z^{3}=-3B^{-1}A^{-3}B^{-2}A^{-5}$
But in  the final equation, $B^{-1}$ does not exist so how can I solve this?

A: I think this problem wasn't meant to be solved. Whoever set this question probably wanted you to point out that the equation is insolvable, because the LHS is singular (as $B$ is singular) but the RHS is not.


text:
Q: How to fix 'cannot read property call of undefined' error in Symfony? In Developer Tools I get following error message in my Symfony project and I can't fix it.
I tried to edit my dev and public app.js and put out my Bootstrap there but I think this is the wrong way.
bootstrap:78 Uncaught TypeError: Cannot read property 'call' of undefined
 at __webpack_require__ (bootstrap:78)
 at Object../assets/js/app.js (app.js:1)
 at __webpack_require__ (bootstrap:78)
 at checkDeferredModules (bootstrap:45)
 at Array.webpackJsonpCallback [as push] (bootstrap:32)
 at app.js:1

app.js
require('../css/bootstrap.min.css');
//require('../css/admin.css');
require('../css/dataTables.bootstrap4.css');
require('../css/app.css');
var $ = require('jquery');

webpack/bootstrap:78
 modules[moduleId].call(module.exports, module,
  __module.exports,__webpack_require__);

How can I figure it out?


text:
Q: Let $f$ be continuous on $I=[a,b]$ such that $f(a)<0$, $f(b)>0$, $W= \{x\in I: f(x)<0\}$, $w=\sup W$ Prove that $f(w)=0$ Let $f$ be continuous on $I=[a,b]$ such that $f(a)<0, f(b)>0, W= \{x\in I: f(x)<0\}$, $w=\sup W$ Prove that $f(w)=0$
[I can see that this is an alternate proof for the Location of roots theorem]
My progress:
If possible, let $f(w)>0$. Since $f$ is continuous at $w, \exists \delta_1>0$ such that $f(x)>0, \forall x\in V_{\delta_1}(w)$.
Similarly, letting let $f(w)<0,\exists \delta_2>0$ such that $f(x)<0, \forall x\in V_{\delta_2}(w)$.
[I have been able to prove the existence of such $\delta_1, \delta_2$.]
I know I'm supposed to arrive at a contradiction here, but I can't figure out what the contradiction is. Please help!

A: Suppose $f(w)<0$. Then there is a $\delta>0$ such that $|x-w|<\delta\implies |f(x)-f(w)|<\epsilon$ where $\epsilon=|f(w)|$. So for any $x$ such that $w<x<w+\delta$, $f(x)<0$ which contradicts that $w$ is an upper bound of $W$.
If $f(w)>0$, defining $\delta$,$\epsilon$, and $x$ such that $w-\delta<x<w$. We have $f(x)>0$ for all such $x$. This contradicts that $w$ is the least upper bound of $W$.

A: Note that $f(b) > 0$ so there is a neighborhood of $b$ where $f(x)$ is positive and hence $w = \sup W < b$. And clearly $w \geq a$ as $a \in W$. Thus $w \in I$.
Proceeding exactly as OP let us assume that $f(w) > 0$. So there is a neighborhood $V_{\delta_{1}}(w) = (w - \delta_{1}, w + \delta_{1})$ such that $f(x)$ is positive in this neighborhood. Clearly $W = \{x \mid x \in I, f(x) < 0\}$ and hence $V_{\delta_{1}}(w)$ is disjoint from $W$.
Also by definition of $w = \sup W$ it is clear that there is a member $c \in W$ such that $w - \delta_{1} < c \leq w$. So then $f(c) < 0$. And since $c \in V_{\delta_{1}}(w)$ so $f(c) > 0$. Contradiction.
Similarly try $f(w) < 0$. In this case you will need $\delta_{2}$.


text:
Q: How can I accomplish this logical exclusion of certain records? Rewritten for clarity,
I need to exclude any records where the key is greater than 2 unfortunately I cant bail out on .find for aggregate because then I lose my language specific features
i've already tried nesting $ne in each field but currently not getting what I'm looking to accomplish
Example Data:
[
  { status: 'draft', key: 1, ... },
  { status: 'terminated', key: 2, ... },
  { status: 'terminated', key: 3, ... },
  ...
]

Javascript
const query = {
  $and: [
    { status: { $ne: 'terminated' }, key: { $lte: 2 } }
  ]
}

db.getCollection('forecasts').find(query)

Desired Output
[
  { status: 'draft', key: 1, ... },
  { status: 'terminated', key: 3, ... },
]

Got
[
  { status: 'draft', key: 1, ... }
]

This throws an error (elasticsearch supports this sort of logic):
db.getCollection('forecasts').find({
    $and: [{
      $not: { status: 'terminated', key: { $gt: 2 } }
    }]
})

Error: error: {
    "ok" : 0,
    "errmsg" : "unknown top level operator: $not. If you have a field name that starts with a '$' symbol, consider using $getField or $setField.",
    "code" : 2,
    "codeName" : "BadValue"
}

if it was raw javascript it would be done in the following way
const collection = [
  { status: 'draft', key: 1 },
  { status: 'terminated', key: 2 },
  { status: 'terminated', key: 3 }
]

const response = collection.filter(doc => {
  let include = true
  if (doc.status === 'terminated' && doc.key <= 2) include = false
  return include
})

console.log(response)
// => [ { status: 'draft', key: 1 }, { status: 'terminated', key: 3 } ]

A:  if (doc.status === 'terminated' && doc.key <= 2) include = false means the white part, so basically you want the yellow part.

db.collection.find({
  $or: [
    { status: { $ne: "terminated" } },
    { key: { $gt: 2 } }
  ]
})

mongoplayground


text:
Q: How to convert FORM response data to Python dictionary in Flask? I have the following data in POST format
Header: Content-Type: 'application/x-www-form-urlencoded':
Data: 'field1=true&field2=false&field3=123'
In the flask server, using the response.form, yields the following result:
ImmutableMultiDict([('field1', 'true'), ('field2', 'false'), ('field3', '123')])
After doing:
request.form.to_dict()
Result is:
{'field1': 'true', 'field2': 'false', 'field3': '123'}
Is there a way to convert the JSON boolean true/false to Python Boolean True/False?
Shouldn't the to_dict function convert these to python boolean types?
The dictionary is converted, but the true/false remains a string.
What is the optimal way to achieve this, besides using string comparison?

A: You will have to marshal the data i.e refer - https://flask-restful.readthedocs.io/en/latest/api.html.
In [11]: from flask_restful import fields, marshal

In [12]: data = {'field1': 'true', 'field2': 'false', 'field3': '123'}

In [13]: mfields = { 'field1':fields.Boolean, 'field2':fields.Boolean, 'field3':fields.Raw}

In [14]: marshal(data, mfields)
Out[14]: OrderedDict([('field1', True), ('field2', True), ('field3', '123')])

In [17]: dict(marshal(data, mfields))
Out[17]: {'field1': True, 'field2': True, 'field3': '123'}

Use a serialization library such as Marshmallow to handle form data.
Edit:
In case you don't know the form structure before hand, you will have to convert it manually because true is a string here. If it wasn't then json.loads could be used.
In [18]: data
Out[18]: {'field1': 'true', 'field2': 'false', 'field3': '123'}

In [19]: {k: True if v == "true" else False if v == "false" else v for k,v in data.items()}
Out[19]: {'field1': True, 'field2': False, 'field3': '123'}


text:
Q: How to find parent element by class name using BeautifulSoup? How can I properly access the parent element of a tag using BeautifulSoup? I've the following structure:

Character Information

There are N structures on the website like this and in order the get the right information I'm filtering first by the text "Character Information", then I want to get the first parent with class TableContainer so after this, I'll be able to find the table with the content that I want.
The current code returns None when I try to find_parent
soup = BeautifulSoup(page.content, "html.parser")

char_title = soup.find("div", string="Character Information")
# result is:
Character Information

parent = char_title.find_parent("div", {"class": "TableContainer"})
# result is: None

parent = char_title.find_parent("div", _class="TableContainer")
# result is: None

How can I find the parent with a specific class?

A: First locate the containing div for each block. Then search for the title to decide if it is the block you want. If it is, use the same search to locate the required table inside the block. For example:
import requests
from bs4 import BeautifulSoup
from unicodedata import normalize

url = "https://www.tibia.com/community/?name=Rubini"
req = requests.get(url)
soup = BeautifulSoup(req.content, "lxml")

for div in soup.find_all('div', class_="TableContainer"):
    title = div.find('div', class_="Text").text

    if title == "Character Information":
        table_inner = div.find('table', class_="Table3").table

        for tr in table_inner.find_all('tr'):
            row = [normalize('NFKD', td.get_text(strip=True)) for td in tr.find_all('td')]
            print(row)

Giving you output:
['Name:RubiniTitle:Exalted (21 titles unlocked)Sex:maleVocation:Elder DruidLevel:1305Achievement Points:411World:LibertabraResidence:ThaisGuild Membership:Leader of theLibertabra PuneLast Login:May 18 2022, 22:17:16 CESTComment:"Frase motivacional de Lideres antigos de Guerras"First Level 1000 on RetroHardcore Servers.Rubini formerly Shanera and Calvera@Since 2007836a95f1d69460734766489384f641cbAccount Status:Free Account', 'Name:', 'Rubini', 'Title:', 'Exalted (21 titles unlocked)', 'Sex:', 'male', 'Vocation:', 'Elder Druid', 'Level:', '1305', 'Achievement Points:', '411', 'World:', 'Libertabra', 'Residence:', 'Thais', 'Guild Membership:', 'Leader of theLibertabra Pune', 'Last Login:', 'May 18 2022, 22:17:16 CEST', 'Comment:', '"Frase motivacional de Lideres antigos de Guerras"First Level 1000 on RetroHardcore Servers.Rubini formerly Shanera and Calvera@Since 2007836a95f1d69460734766489384f641cb', 'Account Status:', 'Free Account']
['Name:', 'Rubini']
['Title:', 'Exalted (21 titles unlocked)']
['Sex:', 'male']
['Vocation:', 'Elder Druid']
['Level:', '1305']
['Achievement Points:', '411']
['World:', 'Libertabra']
['Residence:', 'Thais']
['Guild Membership:', 'Leader of theLibertabra Pune']
['Last Login:', 'May 18 2022, 22:17:16 CEST']
['Comment:', '"Frase motivacional de Lideres antigos de Guerras"First Level 1000 on RetroHardcore Servers.Rubini formerly Shanera and Calvera@Since 2007836a95f1d69460734766489384f641cb']
['Account Status:', 'Free Account']

The text is normalized using unicodedata.normalize()


text:
Q: C# Object Constructor with Specific Values I want to be able to allow only certain values to a custom object method.  The first example that came to mind to illustrate the point is the VB msgbox and the specific values that you use for which set of buttons you could choose.
 MsgBox("Message", vbYesNo,"title")

How would I be able to do the same in C# with a custom object?
The method will search a particular area based on the value sent.
 object.method(SearchArea1);
 object.method(SearchArea2);

I want to be able just type SearchArea1 or SearchArea2 (not as strings) just like you would use vbYesNo, vbCancel.
Does that make sense at all?

A: You could define an enum and then use it as parameter for method
public enum SearchArea
{
    SearchArea1,
    SearchArea2
}

public void method(SearchArea searchArea)
{
    switch (searchArea)
    {
        case SearchArea.SearchArea1:
            // your logic for SearchArea1
            break;
        case SearchArea.SearchArea2:
            // your logic for SearchArea2
            break;
        default:
            throw new ArgumentException("Logic not implemented for provided search area");
    }
}

A: What you're looking for is called an enumeration.


text:
Q: rotate an nxnxn matrix in python I have a binary array of size 64x64x64, where a volume of 40x40x40 is set to "1" and rest is "0". I have been trying to rotate this cube about its center around z-axis using skimage.transform.rotate and also Opencv as:
def rotateImage(image, angle):
    row, col = image.shape
    center = tuple(np.array([row, col]) / 2)
    rot_mat = cv2.getRotationMatrix2D(center, angle, 1.0)
    new_image = cv2.warpAffine(image, rot_mat, (col, row))
    return new_image

In the case of openCV, I tried, 2D rotation of each idividual slices in a cube (Cube[:,:,n=1,2,3...p]).
After rotating, total sum of the values in the array changes. This may be caused by interpolation during rotation. How can I rotate 3D array of this kind without adding anything to the array?

A: Ok so I understand now what you are asking. The closest I can come up with is scipy.ndimage. But there is a way interface with imagej from python if which might be easier. But here is what I did with scipy.ndimage:
    from scipy.ndimage import interpolation
    angle = 25 #angle should be in degrees
    Rotatedim = interpolation.rotate(yourimage, angle, reshape = False,output = np.int32, order = 5,prefilter = False)

This worked for some angles to preserve the some and not others, perhaps by playing around more with the parameters you might be able to get your desired outcome.

A: One option is to convert into sparse, and transform the coordinates using a matrix rotation. Then transform back into dense.  In 2 dimensions, this looks like:
import numpy as np
import scipy.sparse
import math

N = 10
space = np.zeros((N, N), dtype=np.int8)
space[3:7, 3:7].fill(1)
print(space)
print(np.sum(space))

space_coo = scipy.sparse.coo_matrix(space)
Coords = np.array(space_coo.nonzero()) - 3

theta = 30 * 3.1416 / 180

R = np.array([[math.cos(theta), math.sin(theta)], [-math.sin(theta), math.cos(theta)]])
space2_coords = R.dot(Coords)
space2_coords = np.round(space2_coords)
space2_coords += 3
space2_sparse = scipy.sparse.coo_matrix(([1] * space2_coords.shape[1], (space2_coords[0], space2_coords[1])), shape=(N, N))
space2 = space2_sparse.todense()
print(space2)
print(np.sum(space2))

Output:
[[0 0 0 0 0 0 0 0 0 0]
 [0 0 0 0 0 0 0 0 0 0]
 [0 0 0 0 0 0 0 0 0 0]
 [0 0 0 1 1 1 1 0 0 0]
 [0 0 0 1 1 1 1 0 0 0]
 [0 0 0 1 1 1 1 0 0 0]
 [0 0 0 1 1 1 1 0 0 0]
 [0 0 0 0 0 0 0 0 0 0]
 [0 0 0 0 0 0 0 0 0 0]
 [0 0 0 0 0 0 0 0 0 0]]
16
[[0 0 0 0 0 0 0 0 0 0]
 [0 0 0 0 0 0 0 0 0 0]
 [0 0 0 0 0 0 0 0 0 0]
 [0 0 0 1 0 0 0 0 0 0]
 [0 0 1 1 1 1 0 0 0 0]
 [0 0 1 1 1 1 1 0 0 0]
 [0 1 1 0 1 1 0 0 0 0]
 [0 0 0 1 1 0 0 0 0 0]
 [0 0 0 0 0 0 0 0 0 0]
 [0 0 0 0 0 0 0 0 0 0]]
16

The advantage is that you'll get exactly as many 1 values before and after the transform.  The downsides is that you might get 'holes', as above, and/or duplicate coordinates, giving values of '2' in the final dense matrix.


text:
Q: How to redirect all .plist file requests to index.php I need to edit htaccess special way that all requests i.e. http://www.example.com/supermega.plist or http://www.example.com/ultraturbo.plist will be redirected and generated by one index.php. In index.php I want also read plist filename.
Thanks

A: RewriteEngine On

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule (.*)\.(plist)$ /index.php?filename=$1&ext=$2 [L,QSA]

in the following URL :
http://127.0.0.1/somefilename.plist
you have access to filename and ext in $_GET :
print_r($_GET);
/* output
Array
(
    [filename] => somefilename
    [ext] => plist
)
*/


text:
Q: how to soql query from ContentDocumentLink for batch? i'm struggling with understanding the logic behind this query i need to do for a batch job. i am querying the contentdocumentlink object because i need to capture files (potentially multiple) related to specific campaigns. since its a batch i want to query all campaigns that had files added to it each day and store the URLs of the files for each campaign.
i have:
final ID campId;
List<Campaign> campList = [Select Name, Content_Link__c FROM Campaign];

global String soqlQuery = 'Select ContentDocumentId FROM ContentDocumentLink WHERE LinkedEntityId=:campId';

any help means a lot, thanks!


text:
Q: Include not working on ef-core2.0 Working on a aspnetcore2.0 project in VS2017
The '.Include(o => o.OrderEventLogs)'  clause is not working in the following query:
       var orders = _repository.GetDbSet<Order>()
             .Where(o => o.RiskCellId == int.Parse(riskCellId) &&
                    o.OrderDate.ToShortDateString() == OrderDate.ToShortDateString())
             .Include(o => o.OrderEventLogs)
             .Include(o => o.Instrument)
             .ToList();

Is not loading the related OrderEventLog entities. (Actually sometimes it does work, sometimes it doesn't. Same query, same parameters)
It's really weird because this related entities are included when I run this query:
        var order = _repository.GetDbSet<Order>()
            .Where(o => o.Id == Guid.Parse(orderId))
            .Include(o => o.OrderEventLogs)
            .Include(o => o.Instrument)
            .SingleOrDefault();

Both pieces of code run just fine in previous ef-core versions
Packages:
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="2.0.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="2.0.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools.DotNet" Version="2.0.0" />

UPDATE
It seems to work fine if I do this:
       var orders = _repository.GetDbSet<Order>()
             .Where(o => o.RiskCellId == int.Parse(riskCellId) &&
                    o.OrderDate.ToShortDateString() == OrderDate.ToShortDateString())
             .Include(o => o.Instrument)
             .ToList();

        foreach (Order order in orders)
        {
            _repository.Context.Entry(order).Collection(e => e.OrderEventLogs)
                .Load();
        }


text:
Q: Find Outlook Email using Email ID or Extended Property with VBA With the MS Graph API, I can see an Outlook Email's ID and set custom properties (Single Value extended property - https://learn.microsoft.com/en-us/graph/api/singlevaluelegacyextendedproperty-post-singlevalueextendedproperties?view=graph-rest-1.0).
Is there a way to find a specific email by searching on that EmailID or custom property with VBA? It doesn't seem like I can search those properties with 'Folder.Items.Restrict()'
Also, once I get an email item, I'm able to see the custom property I set through MS Graph Api.
oItem.PropertyAccessor.GetProperty("http://schemas.microsoft.com/mapi/string/{10101010-1010-1010-C101-1010101010101010}/myCustomProp")
But is there a way to query the inbox and find that specific email with VBA?
I tried Using Restrict() and PropertyAccessor but they don't seem to address my issue.

A: You can use Items.Find/Restrict to search for a property using its DASL name. Use a query like
@SQL="http://schemas.microsoft.com/mapi/string/{10101010-1010-1010-C101-1010101010101010}/myCustomProp" = 'some value'

Note that the DASL name must be quoted, so in VBA it will be
set item = SomeFolder.Items.Find("@SQL=""http://schemas.microsoft.com/mapi/string/{10101010-1010-1010-C101-1010101010101010}/myCustomProp"" = 'some value'")

A: Binary properties (like EntryID and etc.) are not supported for searching items in Outlook. The best what you could do is to search items with a custom property. For example, you would use the following filter to search for a custom property named Mom's "Gift" that contains the word pearls:
filter = "@SQL=" & Chr(34) & _
    "https://schemas.microsoft.com/mapi/string/{00020329-0000-0000-C000-000000000046}/" _
    & "Mom%27s%20%22Gift%22" & Chr(34) & " like '%pearls%'"

Note, we have used the Chr(34) function solve the problem with double quotes. Read more about string comparisons in the Filtering Items Using a String Comparison article.
To search for items that correspond to your conditions in an Outlook folder you can use the Find/FindNext or Restrict methods of the Items class. You can read more about them in the articles that I wrote for the technical blog:

*

*How To: Use Restrict method to retrieve Outlook mail items from a folder

*How To: Use Find and FindNext methods to retrieve Outlook mail items from a folder (C#, VB.NET)
But if you need to search for items in multiple folders or subfolders you may consider using the AdvancedSearch method of the Application class instead. The key benefits of using the AdvancedSearch method in Outlook are:

*

*The search is performed in another thread. You don't need to run another thread manually since the AdvancedSearch method runs it automatically in the background.

*Possibility to search for any item types: mail, appointment, calendar, notes etc. in any location, i.e. beyond the scope of a certain folder. The Restrict and Find/FindNext methods can be applied to a particular Items collection (see the Items property of the Folder class in Outlook).

*Full support for DASL queries (custom properties can be used for searching too). To improve the search performance, Instant Search keywords can be used if Instant Search is enabled for the store (see the IsInstantSearchEnabled property of the Store class).

*You can stop the search process at any moment using the Stop method of the Search class.

See Advanced search in Outlook programmatically: C#, VB.NET for more information.


text:
Q: How to detect overlay window has been hidden in Android 12 One of the major changes in Android 12 is App Overlay Controls.
This feature allows you to hide the overlay window (window type is TYPE_APPLICATION_OVERLAY).
The details are summarized very clearly in this article.
I think it is a very innovative feature.
However, there is one thing I am having trouble with this feature.
I don't know how to detect that the overlay window itself is hidden.
I've created a sample that shows the overlay window and an app that hides the overlay, and I've tested the various callbacks that the overlay window receives, but I couldn't detected that the overlay window itself is hidden.
If anyone has a solution, please let me know.
Thanks.


text:
Q: Unable to use Microsoft.Web.Helpers in Razor view vbhtml file I want to use the Linkshare helper in the Microsoft.Web.Helpers dll. I added the reference to my project but if attempt to use it in the vbhtml file Visual studio underlines it with a blue squiggly and tells me it is inaccessible blah blah. I even added references to those webmatrix dlls as described here: http://hadsy.net/2011/01/19/ASPNETMVC3MicrosoftWebHelpersErrorTheTypeOrNamespaceNameSimpleMembershipProviderCouldNotBeFound.aspx
How can i get the linkshare and other helpers to work?

A: You also need to add a reference to the assembly in web.config, under Namespaces
i.e;
<pages controlRenderingCompatibilityVersion="3.5" clientIDMode="AutoID">
    <namespaces>
        <clear/>
        <add namespace="System.Web.Mvc"/>
        <add namespace="System.Web.Mvc.Ajax"/>
        ...
        <add namespace="Microsoft.Web.Helpers"/>

A: the solution  is to build the project after adding the assembly reference
then I was able to use the linkshare helper


text:
Q: IF statement returns TRUE and/or FALSE but not calculation =IF([@[Total 2012]]<>0,([@[Total 2013]]/[@[Total 2012]]*100),100,IF(AND([@[Total 2012]]=0,[@[Total 2013]]=0),0,0))

A: You're formula does not work - it has one parameter too much:
=IF(
1:   [@[Total 2012]]<>0,
2:   ([@[Total 2013]]/[@[Total 2012]]*100),
3:   100,
4:   IF(AND([@[Total 2012]]=0,[@[Total 2013]]=0),0,0)
)

IF needs only three - condition, result when true, result when false. So need to change it to what you need.
Also note, that your 4th parameter will always return 0, as the nested IF formula there has 0 for both, true and false part.


text:
Q: Exception in thread "main" org.openqa.selenium.InvalidElementStateException: Here I am opening a Chrome browser and trying to send input string to the WebElement search text box:
// search for a text in Google
WebDriverWait wait3 = new WebDriverWait(driver1,30);
WebElement textBox = wait3.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//input[@class = 'gsfi']")));

Error Observed for Chrome
Exception in thread "main" org.openqa.selenium.InvalidElementStateException: invalid element state
(Session info: chrome=62.0.3202.94)
(Driver info: chromedriver=2.33.506120 (e3e53437346286c0bc2d2dc9aa4915ba81d9023f),platform=Windows NT 10.0.16299 x86) (WARNING: The server did not provide any stacktrace information)
Command duration or timeout: 0 milliseconds
Build info: version: '3.6.0', revision: '6fbf3ec767', time: '2017-09-27T16:15:26.402Z'
System info: host: 'ADMIN-PC', ip: '192.168.1.5', os.name: 'Windows 10', os.arch: 'x86', os.version: '10.0', java.version: '1.8.0_151'
Driver info: org.openqa.selenium.chrome.ChromeDriver
Capabilities [{mobileEmulationEnabled=false, hasTouchScreen=false, platform=XP, acceptSslCerts=true, webStorageEnabled=true, browserName=chrome, takesScreenshot=true, javascriptEnabled=true, platformName=XP, setWindowRect=true, unexpectedAlertBehaviour=, applicationCacheEnabled=false, rotatable=false, networkConnectionEnabled=false, chrome={chromedriverVersion=2.33.506120 (e3e53437346286c0bc2d2dc9aa4915ba81d9023f), userDataDir=C:\Users\admin\AppData\Local\Temp\scoped_dir15624_26281}, takesHeapSnapshot=true, pageLoadStrategy=normal, unhandledPromptBehavior=, databaseEnabled=false, handlesAlerts=true, version=62.0.3202.94, browserConnectionEnabled=false, nativeEvents=true, locationContextEnabled=true, cssSelectorsEnabled=true}]
Session ID: d4178e5e05d8efc8800ec1e1ceb1f63a
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
    at java.lang.reflect.Constructor.newInstance(Unknown Source)
    at org.openqa.selenium.remote.ErrorHandler.createThrowable(ErrorHandler.java:214)
    at org.openqa.selenium.remote.ErrorHandler.throwIfResponseFailed(ErrorHandler.java:166)
    at org.openqa.selenium.remote.http.JsonHttpResponseCodec.reconstructValue(JsonHttpResponseCodec.java:40)
    at org.openqa.selenium.remote.http.AbstractHttpResponseCodec.decode(AbstractHttpResponseCodec.java:82)
    at org.openqa.selenium.remote.http.AbstractHttpResponseCodec.decode(AbstractHttpResponseCodec.java:45)
    at org.openqa.selenium.remote.HttpCommandExecutor.execute(HttpCommandExecutor.java:164)
    at org.openqa.selenium.remote.service.DriverCommandExecutor.execute(DriverCommandExecutor.java:83)
    at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:586)
    at org.openqa.selenium.remote.RemoteWebElement.execute(RemoteWebElement.java:279)
    at org.openqa.selenium.remote.RemoteWebElement.sendKeys(RemoteWebElement.java:100)
    at packageFF.browserAutomation.main(browserAutomation.java:76)

A: By.xpath("//input[@class = 'gsfi']") is not found through xpath because it is not opened successfully. You can set sleep time also.
And if possible, you can use id or class instead of xpath.

A: You're searching for input elements that have the class 'gsfi'. A quick search through the Google homepage html returns three input elements that have this class, two of them are hidden. The field that you need to send text to has an id, so why not use the id?
// The input element you need
<input class="gsfi" id="lst-ib" .../>

// Locate element by id
WebDriverWait wait = new WebDriverWait(driver1, 30);
WebElement textBox = wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("list-ib")));


text:
Q: Python: Unresolved reference in try catch I'm trying to use accumulator (variable) inside the except/else:
Updated code
classifier = UtteranceClassifier()

sc = SparkContext("local[2]")

offensives = sc.accumulator(0)
total = sc.accumulator(0)

# Create Spark session
def get_spark_session():
    return SparkSession \
        .builder \
        .master(master) \
        .appName(appName) \
        .getOrCreate()

def classify(utterance):
    global offensives
    global total

    total += 1
    print("total: ", total)
    try:
        return classifier.classify(utterance)
    except Exception:
        offensives += 1
        print("offensives: ", offensives)

def main():
    spark: SparkSession = get_spark_session()

    ....

    # Clean text
    df_clean = df.select((f.lower(f.regexp_replace('utterance', "[^a-zA-Z\\s]", "")).alias('utterance_text')))

    # Tokenize text
    tokenizer = Tokenizer(inputCol='utterance_text', outputCol='utterance_token')
    df_words_token = tokenizer.transform(df_clean).select('utterance_token')

    # Remove stop words
    remover = StopWordsRemover(inputCol='utterance_token', outputCol='utterance_clean')
    df_no_stopwords = remover.transform(df_words_token).select('utterance_clean')
    #df_no_stopwords.show(truncate=False)

    classify_udf = f.udf(classify, StringType())
    # Classify utterance
    df_no_stopwords = df_no_stopwords.withColumn("offensive", classify_udf(f.col('utterance_clean')))
    df_no_stopwords.show(truncate=False)

    print("Offensives: ", offensives.value)
    print("Total: ", total.value)

I have such compilation error on both variables total & offensives:

Inspection info: this inspection detects names that should resolved but don't...

A: Python doesn't have a ++ operator. You could you the += operator instead:
def classify(utterance):
    try:
        classifier.classify(utterance)
    except Exception:
        num_of_offensive += 1
    else:
        total += 1

A: You are confusing the if/else with try/except.  Do it like this:
    def classify(utterance):
        try:
            classifier.classify(utterance)
            total += 1
        except:
            num_of_offensive += 1


text:
Q: Shadows on toolbar and menu not showing in duplicate layout I encountered a weird situation that one of the activity layout (design) acts differently!!To check the error I Just copied another activity with working design and link that activity!! But to my surprise, the copied activity layout design changed, which is working before! I am attaching the images for reference!!

*

*Activity that Works fine here

*The activity copied and created another activity and linked
Code of the activity:
@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Fabric.with(this, new Crashlytics());
        setContentView(R.layout.activity_topup_method);
        toolbar = (Toolbar) findViewById(R.id.tool_bar);
        setSupportActionBar(toolbar);
        prefs = new PreferenceHelper(TopupOperators.this);
        topup = (LinearLayout)findViewById(R.id.topup);
        eload  = (LinearLayout) findViewById(R.id.eload);
        check = new CheckInterNetConnection(TopupOperators.this);
        isInternetPresent = check.isConnectingToInternet();
        topup.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                Intent intent = new Intent(TopupOperators.this, TopupAll.class);
                intent.putExtra("mode", "topup");
                startActivity(intent);
            }
        });
        eload.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                Intent intent = new Intent(TopupOperators.this, TopupAll.class);
                intent.putExtra("mode", "eload");
                startActivity(intent);
            }
        });
    }

----Both the activity has same code---
Layout file:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#fff">
    <include
        android:id="@+id/tool_bar"
        layout="@layout/tool_bar"
        ></include>
    <ProgressBar
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/progressBar"
        android:layout_centerInParent="true"
        android:visibility="gone"/>

    <ImageView
        android:id="@+id/zigzag_bottom"
        android:layout_width="match_parent"
        android:layout_below="@+id/mylayout"
        android:layout_height="18dp"
        android:adjustViewBounds="true"
        android:scaleType="fitXY"
        android:src="@drawable/zigzag"/>

    <RelativeLayout
        android:id="@+id/mylayout"
        android:background="@color/colorPrimary"
        android:layout_width="match_parent"
        android:layout_height="80dp"
        android:layout_below="@+id/tool_bar"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true">

        <TextView
            android:text="SELECT RECHARGE METHOD"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentBottom="true"
            android:layout_centerHorizontal="true"
            android:layout_marginBottom="22dp"
            android:id="@+id/textView"
            android:textSize="18sp"
            android:textColor="#fff"
            android:textStyle="normal|bold" />
    </RelativeLayout>

    <LinearLayout
        android:id="@+id/eload"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="33dp"
        android:background="@drawable/gridbackground"
        android:orientation="vertical"
        android:src="@drawable/voucher"
        android:padding="5dp"
        android:layout_below="@+id/topup"
        android:layout_centerHorizontal="true">

        <de.hdodenhof.circleimageview.CircleImageView
            xmlns:app="http://schemas.android.com/apk/res-auto"
            android:id="@+id/grid_item_image2"
            android:layout_width="95dp"
            android:src="@drawable/eload"
            android:layout_height="95dp"/>
        <TextView
            android:id="@+id/grid_item_title2"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="5dp"
            android:gravity="center"
            android:text="E-load"
            android:maxLines="2"
            android:ellipsize="marquee"
            android:textSize="15sp"
            android:textStyle="normal|bold" />

    </LinearLayout>

    <LinearLayout
        android:id="@+id/topup"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="16dp"
        android:background="@drawable/gridbackground"
        android:orientation="vertical"
        android:padding="5dp"
        android:layout_below="@+id/zigzag_bottom"
        android:layout_alignLeft="@+id/eload"
        android:layout_alignStart="@+id/eload">

        <de.hdodenhof.circleimageview.CircleImageView
            xmlns:app="http://schemas.android.com/apk/res-auto"
            android:id="@+id/grid_item_image1"
            android:layout_width="95dp"
            android:layout_height="95dp"
            android:src="@drawable/voucher"/>
        <TextView
            android:id="@+id/grid_item_title1"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="5dp"
            android:gravity="center"
            android:maxLines="2"
            android:ellipsize="marquee"
            android:textSize="15sp"
            android:textStyle="normal|bold"
            android:text="Voucher" />

    </LinearLayout>

Please help:
MANIFEST:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    package="com.mobeeloadpartner">

    <uses-permission android:name="android.permission.BLUETOOTH" />
    <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
    <uses-permission android:name="android.permission.INTERNET"/>

    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.INSTALL_PACKAGES" />
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:screenOrientation="portrait"
        android:theme="@style/AppTheme">
        <activity
            android:label="@string/app_name"
            android:screenOrientation="portrait"
            android:name=".Splashscreen">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name=".DeviceVerification"
            android:screenOrientation="portrait"
            android:label="@string/deviceVerification" >
        </activity>
        <activity
            android:name=".TopupList"
            android:screenOrientation="portrait"
            android:label="Mobile Topup" >
        </activity>
        <activity
            android:name=".Pinverification"
            android:screenOrientation="portrait"
            android:label="@string/pinVerification" >
        </activity>
        <activity
            android:name=".CouponRedeem"
            android:screenOrientation="portrait"
            android:label="Coupon Redeem" >
        </activity>

        <activity
            android:name=".MainActivity"
            android:launchMode="singleTask"
            android:screenOrientation="portrait"
            android:label="@string/app_name" >
        </activity>
        <activity
            android:name=".Topup"
            android:hardwareAccelerated="false"
            android:screenOrientation="portrait"
            android:label="@string/topupTab" >
        </activity>
        <activity
            android:name=".TopupAll"
            android:hardwareAccelerated="false"
            android:screenOrientation="portrait"
            android:label="@string/topupTab" >
        </activity>
        <activity
            android:name=".TopupOperators"
            android:hardwareAccelerated="false"
            android:screenOrientation="portrait"
            android:label="@string/topupTab" >
        </activity>
        <activity
            android:name=".RechargeActivity"
            android:screenOrientation="portrait"
            android:label="@string/rechargeTab" >
        </activity>
        <activity
            android:name=".EloadActivity1"
            android:windowSoftInputMode="adjustPan"
            android:screenOrientation="portrait"
            android:label="@string/erechargeTab" >
        </activity>

        <activity
            android:name=".BankReport"
            android:windowSoftInputMode="adjustPan"
            android:label="Status" >
        </activity>
        <activity
            android:name=".SettingsActivity"
            android:screenOrientation="portrait"
            android:label="@string/settings" >
        </activity>
        <activity
            android:name=".Earnings"
            android:screenOrientation="portrait"
            android:label="@string/earnings_redem" >
        </activity>
        <activity
            android:name=".BankInCash"
            android:screenOrientation="portrait"
            android:label="@string/bank_deposit" >
        </activity>
        <activity
            android:name=".TransactionsActivity"
            android:screenOrientation="portrait"
            android:label="@string/transactions" >
        </activity>
        <activity
            android:name=".BankActivity"
            android:screenOrientation="portrait"
            android:label="@string/bankactivity" >
        </activity>
        <activity
            android:name=".PrintActivity"
            android:screenOrientation="portrait"
            android:label="Print POS" >
        </activity>
        <activity
            android:name=".PrintBluetooth"
            android:screenOrientation="portrait"
            android:label="Print Bluetooth" >
        </activity>
        <activity
            android:name=".Transactionstatus"
            android:screenOrientation="portrait"
            android:label="Transaction Status" >
        </activity>
        <activity
            android:name=".InternationalCountry"
            android:screenOrientation="portrait"
            android:label="International Topup" >
        </activity>

        <activity
            android:name=".InternationalZone"
            android:screenOrientation="portrait"
            android:label="International Topup" >
        </activity>

        <activity
            android:name=".InternationalOperators"
            android:screenOrientation="portrait"
            android:label="International Topup" >
        </activity>
        <activity
            android:name=".DthList"
            android:screenOrientation="portrait"
            android:label="DTH" >
        </activity>
        <activity
            android:name=".DTHRecharge"
            android:screenOrientation="portrait"
            android:windowSoftInputMode="adjustPan"
            android:label="DTH Recharge" >
        </activity>
        <activity
            android:name=".InternationalTopup"
            android:windowSoftInputMode="adjustPan"
            android:screenOrientation="portrait"
            android:label="International Topup" >
        </activity>
        <activity
            android:name=".BillPaymentServices"
            android:screenOrientation="portrait"
            android:label="Bill Payment" >
        </activity>
        <activity
            android:name=".BillPaymentType"
            android:screenOrientation="portrait"
            android:label="Bill Payment" >
        </activity>
        <activity
            android:name=".BillPaymentOperators"
            android:screenOrientation="portrait"
            android:label="Bill Payment" >
        </activity>
        <activity
            android:name=".BillPaymentRecharge"
            android:screenOrientation="portrait"
            android:label="Bill Payment" >
        </activity>

        <activity
            android:name=".BillPaymentVVP"
            android:screenOrientation="portrait"
            android:label="Bill Payment" >
        </activity>
        <activity
            android:name=".Login"
            android:screenOrientation="portrait"
            android:label="Login" >
        </activity>
        <activity
            android:name=".BillPaymentold"
            android:screenOrientation="portrait"
            android:label="Bill Payment" >
        </activity>

        <activity
            android:name=".BillPaymentFVV"
            android:screenOrientation="portrait"
            android:label="Bill Payment" >
        </activity>

        <activity
            android:name=".BillPaymentVVR"
            android:screenOrientation="portrait"
            android:label="Bill Payment" >
        </activity>
        <activity
            android:name=".ComingSoon"
            android:screenOrientation="portrait"
            android:label="Coming Soon" >
        </activity>
        <activity
            android:name=".PaperRequest"
            android:screenOrientation="portrait"
            android:label="Paper Request" >
        </activity>
        <activity
            android:name=".BillpaymentCountry"
            android:screenOrientation="portrait"
            android:label="Bill Payment" >
        </activity>
        <activity
            android:name=".GlobalActivity"
            android:screenOrientation="portrait"
            android:label="International Payments" >
        </activity>
        <activity
            android:name=".VoucherActivity"
            android:screenOrientation="portrait"
            android:label="Voucher Printing" >
        </activity>
        <activity
            android:name=".FundTransferHistory"
            android:screenOrientation="portrait"
            android:label="Fund Transfer History" >
        </activity>
        <activity
            android:name=".TransactionStatusBT"
            android:screenOrientation="portrait"
            android:label="Transaction Status" >
        </activity>
        <activity
            android:name=".SalesReport"
            android:screenOrientation="portrait"
            android:label="Sales Report" >
        </activity>
        <activity
            android:name=".SalesReportPOS"
            android:screenOrientation="portrait"
            android:label="Sales Report" >
        </activity>

        <activity
            android:name=".TransactionStatusPOS"
            android:screenOrientation="portrait"
            android:label="Transaction Status" >
        </activity>

        <activity android:name=".DeviceListActivity"
            android:label="@string/select_device"
            android:theme="@android:style/Theme.Dialog"
            android:configChanges="orientation|keyboardHidden" />

        <service android:name=".MyFirebaseMessagingService">
            <intent-filter>
                <action android:name="com.google.firebase.MESSAGING_EVENT" />
            </intent-filter>
        </service>
        <service android:name=".FirebaseIDService">
            <intent-filter>
                <action android:name="com.google.firebase.INSTANCE_ID_EVENT" />
            </intent-filter>
        </service>
        <meta-data
            android:name="io.fabric.ApiKey"
            android:value="xxxxxxx"
            />
    </application>

</manifest>

A: Finally, able to get what the issue!
android:hardwareAccelerated="false"

This line in the manifest was making the issue. removing the line solved the issue!! In Android developer docs, it is saying that they may affect some views!


text:
Q: ES Lint throwing no-unused-vars error on constructor variable I have a component that looks like this:
class NavPane extends Component {
  constructor(props) {
    super(props);
    let lastX = 0;
  }
  NavOnTouchStart = (e) => {
    this.lastX = e.touches[0].clientX;
  }
  NavOnTouchMove = (e) => {
    const currentX = e.touches[0].clientX;
    if (currentX > this.lastX + 10) {
      this.props.toggle();
    }
    this.lastX = currentX;
  }
  render() {
    return (
      <Collapse
        ...
      </Collapse>
    );
  }
}

export default onClickOutside(NavPane);

This runs fine when executed but ES Lint doesn't seem to agree. It keeps throwing the following error on the variable lastX:

21:9   error  'lastX' is assigned a value but never used
  no-unused-vars

Could someone help me understand what's going on here? I do realize that let and const are scoped to the block the variable is defined in which is why it's throwing an error since I'm not using it within the constructor. However, ES Lint also cribs when I use var instead.

A: Try this:
  constructor(props) {
    super(props);
    this.lastX = 0;
  }


text:
Q: jQuery Ajax retrieves either "success" or "reload" - testing for each? i'm rather new to ajax. However I've gotten quite far.
$.ajax({
        url: loadUrl,
        dataType: "html",
        timeout: 5000,
        cache: false,
        // async: false,
        success: function(html,textStatus) {
            $("div." + targetBox).html(html);
            console.log(textStatus);

If this function is called a div container on my page gets updated with the following html coming from the server as a json string.
'{"status":"reload", "data":"/ajax/mowl/1/comments"}'

the backend developer says, the status could either be "success" or "reload".
If status success comes in I simply want to show the data as a message.
If status reload comes in I want to reload the current div with the url passed in the data.
So right now when triggering this ajax function my div container simply gets inserted this '{"status":"reload", "data":"/ajax/mowl/1/comments"}' message as html. However I don't want that but rather want to check if the status coming with this is "success" or "reload" and then react to it.
Any idea how to do so?

A: your datatype should be JSON dataType: json,so:
url: loadUrl,
dataType: json,
...
success: function(data) {
if(data.succes == "reload"){
 // some AJAX here that gets the HTMl from data.data (in this case '/ajax/mowl/1/comments')
$("div." + targetBox).html(data.data);
 ...

here data in an object with the 'status' and 'data' elements, that you can access
this script will put the URL in the DIV
PS take a look at: http://api.jquery.com/jQuery.getJSON/


text:
Q: Screen refresh/display problem in Xubuntu 14.04 I have just installed Xubuntu 14.04 as a dual boot on a desk top (Pentium R 4 CPU, 2.66 GHZ, 2G RAM) running XP home edition. In some situations when in Xubuntu I am having what seem to be screen refresh problems.

*

*When I open File Manager or Settings Manager the text names of various apps display but most of the icons do not. Moving the mouse over an app name generally causes the icon to appear, but it often vanishes once the mouse pointer is moved. This issue occurs irrespective of the view setting.

Icons appear fine in the menu that comes up when I right click in the desktop, and in the menu that comes up when I click the mouse icon at top left.

*

*What I suspect is a related issue. In Abiword text sometimes fades, disappears or does not display immediately when I type, or text of the whole document fades. It then comes back or darkens if I left click a few times on the text. If I scroll through a document the text often fades and may remain faded until I left click a few times.

A: I went to Settings > Appearance > Fonts > Rendering
changed Sub-pixel order to: None
This solved the problem for me.

A: Maybe was the share memory with video ram. Take a look in the /etc/X11/xorg.conf (in 16.04 is a directory /usr/share/X11/xorg.conf.d/). In "Section 'Device'" search for "VideoRam" and change the number for a correctly information of your shared ram with your video onboard.
Section "Device"
  Identifier "Generic Video Card"
    VendorName  "Silicon Integrated Systems [SiS]"
        BoardName   "771/671 PCIE VGA Display Adapter"
    Busid "PCI:1:0:0"
    Driver "vesa"
    Screen 0
        Option "UseFBDev" "true"
        Option "DPMS"
        Option "ShadowFB"
        Option "MaxXFBMem"
        VideoRam 128000
        Option "RenderAccel" "true"
        Option "AllowGLXWithComposite" "true"
        Option "backingstore" "true"
        Option "AddARGBGLXVisuals" "True"

If "VideoRam" not to exist, try to create.


text:
Q: symbolic link not created All my docs are in:
/Users/Joe/Documents/Mydocs

I want to put them on dropbox through symbolic link so I created this empty folder:
/Users/Joe/Dropbox/Mydocs

Then used this command to create a symbolic link:
ls -s /Users/Joe/Documents/Mydocs /Users/Joe/Dropbox/Mydocs

The destination folder is still empty, what can I do to properly make the link?

A: As Vincent points out, the proper command is ln -s, not ls -s. In addition to that, ln will throw an error if the target of the link (in this case, the Mydocs folder in Dropbox) already exists.
The proper way to do this is to delete /Users/Joe/Dropbox/Mydocs, then run ln -s /Users/Joe/Documents/Mydocs /Users/Joe/Dropbox/Mydocs.

A: Your command is wrong.
It is not ls -s, but ln -s